min.js 1.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872
  1. /**
  2. * @author Richard Davey <rich@photonstorm.com>
  3. * @copyright 2014 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.0.7 "Amadicia" - Built: Fri Jul 18 2014 12:35:30
  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
  22. * and my love of framework development originate.
  23. *
  24. * Follow development at http://phaser.io and on our forum
  25. *
  26. * "If you want your children to be intelligent, read them fairy tales."
  27. * "If you want them to be more intelligent, read them more fairy tales."
  28. * -- Albert Einstein
  29. */
  30. /**
  31. * @author Mat Groves http://matgroves.com/ @Doormat23
  32. */
  33. (function(){
  34. var root = this;
  35. /**
  36. * @author Mat Groves http://matgroves.com/ @Doormat23
  37. */
  38. /**
  39. * @module PIXI
  40. */
  41. var PIXI = PIXI || {};
  42. /*
  43. *
  44. * This file contains a lot of pixi consts which are used across the rendering engine
  45. * @class Consts
  46. */
  47. PIXI.WEBGL_RENDERER = 0;
  48. PIXI.CANVAS_RENDERER = 1;
  49. // useful for testing against if your lib is using pixi.
  50. PIXI.VERSION = "v1.6.1";
  51. // the various blend modes supported by pixi
  52. PIXI.blendModes = {
  53. NORMAL:0,
  54. ADD:1,
  55. MULTIPLY:2,
  56. SCREEN:3,
  57. OVERLAY:4,
  58. DARKEN:5,
  59. LIGHTEN:6,
  60. COLOR_DODGE:7,
  61. COLOR_BURN:8,
  62. HARD_LIGHT:9,
  63. SOFT_LIGHT:10,
  64. DIFFERENCE:11,
  65. EXCLUSION:12,
  66. HUE:13,
  67. SATURATION:14,
  68. COLOR:15,
  69. LUMINOSITY:16
  70. };
  71. // the scale modes
  72. PIXI.scaleModes = {
  73. DEFAULT:0,
  74. LINEAR:0,
  75. NEAREST:1
  76. };
  77. // used to create uids for various pixi objects..
  78. PIXI._UID = 0;
  79. if(typeof(Float32Array) != 'undefined')
  80. {
  81. PIXI.Float32Array = Float32Array;
  82. PIXI.Uint16Array = Uint16Array;
  83. }
  84. else
  85. {
  86. PIXI.Float32Array = Array;
  87. PIXI.Uint16Array = Array;
  88. }
  89. // interaction frequency
  90. PIXI.INTERACTION_FREQUENCY = 30;
  91. PIXI.AUTO_PREVENT_DEFAULT = true;
  92. PIXI.RAD_TO_DEG = 180 / Math.PI;
  93. PIXI.DEG_TO_RAD = Math.PI / 180;
  94. PIXI.dontSayHello = false;
  95. PIXI.sayHello = function (type)
  96. {
  97. if(PIXI.dontSayHello)return;
  98. if ( navigator.userAgent.toLowerCase().indexOf('chrome') > -1 )
  99. {
  100. var args = [
  101. '%c %c %c Pixi.js ' + PIXI.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ',
  102. 'background: #ff66a5',
  103. 'background: #ff66a5',
  104. 'color: #ff66a5; background: #030307;',
  105. 'background: #ff66a5',
  106. 'background: #ffc3dc',
  107. 'background: #ff66a5',
  108. 'color: #ff2424; background: #fff',
  109. 'color: #ff2424; background: #fff',
  110. 'color: #ff2424; background: #fff'
  111. ];
  112. console.log.apply(console, args);
  113. }
  114. else if (window['console'])
  115. {
  116. console.log('Pixi.js ' + PIXI.VERSION + ' - http://www.pixijs.com/');
  117. }
  118. PIXI.dontSayHello = true;
  119. };
  120. /**
  121. * @author Mat Groves http://matgroves.com/ @Doormat23
  122. */
  123. /**
  124. * The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis.
  125. *
  126. * @class Point
  127. * @constructor
  128. * @param x {Number} position of the point on the x axis
  129. * @param y {Number} position of the point on the y axis
  130. */
  131. PIXI.Point = function(x, y)
  132. {
  133. /**
  134. * @property x
  135. * @type Number
  136. * @default 0
  137. */
  138. this.x = x || 0;
  139. /**
  140. * @property y
  141. * @type Number
  142. * @default 0
  143. */
  144. this.y = y || 0;
  145. };
  146. /**
  147. * Creates a clone of this point
  148. *
  149. * @method clone
  150. * @return {Point} a copy of the point
  151. */
  152. PIXI.Point.prototype.clone = function()
  153. {
  154. return new PIXI.Point(this.x, this.y);
  155. };
  156. /**
  157. * Sets the point to a new x and y position.
  158. * If y is ommited, both x and y will be set to x.
  159. *
  160. * @method set
  161. * @param [x=0] {Number} position of the point on the x axis
  162. * @param [y=0] {Number} position of the point on the y axis
  163. */
  164. PIXI.Point.prototype.set = function(x, y)
  165. {
  166. this.x = x || 0;
  167. this.y = y || ( (y !== 0) ? this.x : 0 ) ;
  168. };
  169. // constructor
  170. PIXI.Point.prototype.constructor = PIXI.Point;
  171. /**
  172. * @author Mat Groves http://matgroves.com/
  173. */
  174. /**
  175. * the Rectangle object is an area defined by its position, as indicated by its top-left corner point (x, y) and by its width and its height.
  176. *
  177. * @class Rectangle
  178. * @constructor
  179. * @param x {Number} The X coord of the upper-left corner of the rectangle
  180. * @param y {Number} The Y coord of the upper-left corner of the rectangle
  181. * @param width {Number} The overall width of this rectangle
  182. * @param height {Number} The overall height of this rectangle
  183. */
  184. PIXI.Rectangle = function(x, y, width, height)
  185. {
  186. /**
  187. * @property x
  188. * @type Number
  189. * @default 0
  190. */
  191. this.x = x || 0;
  192. /**
  193. * @property y
  194. * @type Number
  195. * @default 0
  196. */
  197. this.y = y || 0;
  198. /**
  199. * @property width
  200. * @type Number
  201. * @default 0
  202. */
  203. this.width = width || 0;
  204. /**
  205. * @property height
  206. * @type Number
  207. * @default 0
  208. */
  209. this.height = height || 0;
  210. };
  211. /**
  212. * Creates a clone of this Rectangle
  213. *
  214. * @method clone
  215. * @return {Rectangle} a copy of the rectangle
  216. */
  217. PIXI.Rectangle.prototype.clone = function()
  218. {
  219. return new PIXI.Rectangle(this.x, this.y, this.width, this.height);
  220. };
  221. /**
  222. * Checks whether the x and y coordinates passed to this function are contained within this Rectangle
  223. *
  224. * @method contains
  225. * @param x {Number} The X coordinate of the point to test
  226. * @param y {Number} The Y coordinate of the point to test
  227. * @return {Boolean} Whether the x/y coords are within this Rectangle
  228. */
  229. PIXI.Rectangle.prototype.contains = function(x, y)
  230. {
  231. if(this.width <= 0 || this.height <= 0)
  232. return false;
  233. var x1 = this.x;
  234. if(x >= x1 && x <= x1 + this.width)
  235. {
  236. var y1 = this.y;
  237. if(y >= y1 && y <= y1 + this.height)
  238. {
  239. return true;
  240. }
  241. }
  242. return false;
  243. };
  244. // constructor
  245. PIXI.Rectangle.prototype.constructor = PIXI.Rectangle;
  246. PIXI.EmptyRectangle = new PIXI.Rectangle(0,0,0,0);
  247. /**
  248. * @author Adrien Brault <adrien.brault@gmail.com>
  249. */
  250. /**
  251. * @class Polygon
  252. * @constructor
  253. * @param points* {Array<Point>|Array<Number>|Point...|Number...} This can be an array of Points that form the polygon,
  254. * a flat array of numbers that will be interpreted as [x,y, x,y, ...], or the arguments passed can be
  255. * all the points of the polygon e.g. `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the
  256. * arguments passed can be flat x,y values e.g. `new PIXI.Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are
  257. * Numbers.
  258. */
  259. PIXI.Polygon = function(points)
  260. {
  261. //if points isn't an array, use arguments as the array
  262. if(!(points instanceof Array))
  263. points = Array.prototype.slice.call(arguments);
  264. //if this is a flat array of numbers, convert it to points
  265. if(typeof points[0] === 'number') {
  266. var p = [];
  267. for(var i = 0, il = points.length; i < il; i+=2) {
  268. p.push(
  269. new PIXI.Point(points[i], points[i + 1])
  270. );
  271. }
  272. points = p;
  273. }
  274. this.points = points;
  275. };
  276. /**
  277. * Creates a clone of this polygon
  278. *
  279. * @method clone
  280. * @return {Polygon} a copy of the polygon
  281. */
  282. PIXI.Polygon.prototype.clone = function()
  283. {
  284. var points = [];
  285. for (var i=0; i<this.points.length; i++) {
  286. points.push(this.points[i].clone());
  287. }
  288. return new PIXI.Polygon(points);
  289. };
  290. /**
  291. * Checks whether the x and y coordinates passed to this function are contained within this polygon
  292. *
  293. * @method contains
  294. * @param x {Number} The X coordinate of the point to test
  295. * @param y {Number} The Y coordinate of the point to test
  296. * @return {Boolean} Whether the x/y coordinates are within this polygon
  297. */
  298. PIXI.Polygon.prototype.contains = function(x, y)
  299. {
  300. var inside = false;
  301. // use some raycasting to test hits
  302. // https://github.com/substack/point-in-polygon/blob/master/index.js
  303. for(var i = 0, j = this.points.length - 1; i < this.points.length; j = i++) {
  304. var xi = this.points[i].x, yi = this.points[i].y,
  305. xj = this.points[j].x, yj = this.points[j].y,
  306. intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
  307. if(intersect) inside = !inside;
  308. }
  309. return inside;
  310. };
  311. // constructor
  312. PIXI.Polygon.prototype.constructor = PIXI.Polygon;
  313. /**
  314. * @author Chad Engler <chad@pantherdev.com>
  315. */
  316. /**
  317. * The Circle object can be used to specify a hit area for displayObjects
  318. *
  319. * @class Circle
  320. * @constructor
  321. * @param x {Number} The X coordinate of the center of this circle
  322. * @param y {Number} The Y coordinate of the center of this circle
  323. * @param radius {Number} The radius of the circle
  324. */
  325. PIXI.Circle = function(x, y, radius)
  326. {
  327. /**
  328. * @property x
  329. * @type Number
  330. * @default 0
  331. */
  332. this.x = x || 0;
  333. /**
  334. * @property y
  335. * @type Number
  336. * @default 0
  337. */
  338. this.y = y || 0;
  339. /**
  340. * @property radius
  341. * @type Number
  342. * @default 0
  343. */
  344. this.radius = radius || 0;
  345. };
  346. /**
  347. * Creates a clone of this Circle instance
  348. *
  349. * @method clone
  350. * @return {Circle} a copy of the polygon
  351. */
  352. PIXI.Circle.prototype.clone = function()
  353. {
  354. return new PIXI.Circle(this.x, this.y, this.radius);
  355. };
  356. /**
  357. * Checks whether the x, and y coordinates passed to this function are contained within this circle
  358. *
  359. * @method contains
  360. * @param x {Number} The X coordinate of the point to test
  361. * @param y {Number} The Y coordinate of the point to test
  362. * @return {Boolean} Whether the x/y coordinates are within this polygon
  363. */
  364. PIXI.Circle.prototype.contains = function(x, y)
  365. {
  366. if(this.radius <= 0)
  367. return false;
  368. var dx = (this.x - x),
  369. dy = (this.y - y),
  370. r2 = this.radius * this.radius;
  371. dx *= dx;
  372. dy *= dy;
  373. return (dx + dy <= r2);
  374. };
  375. /**
  376. * Returns the framing rectangle of the circle as a PIXI.Rectangle object
  377. *
  378. * @method getBounds
  379. * @return {Rectangle} the framing rectangle
  380. */
  381. PIXI.Circle.prototype.getBounds = function()
  382. {
  383. return new PIXI.Rectangle(this.x - this.radius, this.y - this.radius, this.width, this.height);
  384. };
  385. // constructor
  386. PIXI.Circle.prototype.constructor = PIXI.Circle;
  387. /**
  388. * @author Chad Engler <chad@pantherdev.com>
  389. */
  390. /**
  391. * The Ellipse object can be used to specify a hit area for displayObjects
  392. *
  393. * @class Ellipse
  394. * @constructor
  395. * @param x {Number} The X coordinate of the center of the ellipse
  396. * @param y {Number} The Y coordinate of the center of the ellipse
  397. * @param width {Number} The half width of this ellipse
  398. * @param height {Number} The half height of this ellipse
  399. */
  400. PIXI.Ellipse = function(x, y, width, height)
  401. {
  402. /**
  403. * @property x
  404. * @type Number
  405. * @default 0
  406. */
  407. this.x = x || 0;
  408. /**
  409. * @property y
  410. * @type Number
  411. * @default 0
  412. */
  413. this.y = y || 0;
  414. /**
  415. * @property width
  416. * @type Number
  417. * @default 0
  418. */
  419. this.width = width || 0;
  420. /**
  421. * @property height
  422. * @type Number
  423. * @default 0
  424. */
  425. this.height = height || 0;
  426. };
  427. /**
  428. * Creates a clone of this Ellipse instance
  429. *
  430. * @method clone
  431. * @return {Ellipse} a copy of the ellipse
  432. */
  433. PIXI.Ellipse.prototype.clone = function()
  434. {
  435. return new PIXI.Ellipse(this.x, this.y, this.width, this.height);
  436. };
  437. /**
  438. * Checks whether the x and y coordinates passed to this function are contained within this ellipse
  439. *
  440. * @method contains
  441. * @param x {Number} The X coordinate of the point to test
  442. * @param y {Number} The Y coordinate of the point to test
  443. * @return {Boolean} Whether the x/y coords are within this ellipse
  444. */
  445. PIXI.Ellipse.prototype.contains = function(x, y)
  446. {
  447. if(this.width <= 0 || this.height <= 0)
  448. return false;
  449. //normalize the coords to an ellipse with center 0,0
  450. var normx = ((x - this.x) / this.width),
  451. normy = ((y - this.y) / this.height);
  452. normx *= normx;
  453. normy *= normy;
  454. return (normx + normy <= 1);
  455. };
  456. /**
  457. * Returns the framing rectangle of the ellipse as a PIXI.Rectangle object
  458. *
  459. * @method getBounds
  460. * @return {Rectangle} the framing rectangle
  461. */
  462. PIXI.Ellipse.prototype.getBounds = function()
  463. {
  464. return new PIXI.Rectangle(this.x - this.width, this.y - this.height, this.width, this.height);
  465. };
  466. // constructor
  467. PIXI.Ellipse.prototype.constructor = PIXI.Ellipse;
  468. /**
  469. * @author Mat Groves http://matgroves.com/ @Doormat23
  470. */
  471. /**
  472. * The Matrix class is now an object, which makes it a lot faster,
  473. * here is a representation of it :
  474. * | a | b | tx|
  475. * | c | d | ty|
  476. * | 0 | 0 | 1 |
  477. *
  478. * @class Matrix
  479. * @constructor
  480. */
  481. PIXI.Matrix = function()
  482. {
  483. this.a = 1;
  484. this.b = 0;
  485. this.c = 0;
  486. this.d = 1;
  487. this.tx = 0;
  488. this.ty = 0;
  489. };
  490. /**
  491. * Creates a pixi matrix object based on the array given as a parameter
  492. *
  493. * @method fromArray
  494. * @param array {Array} The array that the matrix will be filled with
  495. */
  496. PIXI.Matrix.prototype.fromArray = function(array)
  497. {
  498. this.a = array[0];
  499. this.b = array[1];
  500. this.c = array[3];
  501. this.d = array[4];
  502. this.tx = array[2];
  503. this.ty = array[5];
  504. };
  505. /**
  506. * Creates an array from the current Matrix object
  507. *
  508. * @method toArray
  509. * @param transpose {Boolean} Whether we need to transpose the matrix or not
  510. * @return {Array} the newly created array which contains the matrix
  511. */
  512. PIXI.Matrix.prototype.toArray = function(transpose)
  513. {
  514. if(!this.array) this.array = new Float32Array(9);
  515. var array = this.array;
  516. if(transpose)
  517. {
  518. array[0] = this.a;
  519. array[1] = this.c;
  520. array[2] = 0;
  521. array[3] = this.b;
  522. array[4] = this.d;
  523. array[5] = 0;
  524. array[6] = this.tx;
  525. array[7] = this.ty;
  526. array[8] = 1;
  527. }
  528. else
  529. {
  530. array[0] = this.a;
  531. array[1] = this.b;
  532. array[2] = this.tx;
  533. array[3] = this.c;
  534. array[4] = this.d;
  535. array[5] = this.ty;
  536. array[6] = 0;
  537. array[7] = 0;
  538. array[8] = 1;
  539. }
  540. return array;
  541. };
  542. PIXI.identityMatrix = new PIXI.Matrix();
  543. PIXI.determineMatrixArrayType = function() {
  544. return (typeof Float32Array !== 'undefined') ? Float32Array : Array;
  545. };
  546. /**
  547. * The Matrix2 class will choose the best type of array to use between
  548. * a regular javascript Array and a Float32Array if the latter is available
  549. *
  550. * @class Matrix2
  551. * @constructor
  552. */
  553. PIXI.Matrix2 = PIXI.determineMatrixArrayType();
  554. /**
  555. * @author Mat Groves http://matgroves.com/ @Doormat23
  556. */
  557. /**
  558. * The base class for all objects that are rendered on the screen.
  559. * This is an abstract class and should not be used on its own rather it should be extended.
  560. *
  561. * @class DisplayObject
  562. * @constructor
  563. */
  564. PIXI.DisplayObject = function()
  565. {
  566. /**
  567. * The coordinate of the object relative to the local coordinates of the parent.
  568. *
  569. * @property position
  570. * @type Point
  571. */
  572. this.position = new PIXI.Point();
  573. /**
  574. * The scale factor of the object.
  575. *
  576. * @property scale
  577. * @type Point
  578. */
  579. this.scale = new PIXI.Point(1,1);//{x:1, y:1};
  580. /**
  581. * The pivot point of the displayObject that it rotates around
  582. *
  583. * @property pivot
  584. * @type Point
  585. */
  586. this.pivot = new PIXI.Point(0,0);
  587. /**
  588. * The rotation of the object in radians.
  589. *
  590. * @property rotation
  591. * @type Number
  592. */
  593. this.rotation = 0;
  594. /**
  595. * The opacity of the object.
  596. *
  597. * @property alpha
  598. * @type Number
  599. */
  600. this.alpha = 1;
  601. /**
  602. * The visibility of the object.
  603. *
  604. * @property visible
  605. * @type Boolean
  606. */
  607. this.visible = true;
  608. /**
  609. * This is the defined area that will pick up mouse / touch events. It is null by default.
  610. * 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)
  611. *
  612. * @property hitArea
  613. * @type Rectangle|Circle|Ellipse|Polygon
  614. */
  615. this.hitArea = null;
  616. /**
  617. * This is used to indicate if the displayObject should display a mouse hand cursor on rollover
  618. *
  619. * @property buttonMode
  620. * @type Boolean
  621. */
  622. this.buttonMode = false;
  623. /**
  624. * Can this object be rendered
  625. *
  626. * @property renderable
  627. * @type Boolean
  628. */
  629. this.renderable = false;
  630. /**
  631. * [read-only] The display object container that contains this display object.
  632. *
  633. * @property parent
  634. * @type DisplayObjectContainer
  635. * @readOnly
  636. */
  637. this.parent = null;
  638. /**
  639. * [read-only] The stage the display object is connected to, or undefined if it is not connected to the stage.
  640. *
  641. * @property stage
  642. * @type Stage
  643. * @readOnly
  644. */
  645. this.stage = null;
  646. /**
  647. * [read-only] The multiplied alpha of the displayObject
  648. *
  649. * @property worldAlpha
  650. * @type Number
  651. * @readOnly
  652. */
  653. this.worldAlpha = 1;
  654. /**
  655. * [read-only] Whether or not the object is interactive, do not toggle directly! use the `interactive` property
  656. *
  657. * @property _interactive
  658. * @type Boolean
  659. * @readOnly
  660. * @private
  661. */
  662. this._interactive = false;
  663. /**
  664. * This is the cursor that will be used when the mouse is over this object. To enable this the element must have interaction = true and buttonMode = true
  665. *
  666. * @property defaultCursor
  667. * @type String
  668. *
  669. */
  670. this.defaultCursor = 'pointer';
  671. /**
  672. * [read-only] Current transform of the object based on world (parent) factors
  673. *
  674. * @property worldTransform
  675. * @type Mat3
  676. * @readOnly
  677. * @private
  678. */
  679. this.worldTransform = new PIXI.Matrix();
  680. /**
  681. * [NYI] Unknown
  682. *
  683. * @property color
  684. * @type Array<>
  685. * @private
  686. */
  687. this.color = [];
  688. /**
  689. * [NYI] Holds whether or not this object is dynamic, for rendering optimization
  690. *
  691. * @property dynamic
  692. * @type Boolean
  693. * @private
  694. */
  695. this.dynamic = true;
  696. // cached sin rotation and cos rotation
  697. this._sr = 0;
  698. this._cr = 1;
  699. /**
  700. * The area the filter is applied to like the hitArea this is used as more of an optimisation
  701. * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle
  702. *
  703. * @property filterArea
  704. * @type Rectangle
  705. */
  706. this.filterArea = null;//new PIXI.Rectangle(0,0,1,1);
  707. /**
  708. * The original, cached bounds of the object
  709. *
  710. * @property _bounds
  711. * @type Rectangle
  712. * @private
  713. */
  714. this._bounds = new PIXI.Rectangle(0, 0, 1, 1);
  715. /**
  716. * The most up-to-date bounds of the object
  717. *
  718. * @property _currentBounds
  719. * @type Rectangle
  720. * @private
  721. */
  722. this._currentBounds = null;
  723. /**
  724. * The original, cached mask of the object
  725. *
  726. * @property _currentBounds
  727. * @type Rectangle
  728. * @private
  729. */
  730. this._mask = null;
  731. this._cacheAsBitmap = false;
  732. this._cacheIsDirty = false;
  733. /*
  734. * MOUSE Callbacks
  735. */
  736. /**
  737. * A callback that is used when the users clicks on the displayObject with their mouse
  738. * @method click
  739. * @param interactionData {InteractionData}
  740. */
  741. /**
  742. * A callback that is used when the user clicks the mouse down over the sprite
  743. * @method mousedown
  744. * @param interactionData {InteractionData}
  745. */
  746. /**
  747. * A callback that is used when the user releases the mouse that was over the displayObject
  748. * for this callback to be fired the mouse must have been pressed down over the displayObject
  749. * @method mouseup
  750. * @param interactionData {InteractionData}
  751. */
  752. /**
  753. * A callback that is used when the user releases the mouse that was over the displayObject but is no longer over the displayObject
  754. * for this callback to be fired, The touch must have started over the displayObject
  755. * @method mouseupoutside
  756. * @param interactionData {InteractionData}
  757. */
  758. /**
  759. * A callback that is used when the users mouse rolls over the displayObject
  760. * @method mouseover
  761. * @param interactionData {InteractionData}
  762. */
  763. /**
  764. * A callback that is used when the users mouse leaves the displayObject
  765. * @method mouseout
  766. * @param interactionData {InteractionData}
  767. */
  768. /*
  769. * TOUCH Callbacks
  770. */
  771. /**
  772. * A callback that is used when the users taps on the sprite with their finger
  773. * basically a touch version of click
  774. * @method tap
  775. * @param interactionData {InteractionData}
  776. */
  777. /**
  778. * A callback that is used when the user touches over the displayObject
  779. * @method touchstart
  780. * @param interactionData {InteractionData}
  781. */
  782. /**
  783. * A callback that is used when the user releases a touch over the displayObject
  784. * @method touchend
  785. * @param interactionData {InteractionData}
  786. */
  787. /**
  788. * A callback that is used when the user releases the touch that was over the displayObject
  789. * for this callback to be fired, The touch must have started over the sprite
  790. * @method touchendoutside
  791. * @param interactionData {InteractionData}
  792. */
  793. };
  794. // constructor
  795. PIXI.DisplayObject.prototype.constructor = PIXI.DisplayObject;
  796. /**
  797. * [Deprecated] Indicates if the sprite will have touch and mouse interactivity. It is false by default
  798. * Instead of using this function you can now simply set the interactive property to true or false
  799. *
  800. * @method setInteractive
  801. * @param interactive {Boolean}
  802. * @deprecated Simply set the `interactive` property directly
  803. */
  804. PIXI.DisplayObject.prototype.setInteractive = function(interactive)
  805. {
  806. this.interactive = interactive;
  807. };
  808. /**
  809. * Indicates if the sprite will have touch and mouse interactivity. It is false by default
  810. *
  811. * @property interactive
  812. * @type Boolean
  813. * @default false
  814. */
  815. Object.defineProperty(PIXI.DisplayObject.prototype, 'interactive', {
  816. get: function() {
  817. return this._interactive;
  818. },
  819. set: function(value) {
  820. this._interactive = value;
  821. // TODO more to be done here..
  822. // need to sort out a re-crawl!
  823. if(this.stage)this.stage.dirty = true;
  824. }
  825. });
  826. /**
  827. * [read-only] Indicates if the sprite is globaly visible.
  828. *
  829. * @property worldVisible
  830. * @type Boolean
  831. */
  832. Object.defineProperty(PIXI.DisplayObject.prototype, 'worldVisible', {
  833. get: function() {
  834. var item = this;
  835. do
  836. {
  837. if(!item.visible)return false;
  838. item = item.parent;
  839. }
  840. while(item);
  841. return true;
  842. }
  843. });
  844. /**
  845. * Sets a mask for the displayObject. A mask is an object that limits the visibility of an object to the shape of the mask applied to it.
  846. * In PIXI a regular mask must be a PIXI.Graphics object. This allows for much faster masking in canvas as it utilises shape clipping.
  847. * To remove a mask, set this property to null.
  848. *
  849. * @property mask
  850. * @type Graphics
  851. */
  852. Object.defineProperty(PIXI.DisplayObject.prototype, 'mask', {
  853. get: function() {
  854. return this._mask;
  855. },
  856. set: function(value) {
  857. if(this._mask)this._mask.isMask = false;
  858. this._mask = value;
  859. if(this._mask)this._mask.isMask = true;
  860. }
  861. });
  862. /**
  863. * Sets the filters for the displayObject.
  864. * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer.
  865. * To remove filters simply set this property to 'null'
  866. * @property filters
  867. * @type Array An array of filters
  868. */
  869. Object.defineProperty(PIXI.DisplayObject.prototype, 'filters', {
  870. get: function() {
  871. return this._filters;
  872. },
  873. set: function(value) {
  874. if(value)
  875. {
  876. // now put all the passes in one place..
  877. var passes = [];
  878. for (var i = 0; i < value.length; i++)
  879. {
  880. var filterPasses = value[i].passes;
  881. for (var j = 0; j < filterPasses.length; j++)
  882. {
  883. passes.push(filterPasses[j]);
  884. }
  885. }
  886. // TODO change this as it is legacy
  887. this._filterBlock = {target:this, filterPasses:passes};
  888. }
  889. this._filters = value;
  890. }
  891. });
  892. /**
  893. * Set weather or not a the display objects is cached as a bitmap.
  894. * This basically takes a snap shot of the display object as it is at that moment. It can provide a performance benefit for complex static displayObjects
  895. * To remove filters simply set this property to 'null'
  896. * @property cacheAsBitmap
  897. * @type Boolean
  898. */
  899. Object.defineProperty(PIXI.DisplayObject.prototype, 'cacheAsBitmap', {
  900. get: function() {
  901. return this._cacheAsBitmap;
  902. },
  903. set: function(value) {
  904. if(this._cacheAsBitmap === value)return;
  905. if(value)
  906. {
  907. //this._cacheIsDirty = true;
  908. this._generateCachedSprite();
  909. }
  910. else
  911. {
  912. this._destroyCachedSprite();
  913. }
  914. this._cacheAsBitmap = value;
  915. }
  916. });
  917. /*
  918. * Updates the object transform for rendering
  919. *
  920. * @method updateTransform
  921. * @private
  922. */
  923. PIXI.DisplayObject.prototype.updateTransform = function()
  924. {
  925. // TODO OPTIMIZE THIS!! with dirty
  926. if(this.rotation !== this.rotationCache)
  927. {
  928. this.rotationCache = this.rotation;
  929. this._sr = Math.sin(this.rotation);
  930. this._cr = Math.cos(this.rotation);
  931. }
  932. // var localTransform = this.localTransform//.toArray();
  933. var parentTransform = this.parent.worldTransform;//.toArray();
  934. var worldTransform = this.worldTransform;//.toArray();
  935. var px = this.pivot.x;
  936. var py = this.pivot.y;
  937. var a00 = this._cr * this.scale.x,
  938. a01 = -this._sr * this.scale.y,
  939. a10 = this._sr * this.scale.x,
  940. a11 = this._cr * this.scale.y,
  941. a02 = this.position.x - a00 * px - py * a01,
  942. a12 = this.position.y - a11 * py - px * a10,
  943. b00 = parentTransform.a, b01 = parentTransform.b,
  944. b10 = parentTransform.c, b11 = parentTransform.d;
  945. worldTransform.a = b00 * a00 + b01 * a10;
  946. worldTransform.b = b00 * a01 + b01 * a11;
  947. worldTransform.tx = b00 * a02 + b01 * a12 + parentTransform.tx;
  948. worldTransform.c = b10 * a00 + b11 * a10;
  949. worldTransform.d = b10 * a01 + b11 * a11;
  950. worldTransform.ty = b10 * a02 + b11 * a12 + parentTransform.ty;
  951. this.worldAlpha = this.alpha * this.parent.worldAlpha;
  952. };
  953. /**
  954. * Retrieves the bounds of the displayObject as a rectangle object
  955. *
  956. * @method getBounds
  957. * @return {Rectangle} the rectangular bounding area
  958. */
  959. PIXI.DisplayObject.prototype.getBounds = function( matrix )
  960. {
  961. matrix = matrix;//just to get passed js hinting (and preserve inheritance)
  962. return PIXI.EmptyRectangle;
  963. };
  964. /**
  965. * Retrieves the local bounds of the displayObject as a rectangle object
  966. *
  967. * @method getLocalBounds
  968. * @return {Rectangle} the rectangular bounding area
  969. */
  970. PIXI.DisplayObject.prototype.getLocalBounds = function()
  971. {
  972. return this.getBounds(PIXI.identityMatrix);///PIXI.EmptyRectangle();
  973. };
  974. /**
  975. * Sets the object's stage reference, the stage this object is connected to
  976. *
  977. * @method setStageReference
  978. * @param stage {Stage} the stage that the object will have as its current stage reference
  979. */
  980. PIXI.DisplayObject.prototype.setStageReference = function(stage)
  981. {
  982. this.stage = stage;
  983. if(this._interactive)this.stage.dirty = true;
  984. };
  985. PIXI.DisplayObject.prototype.generateTexture = function(renderer)
  986. {
  987. var bounds = this.getLocalBounds();
  988. var renderTexture = new PIXI.RenderTexture(bounds.width | 0, bounds.height | 0, renderer);
  989. renderTexture.render(this, new PIXI.Point(-bounds.x, -bounds.y) );
  990. return renderTexture;
  991. };
  992. PIXI.DisplayObject.prototype.updateCache = function()
  993. {
  994. this._generateCachedSprite();
  995. };
  996. PIXI.DisplayObject.prototype._renderCachedSprite = function(renderSession)
  997. {
  998. this._cachedSprite.worldAlpha = this.worldAlpha;
  999. if(renderSession.gl)
  1000. {
  1001. PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession);
  1002. }
  1003. else
  1004. {
  1005. PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession);
  1006. }
  1007. };
  1008. PIXI.DisplayObject.prototype._generateCachedSprite = function()//renderSession)
  1009. {
  1010. this._cacheAsBitmap = false;
  1011. var bounds = this.getLocalBounds();
  1012. if(!this._cachedSprite)
  1013. {
  1014. var renderTexture = new PIXI.RenderTexture(bounds.width | 0, bounds.height | 0);//, renderSession.renderer);
  1015. this._cachedSprite = new PIXI.Sprite(renderTexture);
  1016. this._cachedSprite.worldTransform = this.worldTransform;
  1017. }
  1018. else
  1019. {
  1020. this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0);
  1021. }
  1022. //REMOVE filter!
  1023. var tempFilters = this._filters;
  1024. this._filters = null;
  1025. this._cachedSprite.filters = tempFilters;
  1026. this._cachedSprite.texture.render(this, new PIXI.Point(-bounds.x, -bounds.y) );
  1027. this._cachedSprite.anchor.x = -( bounds.x / bounds.width );
  1028. this._cachedSprite.anchor.y = -( bounds.y / bounds.height );
  1029. this._filters = tempFilters;
  1030. this._cacheAsBitmap = true;
  1031. };
  1032. /**
  1033. * Renders the object using the WebGL renderer
  1034. *
  1035. * @method _renderWebGL
  1036. * @param renderSession {RenderSession}
  1037. * @private
  1038. */
  1039. PIXI.DisplayObject.prototype._destroyCachedSprite = function()
  1040. {
  1041. if(!this._cachedSprite)return;
  1042. this._cachedSprite.texture.destroy(true);
  1043. // console.log("DESTROY")
  1044. // let the gc collect the unused sprite
  1045. // TODO could be object pooled!
  1046. this._cachedSprite = null;
  1047. };
  1048. PIXI.DisplayObject.prototype._renderWebGL = function(renderSession)
  1049. {
  1050. // OVERWRITE;
  1051. // this line is just here to pass jshinting :)
  1052. renderSession = renderSession;
  1053. };
  1054. /**
  1055. * Renders the object using the Canvas renderer
  1056. *
  1057. * @method _renderCanvas
  1058. * @param renderSession {RenderSession}
  1059. * @private
  1060. */
  1061. PIXI.DisplayObject.prototype._renderCanvas = function(renderSession)
  1062. {
  1063. // OVERWRITE;
  1064. // this line is just here to pass jshinting :)
  1065. renderSession = renderSession;
  1066. };
  1067. /**
  1068. * The position of the displayObject on the x axis relative to the local coordinates of the parent.
  1069. *
  1070. * @property x
  1071. * @type Number
  1072. */
  1073. Object.defineProperty(PIXI.DisplayObject.prototype, 'x', {
  1074. get: function() {
  1075. return this.position.x;
  1076. },
  1077. set: function(value) {
  1078. this.position.x = value;
  1079. }
  1080. });
  1081. /**
  1082. * The position of the displayObject on the y axis relative to the local coordinates of the parent.
  1083. *
  1084. * @property y
  1085. * @type Number
  1086. */
  1087. Object.defineProperty(PIXI.DisplayObject.prototype, 'y', {
  1088. get: function() {
  1089. return this.position.y;
  1090. },
  1091. set: function(value) {
  1092. this.position.y = value;
  1093. }
  1094. });
  1095. /**
  1096. * @author Mat Groves http://matgroves.com/ @Doormat23
  1097. */
  1098. /**
  1099. * A DisplayObjectContainer represents a collection of display objects.
  1100. * It is the base class of all display objects that act as a container for other objects.
  1101. *
  1102. * @class DisplayObjectContainer
  1103. * @extends DisplayObject
  1104. * @constructor
  1105. */
  1106. PIXI.DisplayObjectContainer = function()
  1107. {
  1108. PIXI.DisplayObject.call( this );
  1109. /**
  1110. * [read-only] The array of children of this container.
  1111. *
  1112. * @property children
  1113. * @type Array<DisplayObject>
  1114. * @readOnly
  1115. */
  1116. this.children = [];
  1117. };
  1118. // constructor
  1119. PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype );
  1120. PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer;
  1121. /**
  1122. * The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set
  1123. *
  1124. * @property width
  1125. * @type Number
  1126. */
  1127. Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'width', {
  1128. get: function() {
  1129. return this.scale.x * this.getLocalBounds().width;
  1130. },
  1131. set: function(value) {
  1132. var width = this.getLocalBounds().width;
  1133. if(width !== 0)
  1134. {
  1135. this.scale.x = value / ( width/this.scale.x );
  1136. }
  1137. else
  1138. {
  1139. this.scale.x = 1;
  1140. }
  1141. this._width = value;
  1142. }
  1143. });
  1144. /**
  1145. * The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set
  1146. *
  1147. * @property height
  1148. * @type Number
  1149. */
  1150. Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'height', {
  1151. get: function() {
  1152. return this.scale.y * this.getLocalBounds().height;
  1153. },
  1154. set: function(value) {
  1155. var height = this.getLocalBounds().height;
  1156. if(height !== 0)
  1157. {
  1158. this.scale.y = value / ( height/this.scale.y );
  1159. }
  1160. else
  1161. {
  1162. this.scale.y = 1;
  1163. }
  1164. this._height = value;
  1165. }
  1166. });
  1167. /**
  1168. * Adds a child to the container.
  1169. *
  1170. * @method addChild
  1171. * @param child {DisplayObject} The DisplayObject to add to the container
  1172. */
  1173. PIXI.DisplayObjectContainer.prototype.addChild = function(child)
  1174. {
  1175. return this.addChildAt(child, this.children.length);
  1176. };
  1177. /**
  1178. * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown
  1179. *
  1180. * @method addChildAt
  1181. * @param child {DisplayObject} The child to add
  1182. * @param index {Number} The index to place the child in
  1183. */
  1184. PIXI.DisplayObjectContainer.prototype.addChildAt = function(child, index)
  1185. {
  1186. if(index >= 0 && index <= this.children.length)
  1187. {
  1188. if(child.parent)
  1189. {
  1190. child.parent.removeChild(child);
  1191. }
  1192. child.parent = this;
  1193. this.children.splice(index, 0, child);
  1194. if(this.stage)child.setStageReference(this.stage);
  1195. return child;
  1196. }
  1197. else
  1198. {
  1199. throw new Error(child + ' The index '+ index +' supplied is out of bounds ' + this.children.length);
  1200. }
  1201. };
  1202. /**
  1203. * [NYI] Swaps the depth of 2 displayObjects
  1204. *
  1205. * @method swapChildren
  1206. * @param child {DisplayObject}
  1207. * @param child2 {DisplayObject}
  1208. * @private
  1209. */
  1210. PIXI.DisplayObjectContainer.prototype.swapChildren = function(child, child2)
  1211. {
  1212. if(child === child2) {
  1213. return;
  1214. }
  1215. var index1 = this.children.indexOf(child);
  1216. var index2 = this.children.indexOf(child2);
  1217. if(index1 < 0 || index2 < 0) {
  1218. throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.');
  1219. }
  1220. this.children[index1] = child2;
  1221. this.children[index2] = child;
  1222. };
  1223. /**
  1224. * Returns the child at the specified index
  1225. *
  1226. * @method getChildAt
  1227. * @param index {Number} The index to get the child from
  1228. */
  1229. PIXI.DisplayObjectContainer.prototype.getChildAt = function(index)
  1230. {
  1231. if(index >= 0 && index < this.children.length)
  1232. {
  1233. return this.children[index];
  1234. }
  1235. else
  1236. {
  1237. throw new Error('Supplied index does not exist in the child list, or the supplied DisplayObject must be a child of the caller');
  1238. }
  1239. };
  1240. /**
  1241. * Removes a child from the container.
  1242. *
  1243. * @method removeChild
  1244. * @param child {DisplayObject} The DisplayObject to remove
  1245. */
  1246. PIXI.DisplayObjectContainer.prototype.removeChild = function(child)
  1247. {
  1248. return this.removeChildAt( this.children.indexOf( child ) );
  1249. };
  1250. /**
  1251. * Removes a child from the specified index position in the child list of the container.
  1252. *
  1253. * @method removeChildAt
  1254. * @param index {Number} The index to get the child from
  1255. */
  1256. PIXI.DisplayObjectContainer.prototype.removeChildAt = function(index)
  1257. {
  1258. var child = this.getChildAt( index );
  1259. if(this.stage)
  1260. child.removeStageReference();
  1261. child.parent = undefined;
  1262. this.children.splice( index, 1 );
  1263. return child;
  1264. };
  1265. /**
  1266. * Removes all child instances from the child list of the container.
  1267. *
  1268. * @method removeChildren
  1269. * @param beginIndex {Number} The beginning position. Predefined value is 0.
  1270. * @param endIndex {Number} The ending position. Predefined value is children's array length.
  1271. */
  1272. PIXI.DisplayObjectContainer.prototype.removeChildren = function(beginIndex, endIndex)
  1273. {
  1274. var begin = beginIndex || 0;
  1275. var end = typeof endIndex === 'number' ? endIndex : this.children.length;
  1276. var range = end - begin;
  1277. if (range > 0 && range <= end)
  1278. {
  1279. var removed = this.children.splice(begin, range);
  1280. for (var i = 0; i < removed.length; i++) {
  1281. var child = removed[i];
  1282. if(this.stage)
  1283. child.removeStageReference();
  1284. child.parent = undefined;
  1285. }
  1286. return removed;
  1287. }
  1288. else
  1289. {
  1290. throw new Error( 'Range Error, numeric values are outside the acceptable range' );
  1291. }
  1292. };
  1293. /*
  1294. * Updates the container's childrens transform for rendering
  1295. *
  1296. * @method updateTransform
  1297. * @private
  1298. */
  1299. PIXI.DisplayObjectContainer.prototype.updateTransform = function()
  1300. {
  1301. //this._currentBounds = null;
  1302. if(!this.visible)return;
  1303. PIXI.DisplayObject.prototype.updateTransform.call( this );
  1304. if(this._cacheAsBitmap)return;
  1305. for(var i=0,j=this.children.length; i<j; i++)
  1306. {
  1307. this.children[i].updateTransform();
  1308. }
  1309. };
  1310. /**
  1311. * Retrieves the bounds of the displayObjectContainer as a rectangle object
  1312. *
  1313. * @method getBounds
  1314. * @return {Rectangle} the rectangular bounding area
  1315. */
  1316. PIXI.DisplayObjectContainer.prototype.getBounds = function(matrix)
  1317. {
  1318. if(this.children.length === 0)return PIXI.EmptyRectangle;
  1319. // TODO the bounds have already been calculated this render session so return what we have
  1320. if(matrix)
  1321. {
  1322. var matrixCache = this.worldTransform;
  1323. this.worldTransform = matrix;
  1324. this.updateTransform();
  1325. this.worldTransform = matrixCache;
  1326. }
  1327. var minX = Infinity;
  1328. var minY = Infinity;
  1329. var maxX = -Infinity;
  1330. var maxY = -Infinity;
  1331. var childBounds;
  1332. var childMaxX;
  1333. var childMaxY;
  1334. var childVisible = false;
  1335. for(var i=0,j=this.children.length; i<j; i++)
  1336. {
  1337. var child = this.children[i];
  1338. if(!child.visible)continue;
  1339. childVisible = true;
  1340. childBounds = this.children[i].getBounds( matrix );
  1341. minX = minX < childBounds.x ? minX : childBounds.x;
  1342. minY = minY < childBounds.y ? minY : childBounds.y;
  1343. childMaxX = childBounds.width + childBounds.x;
  1344. childMaxY = childBounds.height + childBounds.y;
  1345. maxX = maxX > childMaxX ? maxX : childMaxX;
  1346. maxY = maxY > childMaxY ? maxY : childMaxY;
  1347. }
  1348. if(!childVisible)
  1349. return PIXI.EmptyRectangle;
  1350. var bounds = this._bounds;
  1351. bounds.x = minX;
  1352. bounds.y = minY;
  1353. bounds.width = maxX - minX;
  1354. bounds.height = maxY - minY;
  1355. // TODO: store a reference so that if this function gets called again in the render cycle we do not have to recalculate
  1356. //this._currentBounds = bounds;
  1357. return bounds;
  1358. };
  1359. PIXI.DisplayObjectContainer.prototype.getLocalBounds = function()
  1360. {
  1361. var matrixCache = this.worldTransform;
  1362. this.worldTransform = PIXI.identityMatrix;
  1363. for(var i=0,j=this.children.length; i<j; i++)
  1364. {
  1365. this.children[i].updateTransform();
  1366. }
  1367. var bounds = this.getBounds();
  1368. this.worldTransform = matrixCache;
  1369. return bounds;
  1370. };
  1371. /**
  1372. * Sets the container's stage reference, the stage this object is connected to
  1373. *
  1374. * @method setStageReference
  1375. * @param stage {Stage} the stage that the container will have as its current stage reference
  1376. */
  1377. PIXI.DisplayObjectContainer.prototype.setStageReference = function(stage)
  1378. {
  1379. this.stage = stage;
  1380. if(this._interactive)this.stage.dirty = true;
  1381. for(var i=0,j=this.children.length; i<j; i++)
  1382. {
  1383. var child = this.children[i];
  1384. child.setStageReference(stage);
  1385. }
  1386. };
  1387. /**
  1388. * removes the current stage reference of the container
  1389. *
  1390. * @method removeStageReference
  1391. */
  1392. PIXI.DisplayObjectContainer.prototype.removeStageReference = function()
  1393. {
  1394. for(var i=0,j=this.children.length; i<j; i++)
  1395. {
  1396. var child = this.children[i];
  1397. child.removeStageReference();
  1398. }
  1399. if(this._interactive)this.stage.dirty = true;
  1400. this.stage = null;
  1401. };
  1402. /**
  1403. * Renders the object using the WebGL renderer
  1404. *
  1405. * @method _renderWebGL
  1406. * @param renderSession {RenderSession}
  1407. * @private
  1408. */
  1409. PIXI.DisplayObjectContainer.prototype._renderWebGL = function(renderSession)
  1410. {
  1411. if(!this.visible || this.alpha <= 0)return;
  1412. if(this._cacheAsBitmap)
  1413. {
  1414. this._renderCachedSprite(renderSession);
  1415. return;
  1416. }
  1417. var i,j;
  1418. if(this._mask || this._filters)
  1419. {
  1420. // push filter first as we need to ensure the stencil buffer is correct for any masking
  1421. if(this._filters)
  1422. {
  1423. renderSession.spriteBatch.flush();
  1424. renderSession.filterManager.pushFilter(this._filterBlock);
  1425. }
  1426. if(this._mask)
  1427. {
  1428. renderSession.spriteBatch.stop();
  1429. renderSession.maskManager.pushMask(this.mask, renderSession);
  1430. renderSession.spriteBatch.start();
  1431. }
  1432. // simple render children!
  1433. for(i=0,j=this.children.length; i<j; i++)
  1434. {
  1435. this.children[i]._renderWebGL(renderSession);
  1436. }
  1437. renderSession.spriteBatch.stop();
  1438. if(this._mask)renderSession.maskManager.popMask(this._mask, renderSession);
  1439. if(this._filters)renderSession.filterManager.popFilter();
  1440. renderSession.spriteBatch.start();
  1441. }
  1442. else
  1443. {
  1444. // simple render children!
  1445. for(i=0,j=this.children.length; i<j; i++)
  1446. {
  1447. this.children[i]._renderWebGL(renderSession);
  1448. }
  1449. }
  1450. };
  1451. /**
  1452. * Renders the object using the Canvas renderer
  1453. *
  1454. * @method _renderCanvas
  1455. * @param renderSession {RenderSession}
  1456. * @private
  1457. */
  1458. PIXI.DisplayObjectContainer.prototype._renderCanvas = function(renderSession)
  1459. {
  1460. if(this.visible === false || this.alpha === 0)return;
  1461. if(this._cacheAsBitmap)
  1462. {
  1463. this._renderCachedSprite(renderSession);
  1464. return;
  1465. }
  1466. if(this._mask)
  1467. {
  1468. renderSession.maskManager.pushMask(this._mask, renderSession.context);
  1469. }
  1470. for(var i=0,j=this.children.length; i<j; i++)
  1471. {
  1472. var child = this.children[i];
  1473. child._renderCanvas(renderSession);
  1474. }
  1475. if(this._mask)
  1476. {
  1477. renderSession.maskManager.popMask(renderSession.context);
  1478. }
  1479. };
  1480. /**
  1481. * @author Mat Groves http://matgroves.com/ @Doormat23
  1482. */
  1483. /**
  1484. * The Sprite object is the base for all textured objects that are rendered to the screen
  1485. *
  1486. * @class Sprite
  1487. * @extends DisplayObjectContainer
  1488. * @constructor
  1489. * @param texture {Texture} The texture for this sprite
  1490. *
  1491. * A sprite can be created directly from an image like this :
  1492. * var sprite = new PIXI.Sprite.fromImage('assets/image.png');
  1493. * yourStage.addChild(sprite);
  1494. * then obviously don't forget to add it to the stage you have already created
  1495. */
  1496. PIXI.Sprite = function(texture)
  1497. {
  1498. PIXI.DisplayObjectContainer.call( this );
  1499. /**
  1500. * The anchor sets the origin point of the texture.
  1501. * The default is 0,0 this means the texture's origin is the top left
  1502. * Setting than anchor to 0.5,0.5 means the textures origin is centred
  1503. * Setting the anchor to 1,1 would mean the textures origin points will be the bottom right corner
  1504. *
  1505. * @property anchor
  1506. * @type Point
  1507. */
  1508. this.anchor = new PIXI.Point();
  1509. /**
  1510. * The texture that the sprite is using
  1511. *
  1512. * @property texture
  1513. * @type Texture
  1514. */
  1515. this.texture = texture;
  1516. /**
  1517. * The width of the sprite (this is initially set by the texture)
  1518. *
  1519. * @property _width
  1520. * @type Number
  1521. * @private
  1522. */
  1523. this._width = 0;
  1524. /**
  1525. * The height of the sprite (this is initially set by the texture)
  1526. *
  1527. * @property _height
  1528. * @type Number
  1529. * @private
  1530. */
  1531. this._height = 0;
  1532. /**
  1533. * The tint applied to the sprite. This is a hex value
  1534. *
  1535. * @property tint
  1536. * @type Number
  1537. * @default 0xFFFFFF
  1538. */
  1539. this.tint = 0xFFFFFF;// * Math.random();
  1540. /**
  1541. * The blend mode to be applied to the sprite
  1542. *
  1543. * @property blendMode
  1544. * @type Number
  1545. * @default PIXI.blendModes.NORMAL;
  1546. */
  1547. this.blendMode = PIXI.blendModes.NORMAL;
  1548. if(texture.baseTexture.hasLoaded)
  1549. {
  1550. this.onTextureUpdate();
  1551. }
  1552. else
  1553. {
  1554. this.onTextureUpdateBind = this.onTextureUpdate.bind(this);
  1555. this.texture.addEventListener( 'update', this.onTextureUpdateBind );
  1556. }
  1557. this.renderable = true;
  1558. };
  1559. // constructor
  1560. PIXI.Sprite.prototype = Object.create( PIXI.DisplayObjectContainer.prototype );
  1561. PIXI.Sprite.prototype.constructor = PIXI.Sprite;
  1562. /**
  1563. * The width of the sprite, setting this will actually modify the scale to achieve the value set
  1564. *
  1565. * @property width
  1566. * @type Number
  1567. */
  1568. Object.defineProperty(PIXI.Sprite.prototype, 'width', {
  1569. get: function() {
  1570. return this.scale.x * this.texture.frame.width;
  1571. },
  1572. set: function(value) {
  1573. this.scale.x = value / this.texture.frame.width;
  1574. this._width = value;
  1575. }
  1576. });
  1577. /**
  1578. * The height of the sprite, setting this will actually modify the scale to achieve the value set
  1579. *
  1580. * @property height
  1581. * @type Number
  1582. */
  1583. Object.defineProperty(PIXI.Sprite.prototype, 'height', {
  1584. get: function() {
  1585. return this.scale.y * this.texture.frame.height;
  1586. },
  1587. set: function(value) {
  1588. this.scale.y = value / this.texture.frame.height;
  1589. this._height = value;
  1590. }
  1591. });
  1592. /**
  1593. * Sets the texture of the sprite
  1594. *
  1595. * @method setTexture
  1596. * @param texture {Texture} The PIXI texture that is displayed by the sprite
  1597. */
  1598. PIXI.Sprite.prototype.setTexture = function(texture)
  1599. {
  1600. this.texture = texture;
  1601. this.cachedTint = 0xFFFFFF;
  1602. };
  1603. /**
  1604. * When the texture is updated, this event will fire to update the scale and frame
  1605. *
  1606. * @method onTextureUpdate
  1607. * @param event
  1608. * @private
  1609. */
  1610. PIXI.Sprite.prototype.onTextureUpdate = function()
  1611. {
  1612. // so if _width is 0 then width was not set..
  1613. if(this._width)this.scale.x = this._width / this.texture.frame.width;
  1614. if(this._height)this.scale.y = this._height / this.texture.frame.height;
  1615. //this.updateFrame = true;
  1616. };
  1617. /**
  1618. * Returns the framing rectangle of the sprite as a PIXI.Rectangle object
  1619. *
  1620. * @method getBounds
  1621. * @param matrix {Matrix} the transformation matrix of the sprite
  1622. * @return {Rectangle} the framing rectangle
  1623. */
  1624. PIXI.Sprite.prototype.getBounds = function(matrix)
  1625. {
  1626. var width = this.texture.frame.width;
  1627. var height = this.texture.frame.height;
  1628. var w0 = width * (1-this.anchor.x);
  1629. var w1 = width * -this.anchor.x;
  1630. var h0 = height * (1-this.anchor.y);
  1631. var h1 = height * -this.anchor.y;
  1632. var worldTransform = matrix || this.worldTransform ;
  1633. var a = worldTransform.a;
  1634. var b = worldTransform.c;
  1635. var c = worldTransform.b;
  1636. var d = worldTransform.d;
  1637. var tx = worldTransform.tx;
  1638. var ty = worldTransform.ty;
  1639. var x1 = a * w1 + c * h1 + tx;
  1640. var y1 = d * h1 + b * w1 + ty;
  1641. var x2 = a * w0 + c * h1 + tx;
  1642. var y2 = d * h1 + b * w0 + ty;
  1643. var x3 = a * w0 + c * h0 + tx;
  1644. var y3 = d * h0 + b * w0 + ty;
  1645. var x4 = a * w1 + c * h0 + tx;
  1646. var y4 = d * h0 + b * w1 + ty;
  1647. var maxX = -Infinity;
  1648. var maxY = -Infinity;
  1649. var minX = Infinity;
  1650. var minY = Infinity;
  1651. minX = x1 < minX ? x1 : minX;
  1652. minX = x2 < minX ? x2 : minX;
  1653. minX = x3 < minX ? x3 : minX;
  1654. minX = x4 < minX ? x4 : minX;
  1655. minY = y1 < minY ? y1 : minY;
  1656. minY = y2 < minY ? y2 : minY;
  1657. minY = y3 < minY ? y3 : minY;
  1658. minY = y4 < minY ? y4 : minY;
  1659. maxX = x1 > maxX ? x1 : maxX;
  1660. maxX = x2 > maxX ? x2 : maxX;
  1661. maxX = x3 > maxX ? x3 : maxX;
  1662. maxX = x4 > maxX ? x4 : maxX;
  1663. maxY = y1 > maxY ? y1 : maxY;
  1664. maxY = y2 > maxY ? y2 : maxY;
  1665. maxY = y3 > maxY ? y3 : maxY;
  1666. maxY = y4 > maxY ? y4 : maxY;
  1667. var bounds = this._bounds;
  1668. bounds.x = minX;
  1669. bounds.width = maxX - minX;
  1670. bounds.y = minY;
  1671. bounds.height = maxY - minY;
  1672. // store a reference so that if this function gets called again in the render cycle we do not have to recalculate
  1673. this._currentBounds = bounds;
  1674. return bounds;
  1675. };
  1676. /**
  1677. * Renders the object using the WebGL renderer
  1678. *
  1679. * @method _renderWebGL
  1680. * @param renderSession {RenderSession}
  1681. * @private
  1682. */
  1683. PIXI.Sprite.prototype._renderWebGL = function(renderSession)
  1684. {
  1685. // if the sprite is not visible or the alpha is 0 then no need to render this element
  1686. if(!this.visible || this.alpha <= 0)return;
  1687. var i,j;
  1688. // do a quick check to see if this element has a mask or a filter.
  1689. if(this._mask || this._filters)
  1690. {
  1691. var spriteBatch = renderSession.spriteBatch;
  1692. // push filter first as we need to ensure the stencil buffer is correct for any masking
  1693. if(this._filters)
  1694. {
  1695. spriteBatch.flush();
  1696. renderSession.filterManager.pushFilter(this._filterBlock);
  1697. }
  1698. if(this._mask)
  1699. {
  1700. spriteBatch.stop();
  1701. renderSession.maskManager.pushMask(this.mask, renderSession);
  1702. spriteBatch.start();
  1703. }
  1704. // add this sprite to the batch
  1705. spriteBatch.render(this);
  1706. // now loop through the children and make sure they get rendered
  1707. for(i=0,j=this.children.length; i<j; i++)
  1708. {
  1709. this.children[i]._renderWebGL(renderSession);
  1710. }
  1711. // time to stop the sprite batch as either a mask element or a filter draw will happen next
  1712. spriteBatch.stop();
  1713. if(this._mask)renderSession.maskManager.popMask(this._mask, renderSession);
  1714. if(this._filters)renderSession.filterManager.popFilter();
  1715. spriteBatch.start();
  1716. }
  1717. else
  1718. {
  1719. renderSession.spriteBatch.render(this);
  1720. // simple render children!
  1721. for(i=0,j=this.children.length; i<j; i++)
  1722. {
  1723. this.children[i]._renderWebGL(renderSession);
  1724. }
  1725. }
  1726. //TODO check culling
  1727. };
  1728. /**
  1729. * Renders the object using the Canvas renderer
  1730. *
  1731. * @method _renderCanvas
  1732. * @param renderSession {RenderSession}
  1733. * @private
  1734. */
  1735. PIXI.Sprite.prototype._renderCanvas = function(renderSession)
  1736. {
  1737. // If the sprite is not visible or the alpha is 0 then no need to render this element
  1738. if (this.visible === false || this.alpha === 0) return;
  1739. if (this.blendMode !== renderSession.currentBlendMode)
  1740. {
  1741. renderSession.currentBlendMode = this.blendMode;
  1742. renderSession.context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
  1743. }
  1744. if (this._mask)
  1745. {
  1746. renderSession.maskManager.pushMask(this._mask, renderSession.context);
  1747. }
  1748. // Ignore null sources
  1749. if (this.texture.valid)
  1750. {
  1751. renderSession.context.globalAlpha = this.worldAlpha;
  1752. // Allow for pixel rounding
  1753. if (renderSession.roundPixels)
  1754. {
  1755. renderSession.context.setTransform(
  1756. this.worldTransform.a,
  1757. this.worldTransform.c,
  1758. this.worldTransform.b,
  1759. this.worldTransform.d,
  1760. this.worldTransform.tx | 0,
  1761. this.worldTransform.ty | 0);
  1762. }
  1763. else
  1764. {
  1765. renderSession.context.setTransform(
  1766. this.worldTransform.a,
  1767. this.worldTransform.c,
  1768. this.worldTransform.b,
  1769. this.worldTransform.d,
  1770. this.worldTransform.tx,
  1771. this.worldTransform.ty);
  1772. }
  1773. // If smoothingEnabled is supported and we need to change the smoothing property for this texture
  1774. if (renderSession.smoothProperty && renderSession.scaleMode !== this.texture.baseTexture.scaleMode)
  1775. {
  1776. renderSession.scaleMode = this.texture.baseTexture.scaleMode;
  1777. renderSession.context[renderSession.smoothProperty] = (renderSession.scaleMode === PIXI.scaleModes.LINEAR);
  1778. }
  1779. // If the texture is trimmed we offset by the trim x/y, otherwise we use the frame dimensions
  1780. var dx = (this.texture.trim) ? this.texture.trim.x - this.anchor.x * this.texture.trim.width : this.anchor.x * -this.texture.frame.width;
  1781. var dy = (this.texture.trim) ? this.texture.trim.y - this.anchor.y * this.texture.trim.height : this.anchor.y * -this.texture.frame.height;
  1782. if (this.tint !== 0xFFFFFF)
  1783. {
  1784. if (this.cachedTint !== this.tint)
  1785. {
  1786. this.cachedTint = this.tint;
  1787. // TODO clean up caching - how to clean up the caches?
  1788. this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint);
  1789. }
  1790. renderSession.context.drawImage(
  1791. this.tintedTexture,
  1792. 0,
  1793. 0,
  1794. this.texture.crop.width,
  1795. this.texture.crop.height,
  1796. dx,
  1797. dy,
  1798. this.texture.crop.width,
  1799. this.texture.crop.height);
  1800. }
  1801. else
  1802. {
  1803. renderSession.context.drawImage(
  1804. this.texture.baseTexture.source,
  1805. this.texture.crop.x,
  1806. this.texture.crop.y,
  1807. this.texture.crop.width,
  1808. this.texture.crop.height,
  1809. dx,
  1810. dy,
  1811. this.texture.crop.width,
  1812. this.texture.crop.height);
  1813. }
  1814. }
  1815. // OVERWRITE
  1816. for (var i = 0, j = this.children.length; i < j; i++)
  1817. {
  1818. this.children[i]._renderCanvas(renderSession);
  1819. }
  1820. if (this._mask)
  1821. {
  1822. renderSession.maskManager.popMask(renderSession.context);
  1823. }
  1824. };
  1825. // some helper functions..
  1826. /**
  1827. *
  1828. * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId
  1829. * The frame ids are created when a Texture packer file has been loaded
  1830. *
  1831. * @method fromFrame
  1832. * @static
  1833. * @param frameId {String} The frame Id of the texture in the cache
  1834. * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId
  1835. */
  1836. PIXI.Sprite.fromFrame = function(frameId)
  1837. {
  1838. var texture = PIXI.TextureCache[frameId];
  1839. if(!texture) throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this);
  1840. return new PIXI.Sprite(texture);
  1841. };
  1842. /**
  1843. *
  1844. * Helper function that creates a sprite that will contain a texture based on an image url
  1845. * If the image is not in the texture cache it will be loaded
  1846. *
  1847. * @method fromImage
  1848. * @static
  1849. * @param imageId {String} The image url of the texture
  1850. * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id
  1851. */
  1852. PIXI.Sprite.fromImage = function(imageId, crossorigin, scaleMode)
  1853. {
  1854. var texture = PIXI.Texture.fromImage(imageId, crossorigin, scaleMode);
  1855. return new PIXI.Sprite(texture);
  1856. };
  1857. /**
  1858. * @author Mat Groves http://matgroves.com/
  1859. */
  1860. /**
  1861. * The SpriteBatch class is a really fast version of the DisplayObjectContainer
  1862. * built solely for speed, so use when you need a lot of sprites or particles.
  1863. * And it's extremely easy to use :
  1864. var container = new PIXI.SpriteBatch();
  1865. stage.addChild(container);
  1866. for(var i = 0; i < 100; i++)
  1867. {
  1868. var sprite = new PIXI.Sprite.fromImage("myImage.png");
  1869. container.addChild(sprite);
  1870. }
  1871. * And here you have a hundred sprites that will be renderer at the speed of light
  1872. *
  1873. * @class SpriteBatch
  1874. * @constructor
  1875. * @param texture {Texture}
  1876. */
  1877. PIXI.SpriteBatch = function(texture)
  1878. {
  1879. PIXI.DisplayObjectContainer.call( this);
  1880. this.textureThing = texture;
  1881. this.ready = false;
  1882. };
  1883. PIXI.SpriteBatch.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  1884. PIXI.SpriteBatch.constructor = PIXI.SpriteBatch;
  1885. /*
  1886. * Initialises the spriteBatch
  1887. *
  1888. * @method initWebGL
  1889. * @param gl {WebGLContext} the current WebGL drawing context
  1890. */
  1891. PIXI.SpriteBatch.prototype.initWebGL = function(gl)
  1892. {
  1893. // TODO only one needed for the whole engine really?
  1894. this.fastSpriteBatch = new PIXI.WebGLFastSpriteBatch(gl);
  1895. this.ready = true;
  1896. };
  1897. /*
  1898. * Updates the object transform for rendering
  1899. *
  1900. * @method updateTransform
  1901. * @private
  1902. */
  1903. PIXI.SpriteBatch.prototype.updateTransform = function()
  1904. {
  1905. // TODO dont need to!
  1906. PIXI.DisplayObject.prototype.updateTransform.call( this );
  1907. // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this );
  1908. };
  1909. /**
  1910. * Renders the object using the WebGL renderer
  1911. *
  1912. * @method _renderWebGL
  1913. * @param renderSession {RenderSession}
  1914. * @private
  1915. */
  1916. PIXI.SpriteBatch.prototype._renderWebGL = function(renderSession)
  1917. {
  1918. if(!this.visible || this.alpha <= 0 || !this.children.length)return;
  1919. if(!this.ready)this.initWebGL( renderSession.gl );
  1920. renderSession.spriteBatch.stop();
  1921. renderSession.shaderManager.setShader(renderSession.shaderManager.fastShader);
  1922. this.fastSpriteBatch.begin(this, renderSession);
  1923. this.fastSpriteBatch.render(this);
  1924. renderSession.spriteBatch.start();
  1925. };
  1926. /**
  1927. * Renders the object using the Canvas renderer
  1928. *
  1929. * @method _renderCanvas
  1930. * @param renderSession {RenderSession}
  1931. * @private
  1932. */
  1933. PIXI.SpriteBatch.prototype._renderCanvas = function(renderSession)
  1934. {
  1935. var context = renderSession.context;
  1936. context.globalAlpha = this.worldAlpha;
  1937. PIXI.DisplayObject.prototype.updateTransform.call(this);
  1938. var transform = this.worldTransform;
  1939. // alow for trimming
  1940. var isRotated = true;
  1941. for (var i = 0; i < this.children.length; i++) {
  1942. var child = this.children[i];
  1943. if(!child.visible)continue;
  1944. var texture = child.texture;
  1945. var frame = texture.frame;
  1946. context.globalAlpha = this.worldAlpha * child.alpha;
  1947. if(child.rotation % (Math.PI * 2) === 0)
  1948. {
  1949. if(isRotated)
  1950. {
  1951. context.setTransform(transform.a, transform.c, transform.b, transform.d, transform.tx, transform.ty);
  1952. isRotated = false;
  1953. }
  1954. // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call
  1955. context.drawImage(texture.baseTexture.source,
  1956. frame.x,
  1957. frame.y,
  1958. frame.width,
  1959. frame.height,
  1960. ((child.anchor.x) * (-frame.width * child.scale.x) + child.position.x + 0.5) | 0,
  1961. ((child.anchor.y) * (-frame.height * child.scale.y) + child.position.y + 0.5) | 0,
  1962. frame.width * child.scale.x,
  1963. frame.height * child.scale.y);
  1964. }
  1965. else
  1966. {
  1967. if(!isRotated)isRotated = true;
  1968. PIXI.DisplayObject.prototype.updateTransform.call(child);
  1969. var childTransform = child.worldTransform;
  1970. // allow for trimming
  1971. if (renderSession.roundPixels)
  1972. {
  1973. context.setTransform(childTransform.a, childTransform.c, childTransform.b, childTransform.d, childTransform.tx | 0, childTransform.ty | 0);
  1974. }
  1975. else
  1976. {
  1977. context.setTransform(childTransform.a, childTransform.c, childTransform.b, childTransform.d, childTransform.tx, childTransform.ty);
  1978. }
  1979. context.drawImage(texture.baseTexture.source,
  1980. frame.x,
  1981. frame.y,
  1982. frame.width,
  1983. frame.height,
  1984. ((child.anchor.x) * (-frame.width) + 0.5) | 0,
  1985. ((child.anchor.y) * (-frame.height) + 0.5) | 0,
  1986. frame.width,
  1987. frame.height);
  1988. }
  1989. // context.restore();
  1990. }
  1991. // context.restore();
  1992. };
  1993. /**
  1994. * @author Mat Groves http://matgroves.com/ @Doormat23
  1995. */
  1996. /**
  1997. * This is the base class for creating a pixi.js filter. Currently only webGL supports filters.
  1998. * If you want to make a custom filter this should be your base class.
  1999. * @class AbstractFilter
  2000. * @constructor
  2001. * @param fragmentSrc
  2002. * @param uniforms
  2003. */
  2004. PIXI.AbstractFilter = function(fragmentSrc, uniforms)
  2005. {
  2006. /**
  2007. * An array of passes - some filters contain a few steps this array simply stores the steps in a liniear fashion.
  2008. * For example the blur filter has two passes blurX and blurY.
  2009. * @property passes
  2010. * @type Array an array of filter objects
  2011. * @private
  2012. */
  2013. this.passes = [this];
  2014. /**
  2015. * @property shaders
  2016. * @type Array an array of shaders
  2017. * @private
  2018. */
  2019. this.shaders = [];
  2020. this.dirty = true;
  2021. this.padding = 0;
  2022. /**
  2023. * @property uniforms
  2024. * @type object
  2025. * @private
  2026. */
  2027. this.uniforms = uniforms || {};
  2028. /**
  2029. * @property fragmentSrc
  2030. * @type Array
  2031. * @private
  2032. */
  2033. this.fragmentSrc = fragmentSrc || [];
  2034. };
  2035. /**
  2036. * @author Mat Groves http://matgroves.com/ @Doormat23
  2037. */
  2038. PIXI.FilterBlock = function()
  2039. {
  2040. this.visible = true;
  2041. this.renderable = true;
  2042. };
  2043. /**
  2044. * @author Mat Groves http://matgroves.com/ @Doormat23
  2045. * - Modified by Tom Slezakowski http://www.tomslezakowski.com @TomSlezakowski (24/03/2014) - Added dropShadowColor.
  2046. */
  2047. /**
  2048. * A Text Object will create a line(s) of text. To split a line you can use '\n'
  2049. * or add a wordWrap property set to true and and wordWrapWidth property with a value
  2050. * in the style object
  2051. *
  2052. * @class Text
  2053. * @extends Sprite
  2054. * @constructor
  2055. * @param text {String} The copy that you would like the text to display
  2056. * @param [style] {Object} The style parameters
  2057. * @param [style.font] {String} default 'bold 20px Arial' The style and size of the font
  2058. * @param [style.fill='black'] {String|Number} A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'
  2059. * @param [style.align='left'] {String} Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text
  2060. * @param [style.stroke] {String|Number} A canvas fillstyle that will be used on the text stroke e.g 'blue', '#FCFF00'
  2061. * @param [style.strokeThickness=0] {Number} A number that represents the thickness of the stroke. Default is 0 (no stroke)
  2062. * @param [style.wordWrap=false] {Boolean} Indicates if word wrap should be used
  2063. * @param [style.wordWrapWidth=100] {Number} The width at which text will wrap, it needs wordWrap to be set to true
  2064. * @param [style.dropShadow=false] {Boolean} Set a drop shadow for the text
  2065. * @param [style.dropShadowColor='#000000'] {String} A fill style to be used on the dropshadow e.g 'red', '#00FF00'
  2066. * @param [style.dropShadowAngle=Math.PI/4] {Number} Set a angle of the drop shadow
  2067. * @param [style.dropShadowDistance=5] {Number} Set a distance of the drop shadow
  2068. */
  2069. PIXI.Text = function(text, style)
  2070. {
  2071. /**
  2072. * The canvas element that everything is drawn to
  2073. *
  2074. * @property canvas
  2075. * @type HTMLCanvasElement
  2076. */
  2077. this.canvas = document.createElement('canvas');
  2078. /**
  2079. * The canvas 2d context that everything is drawn with
  2080. * @property context
  2081. * @type HTMLCanvasElement 2d Context
  2082. */
  2083. this.context = this.canvas.getContext('2d');
  2084. PIXI.Sprite.call(this, PIXI.Texture.fromCanvas(this.canvas));
  2085. this.setText(text);
  2086. this.setStyle(style);
  2087. };
  2088. // constructor
  2089. PIXI.Text.prototype = Object.create(PIXI.Sprite.prototype);
  2090. PIXI.Text.prototype.constructor = PIXI.Text;
  2091. /**
  2092. * The width of the sprite, setting this will actually modify the scale to achieve the value set
  2093. *
  2094. * @property width
  2095. * @type Number
  2096. */
  2097. Object.defineProperty(PIXI.Text.prototype, 'width', {
  2098. get: function() {
  2099. if(this.dirty)
  2100. {
  2101. this.updateText();
  2102. this.dirty = false;
  2103. }
  2104. return this.scale.x * this.texture.frame.width;
  2105. },
  2106. set: function(value) {
  2107. this.scale.x = value / this.texture.frame.width;
  2108. this._width = value;
  2109. }
  2110. });
  2111. /**
  2112. * The height of the Text, setting this will actually modify the scale to achieve the value set
  2113. *
  2114. * @property height
  2115. * @type Number
  2116. */
  2117. Object.defineProperty(PIXI.Text.prototype, 'height', {
  2118. get: function() {
  2119. if(this.dirty)
  2120. {
  2121. this.updateText();
  2122. this.dirty = false;
  2123. }
  2124. return this.scale.y * this.texture.frame.height;
  2125. },
  2126. set: function(value) {
  2127. this.scale.y = value / this.texture.frame.height;
  2128. this._height = value;
  2129. }
  2130. });
  2131. /**
  2132. * Set the style of the text
  2133. *
  2134. * @method setStyle
  2135. * @param [style] {Object} The style parameters
  2136. * @param [style.font='bold 20pt Arial'] {String} The style and size of the font
  2137. * @param [style.fill='black'] {Object} A canvas fillstyle that will be used on the text eg 'red', '#00FF00'
  2138. * @param [style.align='left'] {String} Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text
  2139. * @param [style.stroke='black'] {String} A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'
  2140. * @param [style.strokeThickness=0] {Number} A number that represents the thickness of the stroke. Default is 0 (no stroke)
  2141. * @param [style.wordWrap=false] {Boolean} Indicates if word wrap should be used
  2142. * @param [style.wordWrapWidth=100] {Number} The width at which text will wrap
  2143. * @param [style.dropShadow=false] {Boolean} Set a drop shadow for the text
  2144. * @param [style.dropShadowColor='#000000'] {String} A fill style to be used on the dropshadow e.g 'red', '#00FF00'
  2145. * @param [style.dropShadowAngle=Math.PI/4] {Number} Set a angle of the drop shadow
  2146. * @param [style.dropShadowDistance=5] {Number} Set a distance of the drop shadow
  2147. */
  2148. PIXI.Text.prototype.setStyle = function(style)
  2149. {
  2150. style = style || {};
  2151. style.font = style.font || 'bold 20pt Arial';
  2152. style.fill = style.fill || 'black';
  2153. style.align = style.align || 'left';
  2154. style.stroke = style.stroke || 'black'; //provide a default, see: https://github.com/GoodBoyDigital/pixi.js/issues/136
  2155. style.strokeThickness = style.strokeThickness || 0;
  2156. style.wordWrap = style.wordWrap || false;
  2157. style.wordWrapWidth = style.wordWrapWidth || 100;
  2158. style.wordWrapWidth = style.wordWrapWidth || 100;
  2159. style.dropShadow = style.dropShadow || false;
  2160. style.dropShadowAngle = style.dropShadowAngle || Math.PI / 6;
  2161. style.dropShadowDistance = style.dropShadowDistance || 4;
  2162. style.dropShadowColor = style.dropShadowColor || 'black';
  2163. this.style = style;
  2164. this.dirty = true;
  2165. };
  2166. /**
  2167. * Set the copy for the text object. To split a line you can use '\n'
  2168. *
  2169. * @method setText
  2170. * @param {String} text The copy that you would like the text to display
  2171. */
  2172. PIXI.Text.prototype.setText = function(text)
  2173. {
  2174. this.text = text.toString() || ' ';
  2175. this.dirty = true;
  2176. };
  2177. /**
  2178. * Renders text and updates it when needed
  2179. *
  2180. * @method updateText
  2181. * @private
  2182. */
  2183. PIXI.Text.prototype.updateText = function()
  2184. {
  2185. this.context.font = this.style.font;
  2186. var outputText = this.text;
  2187. // word wrap
  2188. // preserve original text
  2189. if(this.style.wordWrap)outputText = this.wordWrap(this.text);
  2190. //split text into lines
  2191. var lines = outputText.split(/(?:\r\n|\r|\n)/);
  2192. //calculate text width
  2193. var lineWidths = [];
  2194. var maxLineWidth = 0;
  2195. for (var i = 0; i < lines.length; i++)
  2196. {
  2197. var lineWidth = this.context.measureText(lines[i]).width;
  2198. lineWidths[i] = lineWidth;
  2199. maxLineWidth = Math.max(maxLineWidth, lineWidth);
  2200. }
  2201. var width = maxLineWidth + this.style.strokeThickness;
  2202. if(this.style.dropShadow)width += this.style.dropShadowDistance;
  2203. this.canvas.width = width + this.context.lineWidth;
  2204. //calculate text height
  2205. var lineHeight = this.determineFontHeight('font: ' + this.style.font + ';') + this.style.strokeThickness;
  2206. var height = lineHeight * lines.length;
  2207. if(this.style.dropShadow)height += this.style.dropShadowDistance;
  2208. this.canvas.height = height;
  2209. if(navigator.isCocoonJS) this.context.clearRect(0,0,this.canvas.width,this.canvas.height);
  2210. this.context.font = this.style.font;
  2211. this.context.strokeStyle = this.style.stroke;
  2212. this.context.lineWidth = this.style.strokeThickness;
  2213. this.context.textBaseline = 'top';
  2214. var linePositionX;
  2215. var linePositionY;
  2216. if(this.style.dropShadow)
  2217. {
  2218. this.context.fillStyle = this.style.dropShadowColor;
  2219. var xShadowOffset = Math.sin(this.style.dropShadowAngle) * this.style.dropShadowDistance;
  2220. var yShadowOffset = Math.cos(this.style.dropShadowAngle) * this.style.dropShadowDistance;
  2221. for (i = 0; i < lines.length; i++)
  2222. {
  2223. linePositionX = this.style.strokeThickness / 2;
  2224. linePositionY = this.style.strokeThickness / 2 + i * lineHeight;
  2225. if(this.style.align === 'right')
  2226. {
  2227. linePositionX += maxLineWidth - lineWidths[i];
  2228. }
  2229. else if(this.style.align === 'center')
  2230. {
  2231. linePositionX += (maxLineWidth - lineWidths[i]) / 2;
  2232. }
  2233. if(this.style.fill)
  2234. {
  2235. this.context.fillText(lines[i], linePositionX + xShadowOffset, linePositionY + yShadowOffset);
  2236. }
  2237. // if(dropShadow)
  2238. }
  2239. }
  2240. //set canvas text styles
  2241. this.context.fillStyle = this.style.fill;
  2242. //draw lines line by line
  2243. for (i = 0; i < lines.length; i++)
  2244. {
  2245. linePositionX = this.style.strokeThickness / 2;
  2246. linePositionY = this.style.strokeThickness / 2 + i * lineHeight;
  2247. if(this.style.align === 'right')
  2248. {
  2249. linePositionX += maxLineWidth - lineWidths[i];
  2250. }
  2251. else if(this.style.align === 'center')
  2252. {
  2253. linePositionX += (maxLineWidth - lineWidths[i]) / 2;
  2254. }
  2255. if(this.style.stroke && this.style.strokeThickness)
  2256. {
  2257. this.context.strokeText(lines[i], linePositionX, linePositionY);
  2258. }
  2259. if(this.style.fill)
  2260. {
  2261. this.context.fillText(lines[i], linePositionX, linePositionY);
  2262. }
  2263. // if(dropShadow)
  2264. }
  2265. this.updateTexture();
  2266. };
  2267. /**
  2268. * Updates texture size based on canvas size
  2269. *
  2270. * @method updateTexture
  2271. * @private
  2272. */
  2273. PIXI.Text.prototype.updateTexture = function()
  2274. {
  2275. this.texture.baseTexture.width = this.canvas.width;
  2276. this.texture.baseTexture.height = this.canvas.height;
  2277. this.texture.crop.width = this.texture.frame.width = this.canvas.width;
  2278. this.texture.crop.height = this.texture.frame.height = this.canvas.height;
  2279. this._width = this.canvas.width;
  2280. this._height = this.canvas.height;
  2281. this.requiresUpdate = true;
  2282. };
  2283. /**
  2284. * Renders the object using the WebGL renderer
  2285. *
  2286. * @method _renderWebGL
  2287. * @param renderSession {RenderSession}
  2288. * @private
  2289. */
  2290. PIXI.Text.prototype._renderWebGL = function(renderSession)
  2291. {
  2292. if(this.requiresUpdate)
  2293. {
  2294. this.requiresUpdate = false;
  2295. PIXI.updateWebGLTexture(this.texture.baseTexture, renderSession.gl);
  2296. }
  2297. PIXI.Sprite.prototype._renderWebGL.call(this, renderSession);
  2298. };
  2299. /**
  2300. * Updates the transform of this object
  2301. *
  2302. * @method updateTransform
  2303. * @private
  2304. */
  2305. PIXI.Text.prototype.updateTransform = function()
  2306. {
  2307. if(this.dirty)
  2308. {
  2309. this.updateText();
  2310. this.dirty = false;
  2311. }
  2312. PIXI.Sprite.prototype.updateTransform.call(this);
  2313. };
  2314. /*
  2315. * http://stackoverflow.com/users/34441/ellisbben
  2316. * great solution to the problem!
  2317. * returns the height of the given font
  2318. *
  2319. * @method determineFontHeight
  2320. * @param fontStyle {Object}
  2321. * @private
  2322. */
  2323. PIXI.Text.prototype.determineFontHeight = function(fontStyle)
  2324. {
  2325. // build a little reference dictionary so if the font style has been used return a
  2326. // cached version...
  2327. var result = PIXI.Text.heightCache[fontStyle];
  2328. if(!result)
  2329. {
  2330. var body = document.getElementsByTagName('body')[0];
  2331. var dummy = document.createElement('div');
  2332. var dummyText = document.createTextNode('M');
  2333. dummy.appendChild(dummyText);
  2334. dummy.setAttribute('style', fontStyle + ';position:absolute;top:0;left:0');
  2335. body.appendChild(dummy);
  2336. result = dummy.offsetHeight;
  2337. PIXI.Text.heightCache[fontStyle] = result;
  2338. body.removeChild(dummy);
  2339. }
  2340. return result;
  2341. };
  2342. /**
  2343. * Applies newlines to a string to have it optimally fit into the horizontal
  2344. * bounds set by the Text object's wordWrapWidth property.
  2345. *
  2346. * @method wordWrap
  2347. * @param text {String}
  2348. * @private
  2349. */
  2350. PIXI.Text.prototype.wordWrap = function(text)
  2351. {
  2352. // Greedy wrapping algorithm that will wrap words as the line grows longer
  2353. // than its horizontal bounds.
  2354. var result = '';
  2355. var lines = text.split('\n');
  2356. for (var i = 0; i < lines.length; i++)
  2357. {
  2358. var spaceLeft = this.style.wordWrapWidth;
  2359. var words = lines[i].split(' ');
  2360. for (var j = 0; j < words.length; j++)
  2361. {
  2362. var wordWidth = this.context.measureText(words[j]).width;
  2363. var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width;
  2364. if(j === 0 || wordWidthWithSpace > spaceLeft)
  2365. {
  2366. // Skip printing the newline if it's the first word of the line that is
  2367. // greater than the word wrap width.
  2368. if(j > 0)
  2369. {
  2370. result += '\n';
  2371. }
  2372. result += words[j];
  2373. spaceLeft = this.style.wordWrapWidth - wordWidth;
  2374. }
  2375. else
  2376. {
  2377. spaceLeft -= wordWidthWithSpace;
  2378. result += ' ' + words[j];
  2379. }
  2380. }
  2381. if (i < lines.length-1)
  2382. {
  2383. result += '\n';
  2384. }
  2385. }
  2386. return result;
  2387. };
  2388. /**
  2389. * Destroys this text object
  2390. *
  2391. * @method destroy
  2392. * @param destroyBaseTexture {Boolean} whether to destroy the base texture as well
  2393. */
  2394. PIXI.Text.prototype.destroy = function(destroyBaseTexture)
  2395. {
  2396. // make sure to reset the the context and canvas.. dont want this hanging around in memory!
  2397. this.context = null;
  2398. this.canvas = null;
  2399. this.texture.destroy(destroyBaseTexture === undefined ? true : destroyBaseTexture);
  2400. };
  2401. PIXI.Text.heightCache = {};
  2402. /**
  2403. * @author Mat Groves http://matgroves.com/ @Doormat23
  2404. */
  2405. /**
  2406. * A Text Object will create a line(s) of text using bitmap font. To split a line you can use '\n', '\r' or '\r\n'
  2407. * You can generate the fnt files using
  2408. * http://www.angelcode.com/products/bmfont/ for windows or
  2409. * http://www.bmglyph.com/ for mac.
  2410. *
  2411. * @class BitmapText
  2412. * @extends DisplayObjectContainer
  2413. * @constructor
  2414. * @param text {String} The copy that you would like the text to display
  2415. * @param style {Object} The style parameters
  2416. * @param style.font {String} The size (optional) and bitmap font id (required) eq 'Arial' or '20px Arial' (must have loaded previously)
  2417. * @param [style.align='left'] {String} Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text
  2418. */
  2419. PIXI.BitmapText = function(text, style)
  2420. {
  2421. PIXI.DisplayObjectContainer.call(this);
  2422. this._pool = [];
  2423. this.setText(text);
  2424. this.setStyle(style);
  2425. this.updateText();
  2426. this.dirty = false;
  2427. };
  2428. // constructor
  2429. PIXI.BitmapText.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  2430. PIXI.BitmapText.prototype.constructor = PIXI.BitmapText;
  2431. /**
  2432. * Set the copy for the text object
  2433. *
  2434. * @method setText
  2435. * @param text {String} The copy that you would like the text to display
  2436. */
  2437. PIXI.BitmapText.prototype.setText = function(text)
  2438. {
  2439. this.text = text || ' ';
  2440. this.dirty = true;
  2441. };
  2442. /**
  2443. * Set the style of the text
  2444. * style.font {String} The size (optional) and bitmap font id (required) eq 'Arial' or '20px Arial' (must have loaded previously)
  2445. * [style.align='left'] {String} Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text
  2446. *
  2447. * @method setStyle
  2448. * @param style {Object} The style parameters, contained as properties of an object
  2449. */
  2450. PIXI.BitmapText.prototype.setStyle = function(style)
  2451. {
  2452. style = style || {};
  2453. style.align = style.align || 'left';
  2454. this.style = style;
  2455. var font = style.font.split(' ');
  2456. this.fontName = font[font.length - 1];
  2457. this.fontSize = font.length >= 2 ? parseInt(font[font.length - 2], 10) : PIXI.BitmapText.fonts[this.fontName].size;
  2458. this.dirty = true;
  2459. this.tint = style.tint;
  2460. };
  2461. /**
  2462. * Renders text and updates it when needed
  2463. *
  2464. * @method updateText
  2465. * @private
  2466. */
  2467. PIXI.BitmapText.prototype.updateText = function()
  2468. {
  2469. var data = PIXI.BitmapText.fonts[this.fontName];
  2470. var pos = new PIXI.Point();
  2471. var prevCharCode = null;
  2472. var chars = [];
  2473. var maxLineWidth = 0;
  2474. var lineWidths = [];
  2475. var line = 0;
  2476. var scale = this.fontSize / data.size;
  2477. for(var i = 0; i < this.text.length; i++)
  2478. {
  2479. var charCode = this.text.charCodeAt(i);
  2480. if(/(?:\r\n|\r|\n)/.test(this.text.charAt(i)))
  2481. {
  2482. lineWidths.push(pos.x);
  2483. maxLineWidth = Math.max(maxLineWidth, pos.x);
  2484. line++;
  2485. pos.x = 0;
  2486. pos.y += data.lineHeight;
  2487. prevCharCode = null;
  2488. continue;
  2489. }
  2490. var charData = data.chars[charCode];
  2491. if(!charData) continue;
  2492. if(prevCharCode && charData[prevCharCode])
  2493. {
  2494. pos.x += charData.kerning[prevCharCode];
  2495. }
  2496. chars.push({texture:charData.texture, line: line, charCode: charCode, position: new PIXI.Point(pos.x + charData.xOffset, pos.y + charData.yOffset)});
  2497. pos.x += charData.xAdvance;
  2498. prevCharCode = charCode;
  2499. }
  2500. lineWidths.push(pos.x);
  2501. maxLineWidth = Math.max(maxLineWidth, pos.x);
  2502. var lineAlignOffsets = [];
  2503. for(i = 0; i <= line; i++)
  2504. {
  2505. var alignOffset = 0;
  2506. if(this.style.align === 'right')
  2507. {
  2508. alignOffset = maxLineWidth - lineWidths[i];
  2509. }
  2510. else if(this.style.align === 'center')
  2511. {
  2512. alignOffset = (maxLineWidth - lineWidths[i]) / 2;
  2513. }
  2514. lineAlignOffsets.push(alignOffset);
  2515. }
  2516. var lenChildren = this.children.length;
  2517. var lenChars = chars.length;
  2518. var tint = this.tint || 0xFFFFFF;
  2519. for(i = 0; i < lenChars; i++)
  2520. {
  2521. var c = i < lenChildren ? this.children[i] : this._pool.pop(); // get old child if have. if not - take from pool.
  2522. if (c) c.setTexture(chars[i].texture); // check if got one before.
  2523. else c = new PIXI.Sprite(chars[i].texture); // if no create new one.
  2524. c.position.x = (chars[i].position.x + lineAlignOffsets[chars[i].line]) * scale;
  2525. c.position.y = chars[i].position.y * scale;
  2526. c.scale.x = c.scale.y = scale;
  2527. c.tint = tint;
  2528. if (!c.parent) this.addChild(c);
  2529. }
  2530. // remove unnecessary children.
  2531. // and put their into the pool.
  2532. while(this.children.length > lenChars)
  2533. {
  2534. var child = this.getChildAt(this.children.length - 1);
  2535. this._pool.push(child);
  2536. this.removeChild(child);
  2537. }
  2538. /**
  2539. * [read-only] The width of the overall text, different from fontSize,
  2540. * which is defined in the style object
  2541. *
  2542. * @property textWidth
  2543. * @type Number
  2544. */
  2545. this.textWidth = maxLineWidth * scale;
  2546. /**
  2547. * [read-only] The height of the overall text, different from fontSize,
  2548. * which is defined in the style object
  2549. *
  2550. * @property textHeight
  2551. * @type Number
  2552. */
  2553. this.textHeight = (pos.y + data.lineHeight) * scale;
  2554. };
  2555. /**
  2556. * Updates the transform of this object
  2557. *
  2558. * @method updateTransform
  2559. * @private
  2560. */
  2561. PIXI.BitmapText.prototype.updateTransform = function()
  2562. {
  2563. if(this.dirty)
  2564. {
  2565. this.updateText();
  2566. this.dirty = false;
  2567. }
  2568. PIXI.DisplayObjectContainer.prototype.updateTransform.call(this);
  2569. };
  2570. PIXI.BitmapText.fonts = {};
  2571. /**
  2572. * @author Mat Groves http://matgroves.com/ @Doormat23
  2573. */
  2574. /**
  2575. * A Stage represents the root of the display tree. Everything connected to the stage is rendered
  2576. *
  2577. * @class Stage
  2578. * @extends DisplayObjectContainer
  2579. * @constructor
  2580. * @param backgroundColor {Number} the background color of the stage, you have to pass this in is in hex format
  2581. * like: 0xFFFFFF for white
  2582. *
  2583. * Creating a stage is a mandatory process when you use Pixi, which is as simple as this :
  2584. * var stage = new PIXI.Stage(0xFFFFFF);
  2585. * where the parameter given is the background colour of the stage, in hex
  2586. * you will use this stage instance to add your sprites to it and therefore to the renderer
  2587. * Here is how to add a sprite to the stage :
  2588. * stage.addChild(sprite);
  2589. */
  2590. PIXI.Stage = function(backgroundColor)
  2591. {
  2592. PIXI.DisplayObjectContainer.call( this );
  2593. /**
  2594. * [read-only] Current transform of the object based on world (parent) factors
  2595. *
  2596. * @property worldTransform
  2597. * @type Mat3
  2598. * @readOnly
  2599. * @private
  2600. */
  2601. this.worldTransform = new PIXI.Matrix();
  2602. /**
  2603. * Whether or not the stage is interactive
  2604. *
  2605. * @property interactive
  2606. * @type Boolean
  2607. */
  2608. this.interactive = true;
  2609. /**
  2610. * The interaction manage for this stage, manages all interactive activity on the stage
  2611. *
  2612. * @property interactionManager
  2613. * @type InteractionManager
  2614. */
  2615. this.interactionManager = new PIXI.InteractionManager(this);
  2616. /**
  2617. * Whether the stage is dirty and needs to have interactions updated
  2618. *
  2619. * @property dirty
  2620. * @type Boolean
  2621. * @private
  2622. */
  2623. this.dirty = true;
  2624. //the stage is its own stage
  2625. this.stage = this;
  2626. //optimize hit detection a bit
  2627. this.stage.hitArea = new PIXI.Rectangle(0,0,100000, 100000);
  2628. this.setBackgroundColor(backgroundColor);
  2629. };
  2630. // constructor
  2631. PIXI.Stage.prototype = Object.create( PIXI.DisplayObjectContainer.prototype );
  2632. PIXI.Stage.prototype.constructor = PIXI.Stage;
  2633. /**
  2634. * Sets another DOM element which can receive mouse/touch interactions instead of the default Canvas element.
  2635. * This is useful for when you have other DOM elements on top of the Canvas element.
  2636. *
  2637. * @method setInteractionDelegate
  2638. * @param domElement {DOMElement} This new domElement which will receive mouse/touch events
  2639. */
  2640. PIXI.Stage.prototype.setInteractionDelegate = function(domElement)
  2641. {
  2642. this.interactionManager.setTargetDomElement( domElement );
  2643. };
  2644. /*
  2645. * Updates the object transform for rendering
  2646. *
  2647. * @method updateTransform
  2648. * @private
  2649. */
  2650. PIXI.Stage.prototype.updateTransform = function()
  2651. {
  2652. this.worldAlpha = 1;
  2653. for(var i=0,j=this.children.length; i<j; i++)
  2654. {
  2655. this.children[i].updateTransform();
  2656. }
  2657. if(this.dirty)
  2658. {
  2659. this.dirty = false;
  2660. // update interactive!
  2661. this.interactionManager.dirty = true;
  2662. }
  2663. if(this.interactive)this.interactionManager.update();
  2664. };
  2665. /**
  2666. * Sets the background color for the stage
  2667. *
  2668. * @method setBackgroundColor
  2669. * @param backgroundColor {Number} the color of the background, easiest way to pass this in is in hex format
  2670. * like: 0xFFFFFF for white
  2671. */
  2672. PIXI.Stage.prototype.setBackgroundColor = function(backgroundColor)
  2673. {
  2674. this.backgroundColor = backgroundColor || 0x000000;
  2675. this.backgroundColorSplit = PIXI.hex2rgb(this.backgroundColor);
  2676. var hex = this.backgroundColor.toString(16);
  2677. hex = '000000'.substr(0, 6 - hex.length) + hex;
  2678. this.backgroundColorString = '#' + hex;
  2679. };
  2680. /**
  2681. * This will return the point containing global coords of the mouse.
  2682. *
  2683. * @method getMousePosition
  2684. * @return {Point} The point containing the coords of the global InteractionData position.
  2685. */
  2686. PIXI.Stage.prototype.getMousePosition = function()
  2687. {
  2688. return this.interactionManager.mouse.global;
  2689. };
  2690. /**
  2691. * @author Mat Groves http://matgroves.com/ @Doormat23
  2692. */
  2693. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  2694. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  2695. // requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
  2696. // MIT license
  2697. /**
  2698. * A polyfill for requestAnimationFrame
  2699. * You can actually use both requestAnimationFrame and requestAnimFrame,
  2700. * you will still benefit from the polyfill
  2701. *
  2702. * @method requestAnimationFrame
  2703. */
  2704. /**
  2705. * A polyfill for cancelAnimationFrame
  2706. *
  2707. * @method cancelAnimationFrame
  2708. */
  2709. var lastTime = 0;
  2710. var vendors = ['ms', 'moz', 'webkit', 'o'];
  2711. for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
  2712. window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
  2713. window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] ||
  2714. window[vendors[x] + 'CancelRequestAnimationFrame'];
  2715. }
  2716. if (!window.requestAnimationFrame) {
  2717. window.requestAnimationFrame = function(callback) {
  2718. var currTime = new Date().getTime();
  2719. var timeToCall = Math.max(0, 16 - (currTime - lastTime));
  2720. var id = window.setTimeout(function() { callback(currTime + timeToCall); },
  2721. timeToCall);
  2722. lastTime = currTime + timeToCall;
  2723. return id;
  2724. };
  2725. }
  2726. if (!window.cancelAnimationFrame) {
  2727. window.cancelAnimationFrame = function(id) {
  2728. clearTimeout(id);
  2729. };
  2730. }
  2731. window.requestAnimFrame = window.requestAnimationFrame;
  2732. /**
  2733. * Converts a hex color number to an [R, G, B] array
  2734. *
  2735. * @method hex2rgb
  2736. * @param hex {Number}
  2737. */
  2738. PIXI.hex2rgb = function(hex) {
  2739. return [(hex >> 16 & 0xFF) / 255, ( hex >> 8 & 0xFF) / 255, (hex & 0xFF)/ 255];
  2740. };
  2741. /**
  2742. * Converts a color as an [R, G, B] array to a hex number
  2743. *
  2744. * @method rgb2hex
  2745. * @param rgb {Array}
  2746. */
  2747. PIXI.rgb2hex = function(rgb) {
  2748. return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255);
  2749. };
  2750. /**
  2751. * A polyfill for Function.prototype.bind
  2752. *
  2753. * @method bind
  2754. */
  2755. if (typeof Function.prototype.bind !== 'function') {
  2756. Function.prototype.bind = (function () {
  2757. var slice = Array.prototype.slice;
  2758. return function (thisArg) {
  2759. var target = this, boundArgs = slice.call(arguments, 1);
  2760. if (typeof target !== 'function') throw new TypeError();
  2761. function bound() {
  2762. var args = boundArgs.concat(slice.call(arguments));
  2763. target.apply(this instanceof bound ? this : thisArg, args);
  2764. }
  2765. bound.prototype = (function F(proto) {
  2766. if (proto) F.prototype = proto;
  2767. if (!(this instanceof F)) return new F();
  2768. })(target.prototype);
  2769. return bound;
  2770. };
  2771. })();
  2772. }
  2773. /**
  2774. * A wrapper for ajax requests to be handled cross browser
  2775. *
  2776. * @class AjaxRequest
  2777. * @constructor
  2778. */
  2779. PIXI.AjaxRequest = function()
  2780. {
  2781. var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE
  2782. if (window.ActiveXObject)
  2783. { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
  2784. for (var i=0; i<activexmodes.length; i++)
  2785. {
  2786. try{
  2787. return new window.ActiveXObject(activexmodes[i]);
  2788. }
  2789. catch(e) {
  2790. //suppress error
  2791. }
  2792. }
  2793. }
  2794. else if (window.XMLHttpRequest) // if Mozilla, Safari etc
  2795. {
  2796. return new window.XMLHttpRequest();
  2797. }
  2798. else
  2799. {
  2800. return false;
  2801. }
  2802. };
  2803. /*
  2804. PIXI.packColorRGBA = function(r, g, b, a)//r, g, b, a)
  2805. {
  2806. // console.log(r, b, c, d)
  2807. return (Math.floor((r)*63) << 18) | (Math.floor((g)*63) << 12) | (Math.floor((b)*63) << 6);// | (Math.floor((a)*63))
  2808. // i = i | (Math.floor((a)*63));
  2809. // return i;
  2810. // var r = (i / 262144.0 ) / 64;
  2811. // var g = (i / 4096.0)%64 / 64;
  2812. // var b = (i / 64.0)%64 / 64;
  2813. // var a = (i)%64 / 64;
  2814. // console.log(r, g, b, a);
  2815. // return i;
  2816. };
  2817. */
  2818. /*
  2819. PIXI.packColorRGB = function(r, g, b)//r, g, b, a)
  2820. {
  2821. return (Math.floor((r)*255) << 16) | (Math.floor((g)*255) << 8) | (Math.floor((b)*255));
  2822. };
  2823. PIXI.unpackColorRGB = function(r, g, b)//r, g, b, a)
  2824. {
  2825. return (Math.floor((r)*255) << 16) | (Math.floor((g)*255) << 8) | (Math.floor((b)*255));
  2826. };
  2827. */
  2828. /**
  2829. * Checks whether the Canvas BlendModes are supported by the current browser
  2830. *
  2831. * @method canUseNewCanvasBlendModes
  2832. * @return {Boolean} whether they are supported
  2833. */
  2834. PIXI.canUseNewCanvasBlendModes = function()
  2835. {
  2836. var canvas = document.createElement('canvas');
  2837. canvas.width = 1;
  2838. canvas.height = 1;
  2839. var context = canvas.getContext('2d');
  2840. context.fillStyle = '#000';
  2841. context.fillRect(0,0,1,1);
  2842. context.globalCompositeOperation = 'multiply';
  2843. context.fillStyle = '#fff';
  2844. context.fillRect(0,0,1,1);
  2845. return context.getImageData(0,0,1,1).data[0] === 0;
  2846. };
  2847. /**
  2848. * Given a number, this function returns the closest number that is a power of two
  2849. * this function is taken from Starling Framework as its pretty neat ;)
  2850. *
  2851. * @method getNextPowerOfTwo
  2852. * @param number {Number}
  2853. * @return {Number} the closest number that is a power of two
  2854. */
  2855. PIXI.getNextPowerOfTwo = function(number)
  2856. {
  2857. if (number > 0 && (number & (number - 1)) === 0) // see: http://goo.gl/D9kPj
  2858. return number;
  2859. else
  2860. {
  2861. var result = 1;
  2862. while (result < number) result <<= 1;
  2863. return result;
  2864. }
  2865. };
  2866. /**
  2867. * @author Mat Groves http://matgroves.com/ @Doormat23
  2868. */
  2869. /**
  2870. * https://github.com/mrdoob/eventtarget.js/
  2871. * THankS mr DOob!
  2872. */
  2873. /**
  2874. * Adds event emitter functionality to a class
  2875. *
  2876. * @class EventTarget
  2877. * @example
  2878. * function MyEmitter() {
  2879. * PIXI.EventTarget.call(this); //mixes in event target stuff
  2880. * }
  2881. *
  2882. * var em = new MyEmitter();
  2883. * em.emit({ type: 'eventName', data: 'some data' });
  2884. */
  2885. PIXI.EventTarget = function () {
  2886. /**
  2887. * Holds all the listeners
  2888. *
  2889. * @property listeners
  2890. * @type Object
  2891. */
  2892. var listeners = {};
  2893. /**
  2894. * Adds a listener for a specific event
  2895. *
  2896. * @method addEventListener
  2897. * @param type {string} A string representing the event type to listen for.
  2898. * @param listener {function} The callback function that will be fired when the event occurs
  2899. */
  2900. this.addEventListener = this.on = function ( type, listener ) {
  2901. if ( listeners[ type ] === undefined ) {
  2902. listeners[ type ] = [];
  2903. }
  2904. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  2905. listeners[ type ].unshift( listener );
  2906. }
  2907. };
  2908. /**
  2909. * Fires the event, ie pretends that the event has happened
  2910. *
  2911. * @method dispatchEvent
  2912. * @param event {Event} the event object
  2913. */
  2914. this.dispatchEvent = this.emit = function ( event ) {
  2915. if ( !listeners[ event.type ] || !listeners[ event.type ].length ) {
  2916. return;
  2917. }
  2918. for(var i = listeners[ event.type ].length-1; i >= 0; i--) {
  2919. // for(var i = 0, l=listeners[ event.type ].length; i < l; i++) {
  2920. listeners[ event.type ][ i ]( event );
  2921. }
  2922. };
  2923. /**
  2924. * Removes the specified listener that was assigned to the specified event type
  2925. *
  2926. * @method removeEventListener
  2927. * @param type {string} A string representing the event type which will have its listener removed
  2928. * @param listener {function} The callback function that was be fired when the event occured
  2929. */
  2930. this.removeEventListener = this.off = function ( type, listener ) {
  2931. if ( listeners[ type ] === undefined ) return;
  2932. var index = listeners[ type ].indexOf( listener );
  2933. if ( index !== - 1 ) {
  2934. listeners[ type ].splice( index, 1 );
  2935. }
  2936. };
  2937. /**
  2938. * Removes all the listeners that were active for the specified event type
  2939. *
  2940. * @method removeAllEventListeners
  2941. * @param type {string} A string representing the event type which will have all its listeners removed
  2942. */
  2943. this.removeAllEventListeners = function( type ) {
  2944. var a = listeners[type];
  2945. if (a)
  2946. a.length = 0;
  2947. };
  2948. };
  2949. /*
  2950. PolyK library
  2951. url: http://polyk.ivank.net
  2952. Released under MIT licence.
  2953. Copyright (c) 2012 Ivan Kuckir
  2954. Permission is hereby granted, free of charge, to any person
  2955. obtaining a copy of this software and associated documentation
  2956. files (the "Software"), to deal in the Software without
  2957. restriction, including without limitation the rights to use,
  2958. copy, modify, merge, publish, distribute, sublicense, and/or sell
  2959. copies of the Software, and to permit persons to whom the
  2960. Software is furnished to do so, subject to the following
  2961. conditions:
  2962. The above copyright notice and this permission notice shall be
  2963. included in all copies or substantial portions of the Software.
  2964. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  2965. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  2966. OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  2967. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  2968. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  2969. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  2970. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  2971. OTHER DEALINGS IN THE SOFTWARE.
  2972. This is an amazing lib!
  2973. slightly modified by Mat Groves (matgroves.com);
  2974. */
  2975. /**
  2976. * Based on the Polyk library http://polyk.ivank.net released under MIT licence.
  2977. * This is an amazing lib!
  2978. * slightly modified by Mat Groves (matgroves.com);
  2979. * @class PolyK
  2980. *
  2981. */
  2982. PIXI.PolyK = {};
  2983. /**
  2984. * Triangulates shapes for webGL graphic fills
  2985. *
  2986. * @method Triangulate
  2987. *
  2988. */
  2989. PIXI.PolyK.Triangulate = function(p)
  2990. {
  2991. var sign = true;
  2992. var n = p.length >> 1;
  2993. if(n < 3) return [];
  2994. var tgs = [];
  2995. var avl = [];
  2996. for(var i = 0; i < n; i++) avl.push(i);
  2997. i = 0;
  2998. var al = n;
  2999. while(al > 3)
  3000. {
  3001. var i0 = avl[(i+0)%al];
  3002. var i1 = avl[(i+1)%al];
  3003. var i2 = avl[(i+2)%al];
  3004. var ax = p[2*i0], ay = p[2*i0+1];
  3005. var bx = p[2*i1], by = p[2*i1+1];
  3006. var cx = p[2*i2], cy = p[2*i2+1];
  3007. var earFound = false;
  3008. if(PIXI.PolyK._convex(ax, ay, bx, by, cx, cy, sign))
  3009. {
  3010. earFound = true;
  3011. for(var j = 0; j < al; j++)
  3012. {
  3013. var vi = avl[j];
  3014. if(vi === i0 || vi === i1 || vi === i2) continue;
  3015. if(PIXI.PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) {
  3016. earFound = false;
  3017. break;
  3018. }
  3019. }
  3020. }
  3021. if(earFound)
  3022. {
  3023. tgs.push(i0, i1, i2);
  3024. avl.splice((i+1)%al, 1);
  3025. al--;
  3026. i = 0;
  3027. }
  3028. else if(i++ > 3*al)
  3029. {
  3030. // need to flip flip reverse it!
  3031. // reset!
  3032. if(sign)
  3033. {
  3034. tgs = [];
  3035. avl = [];
  3036. for(i = 0; i < n; i++) avl.push(i);
  3037. i = 0;
  3038. al = n;
  3039. sign = false;
  3040. }
  3041. else
  3042. {
  3043. window.console.log("PIXI Warning: shape too complex to fill");
  3044. return [];
  3045. }
  3046. }
  3047. }
  3048. tgs.push(avl[0], avl[1], avl[2]);
  3049. return tgs;
  3050. };
  3051. /**
  3052. * Checks whether a point is within a triangle
  3053. *
  3054. * @method _PointInTriangle
  3055. * @param px {Number} x coordinate of the point to test
  3056. * @param py {Number} y coordinate of the point to test
  3057. * @param ax {Number} x coordinate of the a point of the triangle
  3058. * @param ay {Number} y coordinate of the a point of the triangle
  3059. * @param bx {Number} x coordinate of the b point of the triangle
  3060. * @param by {Number} y coordinate of the b point of the triangle
  3061. * @param cx {Number} x coordinate of the c point of the triangle
  3062. * @param cy {Number} y coordinate of the c point of the triangle
  3063. * @private
  3064. */
  3065. PIXI.PolyK._PointInTriangle = function(px, py, ax, ay, bx, by, cx, cy)
  3066. {
  3067. var v0x = cx-ax;
  3068. var v0y = cy-ay;
  3069. var v1x = bx-ax;
  3070. var v1y = by-ay;
  3071. var v2x = px-ax;
  3072. var v2y = py-ay;
  3073. var dot00 = v0x*v0x+v0y*v0y;
  3074. var dot01 = v0x*v1x+v0y*v1y;
  3075. var dot02 = v0x*v2x+v0y*v2y;
  3076. var dot11 = v1x*v1x+v1y*v1y;
  3077. var dot12 = v1x*v2x+v1y*v2y;
  3078. var invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
  3079. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  3080. var v = (dot00 * dot12 - dot01 * dot02) * invDenom;
  3081. // Check if point is in triangle
  3082. return (u >= 0) && (v >= 0) && (u + v < 1);
  3083. };
  3084. /**
  3085. * Checks whether a shape is convex
  3086. *
  3087. * @method _convex
  3088. *
  3089. * @private
  3090. */
  3091. PIXI.PolyK._convex = function(ax, ay, bx, by, cx, cy, sign)
  3092. {
  3093. return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign;
  3094. };
  3095. /**
  3096. * @author Mat Groves http://matgroves.com/ @Doormat23
  3097. */
  3098. // TODO Alvin and Mat
  3099. // Should we eventually create a Utils class ?
  3100. // Or just move this file to the pixi.js file ?
  3101. PIXI.initDefaultShaders = function()
  3102. {
  3103. // PIXI.stripShader = new PIXI.StripShader();
  3104. // PIXI.stripShader.init();
  3105. };
  3106. PIXI.CompileVertexShader = function(gl, shaderSrc)
  3107. {
  3108. return PIXI._CompileShader(gl, shaderSrc, gl.VERTEX_SHADER);
  3109. };
  3110. PIXI.CompileFragmentShader = function(gl, shaderSrc)
  3111. {
  3112. return PIXI._CompileShader(gl, shaderSrc, gl.FRAGMENT_SHADER);
  3113. };
  3114. PIXI._CompileShader = function(gl, shaderSrc, shaderType)
  3115. {
  3116. var src = shaderSrc.join("\n");
  3117. var shader = gl.createShader(shaderType);
  3118. gl.shaderSource(shader, src);
  3119. gl.compileShader(shader);
  3120. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3121. window.console.log(gl.getShaderInfoLog(shader));
  3122. return null;
  3123. }
  3124. return shader;
  3125. };
  3126. PIXI.compileProgram = function(gl, vertexSrc, fragmentSrc)
  3127. {
  3128. var fragmentShader = PIXI.CompileFragmentShader(gl, fragmentSrc);
  3129. var vertexShader = PIXI.CompileVertexShader(gl, vertexSrc);
  3130. var shaderProgram = gl.createProgram();
  3131. gl.attachShader(shaderProgram, vertexShader);
  3132. gl.attachShader(shaderProgram, fragmentShader);
  3133. gl.linkProgram(shaderProgram);
  3134. if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
  3135. window.console.log("Could not initialise shaders");
  3136. }
  3137. return shaderProgram;
  3138. };
  3139. /**
  3140. * @author Mat Groves http://matgroves.com/ @Doormat23
  3141. * @author Richard Davey http://www.photonstorm.com @photonstorm
  3142. */
  3143. /**
  3144. * @class PixiShader
  3145. * @constructor
  3146. */
  3147. PIXI.PixiShader = function(gl)
  3148. {
  3149. this._UID = PIXI._UID++;
  3150. /**
  3151. * @property gl
  3152. * @type WebGLContext
  3153. */
  3154. this.gl = gl;
  3155. /**
  3156. * @property {any} program - The WebGL program.
  3157. */
  3158. this.program = null;
  3159. /**
  3160. * @property {array} fragmentSrc - The fragment shader.
  3161. */
  3162. this.fragmentSrc = [
  3163. 'precision lowp float;',
  3164. 'varying vec2 vTextureCoord;',
  3165. 'varying vec4 vColor;',
  3166. 'uniform sampler2D uSampler;',
  3167. 'void main(void) {',
  3168. ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;',
  3169. '}'
  3170. ];
  3171. /**
  3172. * @property {number} textureCount - A local texture counter for multi-texture shaders.
  3173. */
  3174. this.textureCount = 0;
  3175. this.attributes = [];
  3176. this.init();
  3177. };
  3178. /**
  3179. * Initialises the shader
  3180. * @method init
  3181. *
  3182. */
  3183. PIXI.PixiShader.prototype.init = function()
  3184. {
  3185. var gl = this.gl;
  3186. var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc);
  3187. gl.useProgram(program);
  3188. // get and store the uniforms for the shader
  3189. this.uSampler = gl.getUniformLocation(program, 'uSampler');
  3190. this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
  3191. this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
  3192. this.dimensions = gl.getUniformLocation(program, 'dimensions');
  3193. // get and store the attributes
  3194. this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
  3195. this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord');
  3196. this.colorAttribute = gl.getAttribLocation(program, 'aColor');
  3197. // Begin worst hack eva //
  3198. // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters?
  3199. // maybe its something to do with the current state of the gl context.
  3200. // 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
  3201. // If theres any webGL people that know why could happen please help :)
  3202. if(this.colorAttribute === -1)
  3203. {
  3204. this.colorAttribute = 2;
  3205. }
  3206. this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute];
  3207. // End worst hack eva //
  3208. // add those custom shaders!
  3209. for (var key in this.uniforms)
  3210. {
  3211. // get the uniform locations..
  3212. this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key);
  3213. }
  3214. this.initUniforms();
  3215. this.program = program;
  3216. };
  3217. /**
  3218. * Initialises the shader uniform values.
  3219. * Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/
  3220. * http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf
  3221. *
  3222. * @method initUniforms
  3223. */
  3224. PIXI.PixiShader.prototype.initUniforms = function()
  3225. {
  3226. this.textureCount = 1;
  3227. var gl = this.gl;
  3228. var uniform;
  3229. for (var key in this.uniforms)
  3230. {
  3231. uniform = this.uniforms[key];
  3232. var type = uniform.type;
  3233. if (type === 'sampler2D')
  3234. {
  3235. uniform._init = false;
  3236. if (uniform.value !== null)
  3237. {
  3238. this.initSampler2D(uniform);
  3239. }
  3240. }
  3241. else if (type === 'mat2' || type === 'mat3' || type === 'mat4')
  3242. {
  3243. // These require special handling
  3244. uniform.glMatrix = true;
  3245. uniform.glValueLength = 1;
  3246. if (type === 'mat2')
  3247. {
  3248. uniform.glFunc = gl.uniformMatrix2fv;
  3249. }
  3250. else if (type === 'mat3')
  3251. {
  3252. uniform.glFunc = gl.uniformMatrix3fv;
  3253. }
  3254. else if (type === 'mat4')
  3255. {
  3256. uniform.glFunc = gl.uniformMatrix4fv;
  3257. }
  3258. }
  3259. else
  3260. {
  3261. // GL function reference
  3262. uniform.glFunc = gl['uniform' + type];
  3263. if (type === '2f' || type === '2i')
  3264. {
  3265. uniform.glValueLength = 2;
  3266. }
  3267. else if (type === '3f' || type === '3i')
  3268. {
  3269. uniform.glValueLength = 3;
  3270. }
  3271. else if (type === '4f' || type === '4i')
  3272. {
  3273. uniform.glValueLength = 4;
  3274. }
  3275. else
  3276. {
  3277. uniform.glValueLength = 1;
  3278. }
  3279. }
  3280. }
  3281. };
  3282. /**
  3283. * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded)
  3284. *
  3285. * @method initSampler2D
  3286. */
  3287. PIXI.PixiShader.prototype.initSampler2D = function(uniform)
  3288. {
  3289. if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded)
  3290. {
  3291. return;
  3292. }
  3293. var gl = this.gl;
  3294. gl.activeTexture(gl['TEXTURE' + this.textureCount]);
  3295. gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]);
  3296. // Extended texture data
  3297. if (uniform.textureData)
  3298. {
  3299. var data = uniform.textureData;
  3300. // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D);
  3301. // GLTextureLinear = mag/min linear, wrap clamp
  3302. // GLTextureNearestRepeat = mag/min NEAREST, wrap repeat
  3303. // GLTextureNearest = mag/min nearest, wrap clamp
  3304. // AudioTexture = whatever + luminance + width 512, height 2, border 0
  3305. // KeyTexture = whatever + luminance + width 256, height 2, border 0
  3306. // magFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST
  3307. // wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT
  3308. var magFilter = (data.magFilter) ? data.magFilter : gl.LINEAR;
  3309. var minFilter = (data.minFilter) ? data.minFilter : gl.LINEAR;
  3310. var wrapS = (data.wrapS) ? data.wrapS : gl.CLAMP_TO_EDGE;
  3311. var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE;
  3312. var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA;
  3313. if (data.repeat)
  3314. {
  3315. wrapS = gl.REPEAT;
  3316. wrapT = gl.REPEAT;
  3317. }
  3318. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY);
  3319. if (data.width)
  3320. {
  3321. var width = (data.width) ? data.width : 512;
  3322. var height = (data.height) ? data.height : 2;
  3323. var border = (data.border) ? data.border : 0;
  3324. // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels);
  3325. gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, border, format, gl.UNSIGNED_BYTE, null);
  3326. }
  3327. else
  3328. {
  3329. // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, ImageData? pixels);
  3330. gl.texImage2D(gl.TEXTURE_2D, 0, format, gl.RGBA, gl.UNSIGNED_BYTE, uniform.value.baseTexture.source);
  3331. }
  3332. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3333. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3334. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapS);
  3335. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapT);
  3336. }
  3337. gl.uniform1i(uniform.uniformLocation, this.textureCount);
  3338. uniform._init = true;
  3339. this.textureCount++;
  3340. };
  3341. /**
  3342. * Updates the shader uniform values.
  3343. *
  3344. * @method syncUniforms
  3345. */
  3346. PIXI.PixiShader.prototype.syncUniforms = function()
  3347. {
  3348. this.textureCount = 1;
  3349. var uniform;
  3350. var gl = this.gl;
  3351. // This would probably be faster in an array and it would guarantee key order
  3352. for (var key in this.uniforms)
  3353. {
  3354. uniform = this.uniforms[key];
  3355. if (uniform.glValueLength === 1)
  3356. {
  3357. if (uniform.glMatrix === true)
  3358. {
  3359. uniform.glFunc.call(gl, uniform.uniformLocation, uniform.transpose, uniform.value);
  3360. }
  3361. else
  3362. {
  3363. uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value);
  3364. }
  3365. }
  3366. else if (uniform.glValueLength === 2)
  3367. {
  3368. uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value.x, uniform.value.y);
  3369. }
  3370. else if (uniform.glValueLength === 3)
  3371. {
  3372. uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value.x, uniform.value.y, uniform.value.z);
  3373. }
  3374. else if (uniform.glValueLength === 4)
  3375. {
  3376. uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value.x, uniform.value.y, uniform.value.z, uniform.value.w);
  3377. }
  3378. else if (uniform.type === 'sampler2D')
  3379. {
  3380. if (uniform._init)
  3381. {
  3382. gl.activeTexture(gl['TEXTURE' + this.textureCount]);
  3383. gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id] || PIXI.createWebGLTexture( uniform.value.baseTexture, gl));
  3384. gl.uniform1i(uniform.uniformLocation, this.textureCount);
  3385. this.textureCount++;
  3386. }
  3387. else
  3388. {
  3389. this.initSampler2D(uniform);
  3390. }
  3391. }
  3392. }
  3393. };
  3394. /**
  3395. * Destroys the shader
  3396. * @method destroy
  3397. */
  3398. PIXI.PixiShader.prototype.destroy = function()
  3399. {
  3400. this.gl.deleteProgram( this.program );
  3401. this.uniforms = null;
  3402. this.gl = null;
  3403. this.attributes = null;
  3404. };
  3405. /**
  3406. * The Default Vertex shader source
  3407. * @property defaultVertexSrc
  3408. * @type String
  3409. */
  3410. PIXI.PixiShader.defaultVertexSrc = [
  3411. 'attribute vec2 aVertexPosition;',
  3412. 'attribute vec2 aTextureCoord;',
  3413. 'attribute vec2 aColor;',
  3414. 'uniform vec2 projectionVector;',
  3415. 'uniform vec2 offsetVector;',
  3416. 'varying vec2 vTextureCoord;',
  3417. 'varying vec4 vColor;',
  3418. 'const vec2 center = vec2(-1.0, 1.0);',
  3419. 'void main(void) {',
  3420. ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);',
  3421. ' vTextureCoord = aTextureCoord;',
  3422. ' vec3 color = mod(vec3(aColor.y/65536.0, aColor.y/256.0, aColor.y), 256.0) / 256.0;',
  3423. ' vColor = vec4(color * aColor.x, aColor.x);',
  3424. '}'
  3425. ];
  3426. /**
  3427. * @author Mat Groves http://matgroves.com/ @Doormat23
  3428. * @author Richard Davey http://www.photonstorm.com @photonstorm
  3429. */
  3430. /**
  3431. * @class PixiFastShader
  3432. * @constructor
  3433. * @param gl {WebGLContext} the current WebGL drawing context
  3434. */
  3435. PIXI.PixiFastShader = function(gl)
  3436. {
  3437. this._UID = PIXI._UID++;
  3438. /**
  3439. * @property gl
  3440. * @type WebGLContext
  3441. */
  3442. this.gl = gl;
  3443. /**
  3444. * @property {any} program - The WebGL program.
  3445. */
  3446. this.program = null;
  3447. /**
  3448. * @property {array} fragmentSrc - The fragment shader.
  3449. */
  3450. this.fragmentSrc = [
  3451. 'precision lowp float;',
  3452. 'varying vec2 vTextureCoord;',
  3453. 'varying float vColor;',
  3454. 'uniform sampler2D uSampler;',
  3455. 'void main(void) {',
  3456. ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;',
  3457. '}'
  3458. ];
  3459. /**
  3460. * @property {array} vertexSrc - The vertex shader
  3461. */
  3462. this.vertexSrc = [
  3463. 'attribute vec2 aVertexPosition;',
  3464. 'attribute vec2 aPositionCoord;',
  3465. 'attribute vec2 aScale;',
  3466. 'attribute float aRotation;',
  3467. 'attribute vec2 aTextureCoord;',
  3468. 'attribute float aColor;',
  3469. 'uniform vec2 projectionVector;',
  3470. 'uniform vec2 offsetVector;',
  3471. 'uniform mat3 uMatrix;',
  3472. 'varying vec2 vTextureCoord;',
  3473. 'varying float vColor;',
  3474. 'const vec2 center = vec2(-1.0, 1.0);',
  3475. 'void main(void) {',
  3476. ' vec2 v;',
  3477. ' vec2 sv = aVertexPosition * aScale;',
  3478. ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);',
  3479. ' v.y = (sv.x) * sin(aRotation) + (sv.y) * cos(aRotation);',
  3480. ' v = ( uMatrix * vec3(v + aPositionCoord , 1.0) ).xy ;',
  3481. ' gl_Position = vec4( ( v / projectionVector) + center , 0.0, 1.0);',
  3482. ' vTextureCoord = aTextureCoord;',
  3483. // ' vec3 color = mod(vec3(aColor.y/65536.0, aColor.y/256.0, aColor.y), 256.0) / 256.0;',
  3484. ' vColor = aColor;',
  3485. '}'
  3486. ];
  3487. /**
  3488. * @property {number} textureCount - A local texture counter for multi-texture shaders.
  3489. */
  3490. this.textureCount = 0;
  3491. this.init();
  3492. };
  3493. /**
  3494. * Initialises the shader
  3495. * @method init
  3496. *
  3497. */
  3498. PIXI.PixiFastShader.prototype.init = function()
  3499. {
  3500. var gl = this.gl;
  3501. var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
  3502. gl.useProgram(program);
  3503. // get and store the uniforms for the shader
  3504. this.uSampler = gl.getUniformLocation(program, 'uSampler');
  3505. this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
  3506. this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
  3507. this.dimensions = gl.getUniformLocation(program, 'dimensions');
  3508. this.uMatrix = gl.getUniformLocation(program, 'uMatrix');
  3509. // get and store the attributes
  3510. this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
  3511. this.aPositionCoord = gl.getAttribLocation(program, 'aPositionCoord');
  3512. this.aScale = gl.getAttribLocation(program, 'aScale');
  3513. this.aRotation = gl.getAttribLocation(program, 'aRotation');
  3514. this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord');
  3515. this.colorAttribute = gl.getAttribLocation(program, 'aColor');
  3516. // Begin worst hack eva //
  3517. // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters?
  3518. // maybe its somthing to do with the current state of the gl context.
  3519. // 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
  3520. // If theres any webGL people that know why could happen please help :)
  3521. if(this.colorAttribute === -1)
  3522. {
  3523. this.colorAttribute = 2;
  3524. }
  3525. this.attributes = [this.aVertexPosition, this.aPositionCoord, this.aScale, this.aRotation, this.aTextureCoord, this.colorAttribute];
  3526. // End worst hack eva //
  3527. this.program = program;
  3528. };
  3529. /**
  3530. * Destroys the shader
  3531. * @method destroy
  3532. *
  3533. */
  3534. PIXI.PixiFastShader.prototype.destroy = function()
  3535. {
  3536. this.gl.deleteProgram( this.program );
  3537. this.uniforms = null;
  3538. this.gl = null;
  3539. this.attributes = null;
  3540. };
  3541. /**
  3542. * @author Mat Groves http://matgroves.com/ @Doormat23
  3543. */
  3544. PIXI.StripShader = function(gl)
  3545. {
  3546. this._UID = PIXI._UID++;
  3547. this.gl = gl;
  3548. /**
  3549. * @property {any} program - The WebGL program.
  3550. */
  3551. this.program = null;
  3552. /**
  3553. * @property {array} fragmentSrc - The fragment shader.
  3554. */
  3555. this.fragmentSrc = [
  3556. 'precision mediump float;',
  3557. 'varying vec2 vTextureCoord;',
  3558. // 'varying float vColor;',
  3559. 'uniform float alpha;',
  3560. 'uniform sampler2D uSampler;',
  3561. 'void main(void) {',
  3562. ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y));',
  3563. // ' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);',//gl_FragColor * alpha;',
  3564. '}'
  3565. ];
  3566. /**
  3567. * @property {array} fragmentSrc - The fragment shader.
  3568. */
  3569. this.vertexSrc = [
  3570. 'attribute vec2 aVertexPosition;',
  3571. 'attribute vec2 aTextureCoord;',
  3572. 'uniform mat3 translationMatrix;',
  3573. 'uniform vec2 projectionVector;',
  3574. 'uniform vec2 offsetVector;',
  3575. // 'uniform float alpha;',
  3576. // 'uniform vec3 tint;',
  3577. 'varying vec2 vTextureCoord;',
  3578. // 'varying vec4 vColor;',
  3579. 'void main(void) {',
  3580. ' vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);',
  3581. ' v -= offsetVector.xyx;',
  3582. ' gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / -projectionVector.y + 1.0 , 0.0, 1.0);',
  3583. ' vTextureCoord = aTextureCoord;',
  3584. // ' vColor = aColor * vec4(tint * alpha, alpha);',
  3585. '}'
  3586. ];
  3587. this.init();
  3588. };
  3589. /**
  3590. * Initialises the shader
  3591. * @method init
  3592. *
  3593. */
  3594. PIXI.StripShader.prototype.init = function()
  3595. {
  3596. var gl = this.gl;
  3597. var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
  3598. gl.useProgram(program);
  3599. // get and store the uniforms for the shader
  3600. this.uSampler = gl.getUniformLocation(program, 'uSampler');
  3601. this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
  3602. this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
  3603. this.colorAttribute = gl.getAttribLocation(program, 'aColor');
  3604. //this.dimensions = gl.getUniformLocation(this.program, 'dimensions');
  3605. // get and store the attributes
  3606. this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
  3607. this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord');
  3608. this.attributes = [this.aVertexPosition, this.aTextureCoord];
  3609. this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix');
  3610. this.alpha = gl.getUniformLocation(program, 'alpha');
  3611. this.program = program;
  3612. };
  3613. /**
  3614. * @author Mat Groves http://matgroves.com/ @Doormat23
  3615. */
  3616. /**
  3617. * @class PrimitiveShader
  3618. * @constructor
  3619. * @param gl {WebGLContext} the current WebGL drawing context
  3620. */
  3621. PIXI.PrimitiveShader = function(gl)
  3622. {
  3623. this._UID = PIXI._UID++;
  3624. /**
  3625. * @property gl
  3626. * @type WebGLContext
  3627. */
  3628. this.gl = gl;
  3629. /**
  3630. * @property {any} program - The WebGL program.
  3631. */
  3632. this.program = null;
  3633. /**
  3634. * @property fragmentSrc
  3635. * @type Array
  3636. */
  3637. this.fragmentSrc = [
  3638. 'precision mediump float;',
  3639. 'varying vec4 vColor;',
  3640. 'void main(void) {',
  3641. ' gl_FragColor = vColor;',
  3642. '}'
  3643. ];
  3644. /**
  3645. * @property vertexSrc
  3646. * @type Array
  3647. */
  3648. this.vertexSrc = [
  3649. 'attribute vec2 aVertexPosition;',
  3650. 'attribute vec4 aColor;',
  3651. 'uniform mat3 translationMatrix;',
  3652. 'uniform vec2 projectionVector;',
  3653. 'uniform vec2 offsetVector;',
  3654. 'uniform float alpha;',
  3655. 'uniform vec3 tint;',
  3656. 'varying vec4 vColor;',
  3657. 'void main(void) {',
  3658. ' vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);',
  3659. ' v -= offsetVector.xyx;',
  3660. ' gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / -projectionVector.y + 1.0 , 0.0, 1.0);',
  3661. ' vColor = aColor * vec4(tint * alpha, alpha);',
  3662. '}'
  3663. ];
  3664. this.init();
  3665. };
  3666. /**
  3667. * Initialises the shader
  3668. * @method init
  3669. *
  3670. */
  3671. PIXI.PrimitiveShader.prototype.init = function()
  3672. {
  3673. var gl = this.gl;
  3674. var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
  3675. gl.useProgram(program);
  3676. // get and store the uniforms for the shader
  3677. this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
  3678. this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
  3679. this.tintColor = gl.getUniformLocation(program, 'tint');
  3680. // get and store the attributes
  3681. this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
  3682. this.colorAttribute = gl.getAttribLocation(program, 'aColor');
  3683. this.attributes = [this.aVertexPosition, this.colorAttribute];
  3684. this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix');
  3685. this.alpha = gl.getUniformLocation(program, 'alpha');
  3686. this.program = program;
  3687. };
  3688. /**
  3689. * Destroys the shader
  3690. * @method destroy
  3691. *
  3692. */
  3693. PIXI.PrimitiveShader.prototype.destroy = function()
  3694. {
  3695. this.gl.deleteProgram( this.program );
  3696. this.uniforms = null;
  3697. this.gl = null;
  3698. this.attribute = null;
  3699. };
  3700. /**
  3701. * @author Mat Groves http://matgroves.com/ @Doormat23
  3702. */
  3703. /**
  3704. * @class ComplexPrimitiveShader
  3705. * @constructor
  3706. * @param gl {WebGLContext} the current WebGL drawing context
  3707. */
  3708. PIXI.ComplexPrimitiveShader = function(gl)
  3709. {
  3710. this._UID = PIXI._UID++;
  3711. /**
  3712. * @property gl
  3713. * @type WebGLContext
  3714. */
  3715. this.gl = gl;
  3716. /**
  3717. * @property {any} program - The WebGL program.
  3718. */
  3719. this.program = null;
  3720. /**
  3721. * @property fragmentSrc
  3722. * @type Array
  3723. */
  3724. this.fragmentSrc = [
  3725. 'precision mediump float;',
  3726. 'varying vec4 vColor;',
  3727. 'void main(void) {',
  3728. ' gl_FragColor = vColor;',
  3729. '}'
  3730. ];
  3731. /**
  3732. * @property vertexSrc
  3733. * @type Array
  3734. */
  3735. this.vertexSrc = [
  3736. 'attribute vec2 aVertexPosition;',
  3737. //'attribute vec4 aColor;',
  3738. 'uniform mat3 translationMatrix;',
  3739. 'uniform vec2 projectionVector;',
  3740. 'uniform vec2 offsetVector;',
  3741. 'uniform vec3 tint;',
  3742. 'uniform float alpha;',
  3743. 'uniform vec3 color;',
  3744. 'varying vec4 vColor;',
  3745. 'void main(void) {',
  3746. ' vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);',
  3747. ' v -= offsetVector.xyx;',
  3748. ' gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / -projectionVector.y + 1.0 , 0.0, 1.0);',
  3749. ' vColor = vec4(color * alpha * tint, alpha);',//" * vec4(tint * alpha, alpha);',
  3750. '}'
  3751. ];
  3752. this.init();
  3753. };
  3754. /**
  3755. * Initialises the shader
  3756. * @method init
  3757. *
  3758. */
  3759. PIXI.ComplexPrimitiveShader.prototype.init = function()
  3760. {
  3761. var gl = this.gl;
  3762. var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
  3763. gl.useProgram(program);
  3764. // get and store the uniforms for the shader
  3765. this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
  3766. this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
  3767. this.tintColor = gl.getUniformLocation(program, 'tint');
  3768. this.color = gl.getUniformLocation(program, 'color');
  3769. // get and store the attributes
  3770. this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
  3771. // this.colorAttribute = gl.getAttribLocation(program, 'aColor');
  3772. this.attributes = [this.aVertexPosition, this.colorAttribute];
  3773. this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix');
  3774. this.alpha = gl.getUniformLocation(program, 'alpha');
  3775. this.program = program;
  3776. };
  3777. /**
  3778. * Destroys the shader
  3779. * @method destroy
  3780. *
  3781. */
  3782. PIXI.ComplexPrimitiveShader.prototype.destroy = function()
  3783. {
  3784. this.gl.deleteProgram( this.program );
  3785. this.uniforms = null;
  3786. this.gl = null;
  3787. this.attribute = null;
  3788. };
  3789. /**
  3790. * @author Mat Groves http://matgroves.com/ @Doormat23
  3791. */
  3792. /**
  3793. * A set of functions used by the webGL renderer to draw the primitive graphics data
  3794. *
  3795. * @class WebGLGraphics
  3796. * @private
  3797. * @static
  3798. */
  3799. PIXI.WebGLGraphics = function()
  3800. {
  3801. };
  3802. /**
  3803. * Renders the graphics object
  3804. *
  3805. * @static
  3806. * @private
  3807. * @method renderGraphics
  3808. * @param graphics {Graphics}
  3809. * @param renderSession {Object}
  3810. */
  3811. PIXI.WebGLGraphics.renderGraphics = function(graphics, renderSession)//projection, offset)
  3812. {
  3813. var gl = renderSession.gl;
  3814. var projection = renderSession.projection,
  3815. offset = renderSession.offset,
  3816. shader = renderSession.shaderManager.primitiveShader,
  3817. webGLData;
  3818. if(graphics.dirty)
  3819. {
  3820. PIXI.WebGLGraphics.updateGraphics(graphics, gl);
  3821. }
  3822. var webGL = graphics._webGL[gl.id];
  3823. // This could be speeded up for sure!
  3824. for (var i = 0; i < webGL.data.length; i++)
  3825. {
  3826. if(webGL.data[i].mode === 1)
  3827. {
  3828. webGLData = webGL.data[i];
  3829. renderSession.stencilManager.pushStencil(graphics, webGLData, renderSession);
  3830. // render quad..
  3831. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 );
  3832. renderSession.stencilManager.popStencil(graphics, webGLData, renderSession);
  3833. this.last = webGLData.mode;
  3834. }
  3835. else
  3836. {
  3837. webGLData = webGL.data[i];
  3838. renderSession.shaderManager.setShader( shader );//activatePrimitiveShader();
  3839. shader = renderSession.shaderManager.primitiveShader;
  3840. gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true));
  3841. gl.uniform2f(shader.projectionVector, projection.x, -projection.y);
  3842. gl.uniform2f(shader.offsetVector, -offset.x, -offset.y);
  3843. gl.uniform3fv(shader.tintColor, PIXI.hex2rgb(graphics.tint));
  3844. gl.uniform1f(shader.alpha, graphics.worldAlpha);
  3845. gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer);
  3846. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0);
  3847. gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4);
  3848. // set the index buffer!
  3849. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer);
  3850. gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 );
  3851. }
  3852. }
  3853. };
  3854. /**
  3855. * Updates the graphics object
  3856. *
  3857. * @static
  3858. * @private
  3859. * @method updateGraphics
  3860. * @param graphicsData {Graphics} The graphics object to update
  3861. * @param gl {WebGLContext} the current WebGL drawing context
  3862. */
  3863. PIXI.WebGLGraphics.updateGraphics = function(graphics, gl)
  3864. {
  3865. // get the contexts graphics object
  3866. var webGL = graphics._webGL[gl.id];
  3867. // if the graphics object does not exist in the webGL context time to create it!
  3868. if(!webGL)webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl};
  3869. // flag the graphics as not dirty as we are about to update it...
  3870. graphics.dirty = false;
  3871. var i;
  3872. // if the user cleared the graphics object we will need to clear every object
  3873. if(graphics.clearDirty)
  3874. {
  3875. graphics.clearDirty = false;
  3876. // lop through and return all the webGLDatas to the object pool so than can be reused later on
  3877. for (i = 0; i < webGL.data.length; i++)
  3878. {
  3879. var graphicsData = webGL.data[i];
  3880. graphicsData.reset();
  3881. PIXI.WebGLGraphics.graphicsDataPool.push( graphicsData );
  3882. }
  3883. // clear the array and reset the index..
  3884. webGL.data = [];
  3885. webGL.lastIndex = 0;
  3886. }
  3887. var webGLData;
  3888. // loop through the graphics datas and construct each one..
  3889. // if the object is a complex fill then the new stencil buffer technique will be used
  3890. // other wise graphics objects will be pushed into a batch..
  3891. for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++)
  3892. {
  3893. var data = graphics.graphicsData[i];
  3894. if(data.type === PIXI.Graphics.POLY)
  3895. {
  3896. // MAKE SURE WE HAVE THE CORRECT TYPE..
  3897. if(data.fill)
  3898. {
  3899. if(data.points.length > 6)
  3900. {
  3901. if(data.points.length > 5 * 2)
  3902. {
  3903. webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1);
  3904. PIXI.WebGLGraphics.buildComplexPoly(data, webGLData);
  3905. }
  3906. else
  3907. {
  3908. webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0);
  3909. PIXI.WebGLGraphics.buildPoly(data, webGLData);
  3910. }
  3911. }
  3912. }
  3913. if(data.lineWidth > 0)
  3914. {
  3915. webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0);
  3916. PIXI.WebGLGraphics.buildLine(data, webGLData);
  3917. }
  3918. }
  3919. else
  3920. {
  3921. webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0);
  3922. if(data.type === PIXI.Graphics.RECT)
  3923. {
  3924. PIXI.WebGLGraphics.buildRectangle(data, webGLData);
  3925. }
  3926. else if(data.type === PIXI.Graphics.CIRC || data.type === PIXI.Graphics.ELIP)
  3927. {
  3928. PIXI.WebGLGraphics.buildCircle(data, webGLData);
  3929. }
  3930. else if(data.type === PIXI.Graphics.RREC)
  3931. {
  3932. PIXI.WebGLGraphics.buildRoundedRectangle(data, webGLData);
  3933. }
  3934. }
  3935. webGL.lastIndex++;
  3936. }
  3937. // upload all the dirty data...
  3938. for (i = 0; i < webGL.data.length; i++)
  3939. {
  3940. webGLData = webGL.data[i];
  3941. if(webGLData.dirty)webGLData.upload();
  3942. }
  3943. };
  3944. PIXI.WebGLGraphics.switchMode = function(webGL, type)
  3945. {
  3946. var webGLData;
  3947. if(!webGL.data.length)
  3948. {
  3949. webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl);
  3950. webGLData.mode = type;
  3951. webGL.data.push(webGLData);
  3952. }
  3953. else
  3954. {
  3955. webGLData = webGL.data[webGL.data.length-1];
  3956. if(webGLData.mode !== type || type === 1)
  3957. {
  3958. webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl);
  3959. webGLData.mode = type;
  3960. webGL.data.push(webGLData);
  3961. }
  3962. }
  3963. webGLData.dirty = true;
  3964. return webGLData;
  3965. };
  3966. /**
  3967. * Builds a rectangle to draw
  3968. *
  3969. * @static
  3970. * @private
  3971. * @method buildRectangle
  3972. * @param graphicsData {Graphics} The graphics object containing all the necessary properties
  3973. * @param webGLData {Object}
  3974. */
  3975. PIXI.WebGLGraphics.buildRectangle = function(graphicsData, webGLData)
  3976. {
  3977. // --- //
  3978. // need to convert points to a nice regular data
  3979. //
  3980. var rectData = graphicsData.points;
  3981. var x = rectData[0];
  3982. var y = rectData[1];
  3983. var width = rectData[2];
  3984. var height = rectData[3];
  3985. if(graphicsData.fill)
  3986. {
  3987. var color = PIXI.hex2rgb(graphicsData.fillColor);
  3988. var alpha = graphicsData.fillAlpha;
  3989. var r = color[0] * alpha;
  3990. var g = color[1] * alpha;
  3991. var b = color[2] * alpha;
  3992. var verts = webGLData.points;
  3993. var indices = webGLData.indices;
  3994. var vertPos = verts.length/6;
  3995. // start
  3996. verts.push(x, y);
  3997. verts.push(r, g, b, alpha);
  3998. verts.push(x + width, y);
  3999. verts.push(r, g, b, alpha);
  4000. verts.push(x , y + height);
  4001. verts.push(r, g, b, alpha);
  4002. verts.push(x + width, y + height);
  4003. verts.push(r, g, b, alpha);
  4004. // insert 2 dead triangles..
  4005. indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3);
  4006. }
  4007. if(graphicsData.lineWidth)
  4008. {
  4009. var tempPoints = graphicsData.points;
  4010. graphicsData.points = [x, y,
  4011. x + width, y,
  4012. x + width, y + height,
  4013. x, y + height,
  4014. x, y];
  4015. PIXI.WebGLGraphics.buildLine(graphicsData, webGLData);
  4016. graphicsData.points = tempPoints;
  4017. }
  4018. };
  4019. /**
  4020. * Builds a rounded rectangle to draw
  4021. *
  4022. * @static
  4023. * @private
  4024. * @method buildRoundedRectangle
  4025. * @param graphicsData {Graphics} The graphics object containing all the necessary properties
  4026. * @param webGLData {Object}
  4027. */
  4028. PIXI.WebGLGraphics.buildRoundedRectangle = function(graphicsData, webGLData)
  4029. {
  4030. var points = graphicsData.points;
  4031. var x = points[0];
  4032. var y = points[1];
  4033. var width = points[2];
  4034. var height = points[3];
  4035. var radius = points[4];
  4036. var recPoints = [];
  4037. recPoints.push(x, y + radius);
  4038. recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height));
  4039. recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius));
  4040. recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y));
  4041. recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius));
  4042. if (graphicsData.fill) {
  4043. var color = PIXI.hex2rgb(graphicsData.fillColor);
  4044. var alpha = graphicsData.fillAlpha;
  4045. var r = color[0] * alpha;
  4046. var g = color[1] * alpha;
  4047. var b = color[2] * alpha;
  4048. var verts = webGLData.points;
  4049. var indices = webGLData.indices;
  4050. var vecPos = verts.length/6;
  4051. var triangles = PIXI.PolyK.Triangulate(recPoints);
  4052. var i = 0;
  4053. for (i = 0; i < triangles.length; i+=3)
  4054. {
  4055. indices.push(triangles[i] + vecPos);
  4056. indices.push(triangles[i] + vecPos);
  4057. indices.push(triangles[i+1] + vecPos);
  4058. indices.push(triangles[i+2] + vecPos);
  4059. indices.push(triangles[i+2] + vecPos);
  4060. }
  4061. for (i = 0; i < recPoints.length; i++)
  4062. {
  4063. verts.push(recPoints[i], recPoints[++i], r, g, b, alpha);
  4064. }
  4065. }
  4066. if (graphicsData.lineWidth) {
  4067. var tempPoints = graphicsData.points;
  4068. graphicsData.points = recPoints;
  4069. PIXI.WebGLGraphics.buildLine(graphicsData, webGLData);
  4070. graphicsData.points = tempPoints;
  4071. }
  4072. };
  4073. /**
  4074. * Calcul the points for a quadratic bezier curve. (helper function..)
  4075. * Based on : https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
  4076. *
  4077. * @param {number} fromX Origin point x
  4078. * @param {number} fromY Origin point x
  4079. * @param {number} cpX Control point x
  4080. * @param {number} cpY Control point y
  4081. * @param {number} toX Destination point x
  4082. * @param {number} toY Destination point y
  4083. * @return {number[]}
  4084. */
  4085. PIXI.WebGLGraphics.quadraticBezierCurve = function(fromX, fromY, cpX, cpY, toX, toY) {
  4086. var xa,
  4087. ya,
  4088. xb,
  4089. yb,
  4090. x,
  4091. y,
  4092. n = 20,
  4093. points = [];
  4094. function getPt(n1 , n2, perc) {
  4095. var diff = n2 - n1;
  4096. return n1 + ( diff * perc );
  4097. }
  4098. var j = 0;
  4099. for (var i = 0; i <= n; i++ )
  4100. {
  4101. j = i / n;
  4102. // The Green Line
  4103. xa = getPt( fromX , cpX , j );
  4104. ya = getPt( fromY , cpY , j );
  4105. xb = getPt( cpX , toX , j );
  4106. yb = getPt( cpY , toY , j );
  4107. // The Black Dot
  4108. x = getPt( xa , xb , j );
  4109. y = getPt( ya , yb , j );
  4110. points.push(x, y);
  4111. }
  4112. return points;
  4113. };
  4114. /**
  4115. * Builds a circle to draw
  4116. *
  4117. * @static
  4118. * @private
  4119. * @method buildCircle
  4120. * @param graphicsData {Graphics} The graphics object to draw
  4121. * @param webGLData {Object}
  4122. */
  4123. PIXI.WebGLGraphics.buildCircle = function(graphicsData, webGLData)
  4124. {
  4125. // need to convert points to a nice regular data
  4126. var rectData = graphicsData.points;
  4127. var x = rectData[0];
  4128. var y = rectData[1];
  4129. var width = rectData[2];
  4130. var height = rectData[3];
  4131. var totalSegs = 40;
  4132. var seg = (Math.PI * 2) / totalSegs ;
  4133. var i = 0;
  4134. if(graphicsData.fill)
  4135. {
  4136. var color = PIXI.hex2rgb(graphicsData.fillColor);
  4137. var alpha = graphicsData.fillAlpha;
  4138. var r = color[0] * alpha;
  4139. var g = color[1] * alpha;
  4140. var b = color[2] * alpha;
  4141. var verts = webGLData.points;
  4142. var indices = webGLData.indices;
  4143. var vecPos = verts.length/6;
  4144. indices.push(vecPos);
  4145. for (i = 0; i < totalSegs + 1 ; i++)
  4146. {
  4147. verts.push(x,y, r, g, b, alpha);
  4148. verts.push(x + Math.sin(seg * i) * width,
  4149. y + Math.cos(seg * i) * height,
  4150. r, g, b, alpha);
  4151. indices.push(vecPos++, vecPos++);
  4152. }
  4153. indices.push(vecPos-1);
  4154. }
  4155. if(graphicsData.lineWidth)
  4156. {
  4157. var tempPoints = graphicsData.points;
  4158. graphicsData.points = [];
  4159. for (i = 0; i < totalSegs + 1; i++)
  4160. {
  4161. graphicsData.points.push(x + Math.sin(seg * i) * width,
  4162. y + Math.cos(seg * i) * height);
  4163. }
  4164. PIXI.WebGLGraphics.buildLine(graphicsData, webGLData);
  4165. graphicsData.points = tempPoints;
  4166. }
  4167. };
  4168. /**
  4169. * Builds a line to draw
  4170. *
  4171. * @static
  4172. * @private
  4173. * @method buildLine
  4174. * @param graphicsData {Graphics} The graphics object containing all the necessary properties
  4175. * @param webGLData {Object}
  4176. */
  4177. PIXI.WebGLGraphics.buildLine = function(graphicsData, webGLData)
  4178. {
  4179. // TODO OPTIMISE!
  4180. var i = 0;
  4181. var points = graphicsData.points;
  4182. if(points.length === 0)return;
  4183. // if the line width is an odd number add 0.5 to align to a whole pixel
  4184. if(graphicsData.lineWidth%2)
  4185. {
  4186. for (i = 0; i < points.length; i++) {
  4187. points[i] += 0.5;
  4188. }
  4189. }
  4190. // get first and last point.. figure out the middle!
  4191. var firstPoint = new PIXI.Point( points[0], points[1] );
  4192. var lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] );
  4193. // if the first point is the last point - gonna have issues :)
  4194. if(firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y)
  4195. {
  4196. // need to clone as we are going to slightly modify the shape..
  4197. points = points.slice();
  4198. points.pop();
  4199. points.pop();
  4200. lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] );
  4201. var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) *0.5;
  4202. var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) *0.5;
  4203. points.unshift(midPointX, midPointY);
  4204. points.push(midPointX, midPointY);
  4205. }
  4206. var verts = webGLData.points;
  4207. var indices = webGLData.indices;
  4208. var length = points.length / 2;
  4209. var indexCount = points.length;
  4210. var indexStart = verts.length/6;
  4211. // DRAW the Line
  4212. var width = graphicsData.lineWidth / 2;
  4213. // sort color
  4214. var color = PIXI.hex2rgb(graphicsData.lineColor);
  4215. var alpha = graphicsData.lineAlpha;
  4216. var r = color[0] * alpha;
  4217. var g = color[1] * alpha;
  4218. var b = color[2] * alpha;
  4219. var px, py, p1x, p1y, p2x, p2y, p3x, p3y;
  4220. var perpx, perpy, perp2x, perp2y, perp3x, perp3y;
  4221. var a1, b1, c1, a2, b2, c2;
  4222. var denom, pdist, dist;
  4223. p1x = points[0];
  4224. p1y = points[1];
  4225. p2x = points[2];
  4226. p2y = points[3];
  4227. perpx = -(p1y - p2y);
  4228. perpy = p1x - p2x;
  4229. dist = Math.sqrt(perpx*perpx + perpy*perpy);
  4230. perpx /= dist;
  4231. perpy /= dist;
  4232. perpx *= width;
  4233. perpy *= width;
  4234. // start
  4235. verts.push(p1x - perpx , p1y - perpy,
  4236. r, g, b, alpha);
  4237. verts.push(p1x + perpx , p1y + perpy,
  4238. r, g, b, alpha);
  4239. for (i = 1; i < length-1; i++)
  4240. {
  4241. p1x = points[(i-1)*2];
  4242. p1y = points[(i-1)*2 + 1];
  4243. p2x = points[(i)*2];
  4244. p2y = points[(i)*2 + 1];
  4245. p3x = points[(i+1)*2];
  4246. p3y = points[(i+1)*2 + 1];
  4247. perpx = -(p1y - p2y);
  4248. perpy = p1x - p2x;
  4249. dist = Math.sqrt(perpx*perpx + perpy*perpy);
  4250. perpx /= dist;
  4251. perpy /= dist;
  4252. perpx *= width;
  4253. perpy *= width;
  4254. perp2x = -(p2y - p3y);
  4255. perp2y = p2x - p3x;
  4256. dist = Math.sqrt(perp2x*perp2x + perp2y*perp2y);
  4257. perp2x /= dist;
  4258. perp2y /= dist;
  4259. perp2x *= width;
  4260. perp2y *= width;
  4261. a1 = (-perpy + p1y) - (-perpy + p2y);
  4262. b1 = (-perpx + p2x) - (-perpx + p1x);
  4263. c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y);
  4264. a2 = (-perp2y + p3y) - (-perp2y + p2y);
  4265. b2 = (-perp2x + p2x) - (-perp2x + p3x);
  4266. c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y);
  4267. denom = a1*b2 - a2*b1;
  4268. if(Math.abs(denom) < 0.1 )
  4269. {
  4270. denom+=10.1;
  4271. verts.push(p2x - perpx , p2y - perpy,
  4272. r, g, b, alpha);
  4273. verts.push(p2x + perpx , p2y + perpy,
  4274. r, g, b, alpha);
  4275. continue;
  4276. }
  4277. px = (b1*c2 - b2*c1)/denom;
  4278. py = (a2*c1 - a1*c2)/denom;
  4279. pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y);
  4280. if(pdist > 140 * 140)
  4281. {
  4282. perp3x = perpx - perp2x;
  4283. perp3y = perpy - perp2y;
  4284. dist = Math.sqrt(perp3x*perp3x + perp3y*perp3y);
  4285. perp3x /= dist;
  4286. perp3y /= dist;
  4287. perp3x *= width;
  4288. perp3y *= width;
  4289. verts.push(p2x - perp3x, p2y -perp3y);
  4290. verts.push(r, g, b, alpha);
  4291. verts.push(p2x + perp3x, p2y +perp3y);
  4292. verts.push(r, g, b, alpha);
  4293. verts.push(p2x - perp3x, p2y -perp3y);
  4294. verts.push(r, g, b, alpha);
  4295. indexCount++;
  4296. }
  4297. else
  4298. {
  4299. verts.push(px , py);
  4300. verts.push(r, g, b, alpha);
  4301. verts.push(p2x - (px-p2x), p2y - (py - p2y));
  4302. verts.push(r, g, b, alpha);
  4303. }
  4304. }
  4305. p1x = points[(length-2)*2];
  4306. p1y = points[(length-2)*2 + 1];
  4307. p2x = points[(length-1)*2];
  4308. p2y = points[(length-1)*2 + 1];
  4309. perpx = -(p1y - p2y);
  4310. perpy = p1x - p2x;
  4311. dist = Math.sqrt(perpx*perpx + perpy*perpy);
  4312. perpx /= dist;
  4313. perpy /= dist;
  4314. perpx *= width;
  4315. perpy *= width;
  4316. verts.push(p2x - perpx , p2y - perpy);
  4317. verts.push(r, g, b, alpha);
  4318. verts.push(p2x + perpx , p2y + perpy);
  4319. verts.push(r, g, b, alpha);
  4320. indices.push(indexStart);
  4321. for (i = 0; i < indexCount; i++)
  4322. {
  4323. indices.push(indexStart++);
  4324. }
  4325. indices.push(indexStart-1);
  4326. };
  4327. /**
  4328. * Builds a complex polygon to draw
  4329. *
  4330. * @static
  4331. * @private
  4332. * @method buildPoly
  4333. * @param graphicsData {Graphics} The graphics object containing all the necessary properties
  4334. * @param webGLData {Object}
  4335. */
  4336. PIXI.WebGLGraphics.buildComplexPoly = function(graphicsData, webGLData)
  4337. {
  4338. //TODO - no need to copy this as it gets turned into a FLoat32Array anyways..
  4339. var points = graphicsData.points.slice();
  4340. if(points.length < 6)return;
  4341. // get first and last point.. figure out the middle!
  4342. var indices = webGLData.indices;
  4343. webGLData.points = points;
  4344. webGLData.alpha = graphicsData.fillAlpha;
  4345. webGLData.color = PIXI.hex2rgb(graphicsData.fillColor);
  4346. /*
  4347. calclate the bounds..
  4348. */
  4349. var minX = Infinity;
  4350. var maxX = -Infinity;
  4351. var minY = Infinity;
  4352. var maxY = -Infinity;
  4353. var x,y;
  4354. // get size..
  4355. for (var i = 0; i < points.length; i+=2)
  4356. {
  4357. x = points[i];
  4358. y = points[i+1];
  4359. minX = x < minX ? x : minX;
  4360. maxX = x > maxX ? x : maxX;
  4361. minY = y < minY ? y : minY;
  4362. maxY = y > maxY ? y : maxY;
  4363. }
  4364. // add a quad to the end cos there is no point making another buffer!
  4365. points.push(minX, minY,
  4366. maxX, minY,
  4367. maxX, maxY,
  4368. minX, maxY);
  4369. // push a quad onto the end..
  4370. //TODO - this aint needed!
  4371. var length = points.length / 2;
  4372. for (i = 0; i < length; i++)
  4373. {
  4374. indices.push( i );
  4375. }
  4376. };
  4377. PIXI.WebGLGraphics.buildPoly = function(graphicsData, webGLData)
  4378. {
  4379. var points = graphicsData.points;
  4380. if(points.length < 6)return;
  4381. // get first and last point.. figure out the middle!
  4382. var verts = webGLData.points;
  4383. var indices = webGLData.indices;
  4384. var length = points.length / 2;
  4385. // sort color
  4386. var color = PIXI.hex2rgb(graphicsData.fillColor);
  4387. var alpha = graphicsData.fillAlpha;
  4388. var r = color[0] * alpha;
  4389. var g = color[1] * alpha;
  4390. var b = color[2] * alpha;
  4391. var triangles = PIXI.PolyK.Triangulate(points);
  4392. var vertPos = verts.length / 6;
  4393. var i = 0;
  4394. for (i = 0; i < triangles.length; i+=3)
  4395. {
  4396. indices.push(triangles[i] + vertPos);
  4397. indices.push(triangles[i] + vertPos);
  4398. indices.push(triangles[i+1] + vertPos);
  4399. indices.push(triangles[i+2] +vertPos);
  4400. indices.push(triangles[i+2] + vertPos);
  4401. }
  4402. for (i = 0; i < length; i++)
  4403. {
  4404. verts.push(points[i * 2], points[i * 2 + 1],
  4405. r, g, b, alpha);
  4406. }
  4407. };
  4408. PIXI.WebGLGraphics.graphicsDataPool = [];
  4409. PIXI.WebGLGraphicsData = function(gl)
  4410. {
  4411. this.gl = gl;
  4412. //TODO does this need to be split before uploding??
  4413. this.color = [0,0,0]; // color split!
  4414. this.points = [];
  4415. this.indices = [];
  4416. this.lastIndex = 0;
  4417. this.buffer = gl.createBuffer();
  4418. this.indexBuffer = gl.createBuffer();
  4419. this.mode = 1;
  4420. this.alpha = 1;
  4421. this.dirty = true;
  4422. };
  4423. PIXI.WebGLGraphicsData.prototype.reset = function()
  4424. {
  4425. this.points = [];
  4426. this.indices = [];
  4427. this.lastIndex = 0;
  4428. };
  4429. PIXI.WebGLGraphicsData.prototype.upload = function()
  4430. {
  4431. var gl = this.gl;
  4432. // this.lastIndex = graphics.graphicsData.length;
  4433. this.glPoints = new Float32Array(this.points);
  4434. gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
  4435. gl.bufferData(gl.ARRAY_BUFFER, this.glPoints, gl.STATIC_DRAW);
  4436. this.glIndicies = new Uint16Array(this.indices);
  4437. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  4438. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.glIndicies, gl.STATIC_DRAW);
  4439. this.dirty = false;
  4440. };
  4441. /**
  4442. * @author Mat Groves http://matgroves.com/ @Doormat23
  4443. */
  4444. PIXI.glContexts = []; // this is where we store the webGL contexts for easy access.
  4445. /**
  4446. * the WebGLRenderer draws the stage and all its content onto a webGL enabled canvas. This renderer
  4447. * should be used for browsers that support webGL. This Render works by automatically managing webGLBatch's.
  4448. * So no need for Sprite Batch's or Sprite Cloud's
  4449. * Dont forget to add the view to your DOM or you will not see anything :)
  4450. *
  4451. * @class WebGLRenderer
  4452. * @constructor
  4453. * @param width=0 {Number} the width of the canvas view
  4454. * @param height=0 {Number} the height of the canvas view
  4455. * @param view {HTMLCanvasElement} the canvas to use as a view, optional
  4456. * @param transparent=false {Boolean} If the render view is transparent, default false
  4457. * @param antialias=false {Boolean} sets antialias (only applicable in chrome at the moment)
  4458. * @param preserveDrawingBuffer=false {Boolean} enables drawing buffer preservation, enable this if you need to call toDataUrl on the webgl context
  4459. *
  4460. */
  4461. PIXI.WebGLRenderer = function(width, height, view, transparent, antialias, preserveDrawingBuffer)
  4462. {
  4463. if(!PIXI.defaultRenderer)
  4464. {
  4465. PIXI.sayHello('webGL');
  4466. PIXI.defaultRenderer = this;
  4467. }
  4468. this.type = PIXI.WEBGL_RENDERER;
  4469. // do a catch.. only 1 webGL renderer..
  4470. /**
  4471. * Whether the render view is transparent
  4472. *
  4473. * @property transparent
  4474. * @type Boolean
  4475. */
  4476. this.transparent = !!transparent;
  4477. /**
  4478. * The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering.
  4479. *
  4480. * @property preserveDrawingBuffer
  4481. * @type Boolean
  4482. */
  4483. this.preserveDrawingBuffer = preserveDrawingBuffer;
  4484. /**
  4485. * The width of the canvas view
  4486. *
  4487. * @property width
  4488. * @type Number
  4489. * @default 800
  4490. */
  4491. this.width = width || 800;
  4492. /**
  4493. * The height of the canvas view
  4494. *
  4495. * @property height
  4496. * @type Number
  4497. * @default 600
  4498. */
  4499. this.height = height || 600;
  4500. /**
  4501. * The canvas element that everything is drawn to
  4502. *
  4503. * @property view
  4504. * @type HTMLCanvasElement
  4505. */
  4506. this.view = view || document.createElement( 'canvas' );
  4507. this.view.width = this.width;
  4508. this.view.height = this.height;
  4509. // deal with losing context..
  4510. this.contextLost = this.handleContextLost.bind(this);
  4511. this.contextRestoredLost = this.handleContextRestored.bind(this);
  4512. this.view.addEventListener('webglcontextlost', this.contextLost, false);
  4513. this.view.addEventListener('webglcontextrestored', this.contextRestoredLost, false);
  4514. this.options = {
  4515. alpha: this.transparent,
  4516. antialias:!!antialias, // SPEED UP??
  4517. premultipliedAlpha:!!transparent,
  4518. stencil:true,
  4519. preserveDrawingBuffer: preserveDrawingBuffer
  4520. };
  4521. var gl = null;
  4522. ['experimental-webgl', 'webgl'].forEach(function(name) {
  4523. try {
  4524. gl = gl || this.view.getContext(name, this.options);
  4525. } catch(e) {}
  4526. }, this);
  4527. if (!gl) {
  4528. // fail, not able to get a context
  4529. throw new Error('This browser does not support webGL. Try using the canvas renderer' + this);
  4530. }
  4531. this.gl = gl;
  4532. this.glContextId = gl.id = PIXI.WebGLRenderer.glContextId ++;
  4533. PIXI.glContexts[this.glContextId] = gl;
  4534. if(!PIXI.blendModesWebGL)
  4535. {
  4536. PIXI.blendModesWebGL = [];
  4537. PIXI.blendModesWebGL[PIXI.blendModes.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  4538. PIXI.blendModesWebGL[PIXI.blendModes.ADD] = [gl.SRC_ALPHA, gl.DST_ALPHA];
  4539. PIXI.blendModesWebGL[PIXI.blendModes.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA];
  4540. PIXI.blendModesWebGL[PIXI.blendModes.SCREEN] = [gl.SRC_ALPHA, gl.ONE];
  4541. PIXI.blendModesWebGL[PIXI.blendModes.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  4542. PIXI.blendModesWebGL[PIXI.blendModes.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  4543. PIXI.blendModesWebGL[PIXI.blendModes.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  4544. PIXI.blendModesWebGL[PIXI.blendModes.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  4545. PIXI.blendModesWebGL[PIXI.blendModes.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  4546. PIXI.blendModesWebGL[PIXI.blendModes.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  4547. PIXI.blendModesWebGL[PIXI.blendModes.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  4548. PIXI.blendModesWebGL[PIXI.blendModes.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  4549. PIXI.blendModesWebGL[PIXI.blendModes.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  4550. PIXI.blendModesWebGL[PIXI.blendModes.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  4551. PIXI.blendModesWebGL[PIXI.blendModes.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  4552. PIXI.blendModesWebGL[PIXI.blendModes.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  4553. PIXI.blendModesWebGL[PIXI.blendModes.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  4554. }
  4555. this.projection = new PIXI.Point();
  4556. this.projection.x = this.width/2;
  4557. this.projection.y = -this.height/2;
  4558. this.offset = new PIXI.Point(0, 0);
  4559. this.resize(this.width, this.height);
  4560. this.contextLost = false;
  4561. // time to create the render managers! each one focuses on managine a state in webGL
  4562. this.shaderManager = new PIXI.WebGLShaderManager(gl); // deals with managing the shader programs and their attribs
  4563. this.spriteBatch = new PIXI.WebGLSpriteBatch(gl); // manages the rendering of sprites
  4564. //this.primitiveBatch = new PIXI.WebGLPrimitiveBatch(gl); // primitive batch renderer
  4565. this.maskManager = new PIXI.WebGLMaskManager(gl); // manages the masks using the stencil buffer
  4566. this.filterManager = new PIXI.WebGLFilterManager(gl, this.transparent); // manages the filters
  4567. this.stencilManager = new PIXI.WebGLStencilManager(gl);
  4568. this.blendModeManager = new PIXI.WebGLBlendModeManager(gl);
  4569. this.renderSession = {};
  4570. this.renderSession.gl = this.gl;
  4571. this.renderSession.drawCount = 0;
  4572. this.renderSession.shaderManager = this.shaderManager;
  4573. this.renderSession.maskManager = this.maskManager;
  4574. this.renderSession.filterManager = this.filterManager;
  4575. this.renderSession.blendModeManager = this.blendModeManager;
  4576. // this.renderSession.primitiveBatch = this.primitiveBatch;
  4577. this.renderSession.spriteBatch = this.spriteBatch;
  4578. this.renderSession.stencilManager = this.stencilManager;
  4579. this.renderSession.renderer = this;
  4580. gl.useProgram(this.shaderManager.defaultShader.program);
  4581. gl.disable(gl.DEPTH_TEST);
  4582. gl.disable(gl.CULL_FACE);
  4583. gl.enable(gl.BLEND);
  4584. gl.colorMask(true, true, true, this.transparent);
  4585. };
  4586. // constructor
  4587. PIXI.WebGLRenderer.prototype.constructor = PIXI.WebGLRenderer;
  4588. /**
  4589. * Renders the stage to its webGL view
  4590. *
  4591. * @method render
  4592. * @param stage {Stage} the Stage element to be rendered
  4593. */
  4594. PIXI.WebGLRenderer.prototype.render = function(stage)
  4595. {
  4596. if(this.contextLost)return;
  4597. // if rendering a new stage clear the batches..
  4598. if(this.__stage !== stage)
  4599. {
  4600. if(stage.interactive)stage.interactionManager.removeEvents();
  4601. // TODO make this work
  4602. // dont think this is needed any more?
  4603. this.__stage = stage;
  4604. }
  4605. // update any textures this includes uvs and uploading them to the gpu
  4606. PIXI.WebGLRenderer.updateTextures();
  4607. // update the scene graph
  4608. stage.updateTransform();
  4609. // interaction
  4610. if(stage._interactive)
  4611. {
  4612. //need to add some events!
  4613. if(!stage._interactiveEventsAdded)
  4614. {
  4615. stage._interactiveEventsAdded = true;
  4616. stage.interactionManager.setTarget(this);
  4617. }
  4618. }
  4619. var gl = this.gl;
  4620. // -- Does this need to be set every frame? -- //
  4621. //gl.colorMask(true, true, true, this.transparent);
  4622. gl.viewport(0, 0, this.width, this.height);
  4623. // make sure we are bound to the main frame buffer
  4624. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4625. if(this.transparent)
  4626. {
  4627. gl.clearColor(0, 0, 0, 0);
  4628. }
  4629. else
  4630. {
  4631. gl.clearColor(stage.backgroundColorSplit[0],stage.backgroundColorSplit[1],stage.backgroundColorSplit[2], 1);
  4632. }
  4633. gl.clear(gl.COLOR_BUFFER_BIT);
  4634. this.renderDisplayObject( stage, this.projection );
  4635. // interaction
  4636. if(stage.interactive)
  4637. {
  4638. //need to add some events!
  4639. if(!stage._interactiveEventsAdded)
  4640. {
  4641. stage._interactiveEventsAdded = true;
  4642. stage.interactionManager.setTarget(this);
  4643. }
  4644. }
  4645. else
  4646. {
  4647. if(stage._interactiveEventsAdded)
  4648. {
  4649. stage._interactiveEventsAdded = false;
  4650. stage.interactionManager.setTarget(this);
  4651. }
  4652. }
  4653. /*
  4654. //can simulate context loss in Chrome like so:
  4655. this.view.onmousedown = function(ev) {
  4656. console.dir(this.gl.getSupportedExtensions());
  4657. var ext = (
  4658. gl.getExtension("WEBGL_scompressed_texture_s3tc")
  4659. // gl.getExtension("WEBGL_compressed_texture_s3tc") ||
  4660. // gl.getExtension("MOZ_WEBGL_compressed_texture_s3tc") ||
  4661. // gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc")
  4662. );
  4663. console.dir(ext);
  4664. var loseCtx = this.gl.getExtension("WEBGL_lose_context");
  4665. console.log("killing context");
  4666. loseCtx.loseContext();
  4667. setTimeout(function() {
  4668. console.log("restoring context...");
  4669. loseCtx.restoreContext();
  4670. }.bind(this), 1000);
  4671. }.bind(this);
  4672. */
  4673. };
  4674. /**
  4675. * Renders a display Object
  4676. *
  4677. * @method renderDIsplayObject
  4678. * @param displayObject {DisplayObject} The DisplayObject to render
  4679. * @param projection {Point} The projection
  4680. * @param buffer {Array} a standard WebGL buffer
  4681. */
  4682. PIXI.WebGLRenderer.prototype.renderDisplayObject = function(displayObject, projection, buffer)
  4683. {
  4684. this.renderSession.blendModeManager.setBlendMode(PIXI.blendModes.NORMAL);
  4685. // reset the render session data..
  4686. this.renderSession.drawCount = 0;
  4687. this.renderSession.currentBlendMode = 9999;
  4688. this.renderSession.projection = projection;
  4689. this.renderSession.offset = this.offset;
  4690. // start the sprite batch
  4691. this.spriteBatch.begin(this.renderSession);
  4692. // this.primitiveBatch.begin(this.renderSession);
  4693. // start the filter manager
  4694. this.filterManager.begin(this.renderSession, buffer);
  4695. // render the scene!
  4696. displayObject._renderWebGL(this.renderSession);
  4697. // finish the sprite batch
  4698. this.spriteBatch.end();
  4699. // this.primitiveBatch.end();
  4700. };
  4701. /**
  4702. * Updates the textures loaded into this webgl renderer
  4703. *
  4704. * @static
  4705. * @method updateTextures
  4706. * @private
  4707. */
  4708. PIXI.WebGLRenderer.updateTextures = function()
  4709. {
  4710. var i = 0;
  4711. //TODO break this out into a texture manager...
  4712. // for (i = 0; i < PIXI.texturesToUpdate.length; i++)
  4713. // PIXI..updateWebGLTexture(PIXI.texturesToUpdate[i], this.gl);
  4714. for (i=0; i < PIXI.Texture.frameUpdates.length; i++)
  4715. PIXI.WebGLRenderer.updateTextureFrame(PIXI.Texture.frameUpdates[i]);
  4716. for (i = 0; i < PIXI.texturesToDestroy.length; i++)
  4717. PIXI.WebGLRenderer.destroyTexture(PIXI.texturesToDestroy[i]);
  4718. PIXI.texturesToUpdate.length = 0;
  4719. PIXI.texturesToDestroy.length = 0;
  4720. PIXI.Texture.frameUpdates.length = 0;
  4721. };
  4722. /**
  4723. * Destroys a loaded webgl texture
  4724. *
  4725. * @method destroyTexture
  4726. * @param texture {Texture} The texture to update
  4727. * @private
  4728. */
  4729. PIXI.WebGLRenderer.destroyTexture = function(texture)
  4730. {
  4731. //TODO break this out into a texture manager...
  4732. for (var i = texture._glTextures.length - 1; i >= 0; i--)
  4733. {
  4734. var glTexture = texture._glTextures[i];
  4735. var gl = PIXI.glContexts[i];
  4736. if(gl && glTexture)
  4737. {
  4738. gl.deleteTexture(glTexture);
  4739. }
  4740. }
  4741. texture._glTextures.length = 0;
  4742. };
  4743. /**
  4744. *
  4745. * @method updateTextureFrame
  4746. * @param texture {Texture} The texture to update the frame from
  4747. * @private
  4748. */
  4749. PIXI.WebGLRenderer.updateTextureFrame = function(texture)
  4750. {
  4751. //texture.updateFrame = false;
  4752. // now set the uvs. Figured that the uv data sits with a texture rather than a sprite.
  4753. // so uv data is stored on the texture itself
  4754. texture._updateWebGLuvs();
  4755. };
  4756. /**
  4757. * resizes the webGL view to the specified width and height
  4758. *
  4759. * @method resize
  4760. * @param width {Number} the new width of the webGL view
  4761. * @param height {Number} the new height of the webGL view
  4762. */
  4763. PIXI.WebGLRenderer.prototype.resize = function(width, height)
  4764. {
  4765. this.width = width;
  4766. this.height = height;
  4767. this.view.width = width;
  4768. this.view.height = height;
  4769. this.gl.viewport(0, 0, this.width, this.height);
  4770. this.projection.x = this.width/2;
  4771. this.projection.y = -this.height/2;
  4772. };
  4773. /**
  4774. * Creates a WebGL texture
  4775. *
  4776. * @method createWebGLTexture
  4777. * @param texture {Texture} the texture to render
  4778. * @param gl {webglContext} the WebGL context
  4779. * @static
  4780. */
  4781. PIXI.createWebGLTexture = function(texture, gl)
  4782. {
  4783. if(texture.hasLoaded)
  4784. {
  4785. texture._glTextures[gl.id] = gl.createTexture();
  4786. gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]);
  4787. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultipliedAlpha);
  4788. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.source);
  4789. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
  4790. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
  4791. // reguler...
  4792. if(!texture._powerOf2)
  4793. {
  4794. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4795. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4796. }
  4797. else
  4798. {
  4799. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
  4800. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
  4801. }
  4802. gl.bindTexture(gl.TEXTURE_2D, null);
  4803. texture._dirty[gl.id] = false;
  4804. }
  4805. return texture._glTextures[gl.id];
  4806. };
  4807. /**
  4808. * Updates a WebGL texture
  4809. *
  4810. * @method updateWebGLTexture
  4811. * @param texture {Texture} the texture to update
  4812. * @param gl {webglContext} the WebGL context
  4813. * @private
  4814. */
  4815. PIXI.updateWebGLTexture = function(texture, gl)
  4816. {
  4817. if( texture._glTextures[gl.id] )
  4818. {
  4819. gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]);
  4820. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultipliedAlpha);
  4821. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.source);
  4822. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
  4823. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
  4824. // reguler...
  4825. if(!texture._powerOf2)
  4826. {
  4827. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4828. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4829. }
  4830. else
  4831. {
  4832. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
  4833. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
  4834. }
  4835. texture._dirty[gl.id] = false;
  4836. }
  4837. };
  4838. /**
  4839. * Handles a lost webgl context
  4840. *
  4841. * @method handleContextLost
  4842. * @param event {Event}
  4843. * @private
  4844. */
  4845. PIXI.WebGLRenderer.prototype.handleContextLost = function(event)
  4846. {
  4847. event.preventDefault();
  4848. this.contextLost = true;
  4849. };
  4850. /**
  4851. * Handles a restored webgl context
  4852. *
  4853. * @method handleContextRestored
  4854. * @param event {Event}
  4855. * @private
  4856. */
  4857. PIXI.WebGLRenderer.prototype.handleContextRestored = function()
  4858. {
  4859. //try 'experimental-webgl'
  4860. try {
  4861. this.gl = this.view.getContext('experimental-webgl', this.options);
  4862. } catch (e) {
  4863. //try 'webgl'
  4864. try {
  4865. this.gl = this.view.getContext('webgl', this.options);
  4866. } catch (e2) {
  4867. // fail, not able to get a context
  4868. throw new Error(' This browser does not support webGL. Try using the canvas renderer' + this);
  4869. }
  4870. }
  4871. var gl = this.gl;
  4872. gl.id = PIXI.WebGLRenderer.glContextId ++;
  4873. // need to set the context...
  4874. this.shaderManager.setContext(gl);
  4875. this.spriteBatch.setContext(gl);
  4876. this.primitiveBatch.setContext(gl);
  4877. this.maskManager.setContext(gl);
  4878. this.filterManager.setContext(gl);
  4879. this.renderSession.gl = this.gl;
  4880. gl.disable(gl.DEPTH_TEST);
  4881. gl.disable(gl.CULL_FACE);
  4882. gl.enable(gl.BLEND);
  4883. gl.colorMask(true, true, true, this.transparent);
  4884. this.gl.viewport(0, 0, this.width, this.height);
  4885. for(var key in PIXI.TextureCache)
  4886. {
  4887. var texture = PIXI.TextureCache[key].baseTexture;
  4888. texture._glTextures = [];
  4889. }
  4890. /**
  4891. * Whether the context was lost
  4892. * @property contextLost
  4893. * @type Boolean
  4894. */
  4895. this.contextLost = false;
  4896. };
  4897. /**
  4898. * Removes everything from the renderer (event listeners, spritebatch, etc...)
  4899. *
  4900. * @method destroy
  4901. */
  4902. PIXI.WebGLRenderer.prototype.destroy = function()
  4903. {
  4904. // deal with losing context..
  4905. // remove listeners
  4906. this.view.removeEventListener('webglcontextlost', this.contextLost);
  4907. this.view.removeEventListener('webglcontextrestored', this.contextRestoredLost);
  4908. PIXI.glContexts[this.glContextId] = null;
  4909. this.projection = null;
  4910. this.offset = null;
  4911. // time to create the render managers! each one focuses on managine a state in webGL
  4912. this.shaderManager.destroy();
  4913. this.spriteBatch.destroy();
  4914. this.primitiveBatch.destroy();
  4915. this.maskManager.destroy();
  4916. this.filterManager.destroy();
  4917. this.shaderManager = null;
  4918. this.spriteBatch = null;
  4919. this.maskManager = null;
  4920. this.filterManager = null;
  4921. this.gl = null;
  4922. //
  4923. this.renderSession = null;
  4924. };
  4925. PIXI.WebGLRenderer.glContextId = 0;
  4926. /**
  4927. * @author Mat Groves http://matgroves.com/ @Doormat23
  4928. */
  4929. /**
  4930. * @class WebGLMaskManager
  4931. * @constructor
  4932. * @param gl {WebGLContext} the current WebGL drawing context
  4933. * @private
  4934. */
  4935. PIXI.WebGLBlendModeManager = function(gl)
  4936. {
  4937. this.gl = gl;
  4938. this.currentBlendMode = 99999;
  4939. };
  4940. /**
  4941. * Sets-up the given blendMode from WebGL's point of view
  4942. * @method setBlendMode
  4943. *
  4944. * @param blendMode {Number} the blendMode, should be a Pixi const, such as PIXI.BlendModes.ADD
  4945. */
  4946. PIXI.WebGLBlendModeManager.prototype.setBlendMode = function(blendMode)
  4947. {
  4948. if(this.currentBlendMode === blendMode)return false;
  4949. // console.log("SWAP!")
  4950. this.currentBlendMode = blendMode;
  4951. var blendModeWebGL = PIXI.blendModesWebGL[this.currentBlendMode];
  4952. this.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]);
  4953. return true;
  4954. };
  4955. PIXI.WebGLBlendModeManager.prototype.destroy = function()
  4956. {
  4957. this.gl = null;
  4958. };
  4959. /**
  4960. * @author Mat Groves http://matgroves.com/ @Doormat23
  4961. */
  4962. /**
  4963. * @class WebGLMaskManager
  4964. * @constructor
  4965. * @param gl {WebGLContext} the current WebGL drawing context
  4966. * @private
  4967. */
  4968. PIXI.WebGLMaskManager = function(gl)
  4969. {
  4970. this.maskStack = [];
  4971. this.maskPosition = 0;
  4972. this.setContext(gl);
  4973. this.reverse = false;
  4974. this.count = 0;
  4975. };
  4976. /**
  4977. * Sets the drawing context to the one given in parameter
  4978. * @method setContext
  4979. * @param gl {WebGLContext} the current WebGL drawing context
  4980. */
  4981. PIXI.WebGLMaskManager.prototype.setContext = function(gl)
  4982. {
  4983. this.gl = gl;
  4984. };
  4985. /**
  4986. * Applies the Mask and adds it to the current filter stack
  4987. * @method pushMask
  4988. * @param maskData {Array}
  4989. * @param renderSession {RenderSession}
  4990. */
  4991. PIXI.WebGLMaskManager.prototype.pushMask = function(maskData, renderSession)
  4992. {
  4993. var gl = renderSession.gl;
  4994. if(maskData.dirty)
  4995. {
  4996. PIXI.WebGLGraphics.updateGraphics(maskData, gl);
  4997. }
  4998. if(!maskData._webGL[gl.id].data.length)return;
  4999. renderSession.stencilManager.pushStencil(maskData, maskData._webGL[gl.id].data[0], renderSession);
  5000. };
  5001. /**
  5002. * Removes the last filter from the filter stack and doesn't return it
  5003. * @method popMask
  5004. *
  5005. * @param renderSession {RenderSession} an object containing all the useful parameters
  5006. */
  5007. PIXI.WebGLMaskManager.prototype.popMask = function(maskData, renderSession)
  5008. {
  5009. var gl = this.gl;
  5010. renderSession.stencilManager.popStencil(maskData, maskData._webGL[gl.id].data[0], renderSession);
  5011. };
  5012. /**
  5013. * Destroys the mask stack
  5014. * @method destroy
  5015. */
  5016. PIXI.WebGLMaskManager.prototype.destroy = function()
  5017. {
  5018. this.maskStack = null;
  5019. this.gl = null;
  5020. };
  5021. /**
  5022. * @author Mat Groves http://matgroves.com/ @Doormat23
  5023. */
  5024. //BA0285
  5025. //Intercontinental Hotel, 888 Howard Street
  5026. //San Francisco
  5027. /**
  5028. * @class WebGLStencilManager
  5029. * @constructor
  5030. * @param gl {WebGLContext} the current WebGL drawing context
  5031. * @private
  5032. */
  5033. PIXI.WebGLStencilManager = function(gl)
  5034. {
  5035. this.stencilStack = [];
  5036. this.setContext(gl);
  5037. this.reverse = true;
  5038. this.count = 0;
  5039. };
  5040. /**
  5041. * Sets the drawing context to the one given in parameter
  5042. * @method setContext
  5043. * @param gl {WebGLContext} the current WebGL drawing context
  5044. */
  5045. PIXI.WebGLStencilManager.prototype.setContext = function(gl)
  5046. {
  5047. this.gl = gl;
  5048. };
  5049. /**
  5050. * Applies the Mask and adds it to the current filter stack
  5051. * @method pushMask
  5052. * @param maskData {Array}
  5053. * @param renderSession {RenderSession}
  5054. */
  5055. PIXI.WebGLStencilManager.prototype.pushStencil = function(graphics, webGLData, renderSession)
  5056. {
  5057. var gl = this.gl;
  5058. this.bindGraphics(graphics, webGLData, renderSession);
  5059. if(this.stencilStack.length === 0)
  5060. {
  5061. gl.enable(gl.STENCIL_TEST);
  5062. gl.clear(gl.STENCIL_BUFFER_BIT);
  5063. this.reverse = true;
  5064. this.count = 0;
  5065. }
  5066. this.stencilStack.push(webGLData);
  5067. var level = this.count;
  5068. gl.colorMask(false, false, false, false);
  5069. gl.stencilFunc(gl.ALWAYS,0,0xFF);
  5070. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT);
  5071. // draw the triangle strip!
  5072. if(webGLData.mode === 1)
  5073. {
  5074. gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 );
  5075. if(this.reverse)
  5076. {
  5077. gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF);
  5078. gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
  5079. }
  5080. else
  5081. {
  5082. gl.stencilFunc(gl.EQUAL,level, 0xFF);
  5083. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
  5084. }
  5085. // draw a quad to increment..
  5086. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 );
  5087. if(this.reverse)
  5088. {
  5089. gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF);
  5090. }
  5091. else
  5092. {
  5093. gl.stencilFunc(gl.EQUAL,level+1, 0xFF);
  5094. }
  5095. this.reverse = !this.reverse;
  5096. }
  5097. else
  5098. {
  5099. if(!this.reverse)
  5100. {
  5101. gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF);
  5102. gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
  5103. }
  5104. else
  5105. {
  5106. gl.stencilFunc(gl.EQUAL,level, 0xFF);
  5107. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
  5108. }
  5109. gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 );
  5110. if(!this.reverse)
  5111. {
  5112. gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF);
  5113. }
  5114. else
  5115. {
  5116. gl.stencilFunc(gl.EQUAL,level+1, 0xFF);
  5117. }
  5118. }
  5119. gl.colorMask(true, true, true, true);
  5120. gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);
  5121. this.count++;
  5122. };
  5123. //TODO this does not belong here!
  5124. PIXI.WebGLStencilManager.prototype.bindGraphics = function(graphics, webGLData, renderSession)
  5125. {
  5126. //if(this._currentGraphics === graphics)return;
  5127. this._currentGraphics = graphics;
  5128. var gl = this.gl;
  5129. // bind the graphics object..
  5130. var projection = renderSession.projection,
  5131. offset = renderSession.offset,
  5132. shader;// = renderSession.shaderManager.primitiveShader;
  5133. if(webGLData.mode === 1)
  5134. {
  5135. shader = renderSession.shaderManager.complexPrimativeShader;
  5136. renderSession.shaderManager.setShader( shader );
  5137. gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true));
  5138. gl.uniform2f(shader.projectionVector, projection.x, -projection.y);
  5139. gl.uniform2f(shader.offsetVector, -offset.x, -offset.y);
  5140. gl.uniform3fv(shader.tintColor, PIXI.hex2rgb(graphics.tint));
  5141. gl.uniform3fv(shader.color, webGLData.color);
  5142. gl.uniform1f(shader.alpha, graphics.worldAlpha * webGLData.alpha);
  5143. gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer);
  5144. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 2, 0);
  5145. // now do the rest..
  5146. // set the index buffer!
  5147. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer);
  5148. }
  5149. else
  5150. {
  5151. //renderSession.shaderManager.activatePrimitiveShader();
  5152. shader = renderSession.shaderManager.primitiveShader;
  5153. renderSession.shaderManager.setShader( shader );
  5154. gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true));
  5155. gl.uniform2f(shader.projectionVector, projection.x, -projection.y);
  5156. gl.uniform2f(shader.offsetVector, -offset.x, -offset.y);
  5157. gl.uniform3fv(shader.tintColor, PIXI.hex2rgb(graphics.tint));
  5158. gl.uniform1f(shader.alpha, graphics.worldAlpha);
  5159. gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer);
  5160. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0);
  5161. gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4);
  5162. // set the index buffer!
  5163. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer);
  5164. }
  5165. };
  5166. PIXI.WebGLStencilManager.prototype.popStencil = function(graphics, webGLData, renderSession)
  5167. {
  5168. var gl = this.gl;
  5169. this.stencilStack.pop();
  5170. this.count--;
  5171. if(this.stencilStack.length === 0)
  5172. {
  5173. // the stack is empty!
  5174. gl.disable(gl.STENCIL_TEST);
  5175. }
  5176. else
  5177. {
  5178. var level = this.count;
  5179. this.bindGraphics(graphics, webGLData, renderSession);
  5180. gl.colorMask(false, false, false, false);
  5181. if(webGLData.mode === 1)
  5182. {
  5183. this.reverse = !this.reverse;
  5184. if(this.reverse)
  5185. {
  5186. gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF);
  5187. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
  5188. }
  5189. else
  5190. {
  5191. gl.stencilFunc(gl.EQUAL,level+1, 0xFF);
  5192. gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
  5193. }
  5194. // draw a quad to increment..
  5195. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 );
  5196. gl.stencilFunc(gl.ALWAYS,0,0xFF);
  5197. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT);
  5198. // draw the triangle strip!
  5199. gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 );
  5200. if(!this.reverse)
  5201. {
  5202. gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF);
  5203. }
  5204. else
  5205. {
  5206. gl.stencilFunc(gl.EQUAL,level, 0xFF);
  5207. }
  5208. }
  5209. else
  5210. {
  5211. // console.log("<<>>")
  5212. if(!this.reverse)
  5213. {
  5214. gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF);
  5215. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
  5216. }
  5217. else
  5218. {
  5219. gl.stencilFunc(gl.EQUAL,level+1, 0xFF);
  5220. gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
  5221. }
  5222. gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 );
  5223. if(!this.reverse)
  5224. {
  5225. gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF);
  5226. }
  5227. else
  5228. {
  5229. gl.stencilFunc(gl.EQUAL,level, 0xFF);
  5230. }
  5231. }
  5232. gl.colorMask(true, true, true, true);
  5233. gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);
  5234. }
  5235. //renderSession.shaderManager.deactivatePrimitiveShader();
  5236. };
  5237. /**
  5238. * Destroys the mask stack
  5239. * @method destroy
  5240. */
  5241. PIXI.WebGLStencilManager.prototype.destroy = function()
  5242. {
  5243. this.maskStack = null;
  5244. this.gl = null;
  5245. };
  5246. /**
  5247. * @author Mat Groves http://matgroves.com/ @Doormat23
  5248. */
  5249. /**
  5250. * @class WebGLShaderManager
  5251. * @constructor
  5252. * @param gl {WebGLContext} the current WebGL drawing context
  5253. * @private
  5254. */
  5255. PIXI.WebGLShaderManager = function(gl)
  5256. {
  5257. this.maxAttibs = 10;
  5258. this.attribState = [];
  5259. this.tempAttribState = [];
  5260. this.shaderMap = [];
  5261. for (var i = 0; i < this.maxAttibs; i++) {
  5262. this.attribState[i] = false;
  5263. }
  5264. this.setContext(gl);
  5265. // the final one is used for the rendering strips
  5266. };
  5267. /**
  5268. * Initialises the context and the properties
  5269. * @method setContext
  5270. * @param gl {WebGLContext} the current WebGL drawing context
  5271. * @param transparent {Boolean} Whether or not the drawing context should be transparent
  5272. */
  5273. PIXI.WebGLShaderManager.prototype.setContext = function(gl)
  5274. {
  5275. this.gl = gl;
  5276. // the next one is used for rendering primatives
  5277. this.primitiveShader = new PIXI.PrimitiveShader(gl);
  5278. // the next one is used for rendering triangle strips
  5279. this.complexPrimativeShader = new PIXI.ComplexPrimitiveShader(gl);
  5280. // this shader is used for the default sprite rendering
  5281. this.defaultShader = new PIXI.PixiShader(gl);
  5282. // this shader is used for the fast sprite rendering
  5283. this.fastShader = new PIXI.PixiFastShader(gl);
  5284. // the next one is used for rendering triangle strips
  5285. this.stripShader = new PIXI.StripShader(gl);
  5286. this.setShader(this.defaultShader);
  5287. };
  5288. /**
  5289. * Takes the attributes given in parameters
  5290. * @method setAttribs
  5291. * @param attribs {Array} attribs
  5292. */
  5293. PIXI.WebGLShaderManager.prototype.setAttribs = function(attribs)
  5294. {
  5295. // reset temp state
  5296. var i;
  5297. for (i = 0; i < this.tempAttribState.length; i++)
  5298. {
  5299. this.tempAttribState[i] = false;
  5300. }
  5301. // set the new attribs
  5302. for (i = 0; i < attribs.length; i++)
  5303. {
  5304. var attribId = attribs[i];
  5305. this.tempAttribState[attribId] = true;
  5306. }
  5307. var gl = this.gl;
  5308. for (i = 0; i < this.attribState.length; i++)
  5309. {
  5310. if(this.attribState[i] !== this.tempAttribState[i])
  5311. {
  5312. this.attribState[i] = this.tempAttribState[i];
  5313. if(this.tempAttribState[i])
  5314. {
  5315. gl.enableVertexAttribArray(i);
  5316. }
  5317. else
  5318. {
  5319. gl.disableVertexAttribArray(i);
  5320. }
  5321. }
  5322. }
  5323. };
  5324. PIXI.WebGLShaderManager.prototype.setShader = function(shader)
  5325. {
  5326. if(this._currentId === shader._UID)return false;
  5327. this._currentId = shader._UID;
  5328. this.currentShader = shader;
  5329. this.gl.useProgram(shader.program);
  5330. this.setAttribs(shader.attributes);
  5331. return true;
  5332. };
  5333. /**
  5334. * Destroys
  5335. * @method destroy
  5336. */
  5337. PIXI.WebGLShaderManager.prototype.destroy = function()
  5338. {
  5339. this.attribState = null;
  5340. this.tempAttribState = null;
  5341. this.primitiveShader.destroy();
  5342. this.defaultShader.destroy();
  5343. this.fastShader.destroy();
  5344. this.stripShader.destroy();
  5345. this.gl = null;
  5346. };
  5347. /**
  5348. * @author Mat Groves
  5349. *
  5350. * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
  5351. * for creating the original pixi version!
  5352. *
  5353. * Heavily inspired by LibGDX's WebGLSpriteBatch:
  5354. * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java
  5355. */
  5356. /**
  5357. *
  5358. * @class WebGLSpriteBatch
  5359. * @private
  5360. * @constructor
  5361. * @param gl {WebGLContext} the current WebGL drawing context
  5362. *
  5363. */
  5364. PIXI.WebGLSpriteBatch = function(gl)
  5365. {
  5366. /**
  5367. *
  5368. *
  5369. * @property vertSize
  5370. * @type Number
  5371. */
  5372. this.vertSize = 6;
  5373. /**
  5374. * The number of images in the SpriteBatch before it flushes
  5375. * @property size
  5376. * @type Number
  5377. */
  5378. this.size = 2000;//Math.pow(2, 16) / this.vertSize;
  5379. //the total number of floats in our batch
  5380. var numVerts = this.size * 4 * this.vertSize;
  5381. //the total number of indices in our batch
  5382. var numIndices = this.size * 6;
  5383. //vertex data
  5384. /**
  5385. * Holds the vertices
  5386. *
  5387. * @property vertices
  5388. * @type Float32Array
  5389. */
  5390. this.vertices = new Float32Array(numVerts);
  5391. //index data
  5392. /**
  5393. * Holds the indices
  5394. *
  5395. * @property indices
  5396. * @type Uint16Array
  5397. */
  5398. this.indices = new Uint16Array(numIndices);
  5399. this.lastIndexCount = 0;
  5400. for (var i=0, j=0; i < numIndices; i += 6, j += 4)
  5401. {
  5402. this.indices[i + 0] = j + 0;
  5403. this.indices[i + 1] = j + 1;
  5404. this.indices[i + 2] = j + 2;
  5405. this.indices[i + 3] = j + 0;
  5406. this.indices[i + 4] = j + 2;
  5407. this.indices[i + 5] = j + 3;
  5408. }
  5409. this.drawing = false;
  5410. this.currentBatchSize = 0;
  5411. this.currentBaseTexture = null;
  5412. this.setContext(gl);
  5413. this.dirty = true;
  5414. this.textures = [];
  5415. this.blendModes = [];
  5416. };
  5417. /**
  5418. *
  5419. * @method setContext
  5420. *
  5421. * @param gl {WebGLContext} the current WebGL drawing context
  5422. */
  5423. PIXI.WebGLSpriteBatch.prototype.setContext = function(gl)
  5424. {
  5425. this.gl = gl;
  5426. // create a couple of buffers
  5427. this.vertexBuffer = gl.createBuffer();
  5428. this.indexBuffer = gl.createBuffer();
  5429. // 65535 is max index, so 65535 / 6 = 10922.
  5430. //upload the index data
  5431. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  5432. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
  5433. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  5434. gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW);
  5435. this.currentBlendMode = 99999;
  5436. };
  5437. /**
  5438. *
  5439. * @method begin
  5440. *
  5441. * @param renderSession {RenderSession} the RenderSession
  5442. */
  5443. PIXI.WebGLSpriteBatch.prototype.begin = function(renderSession)
  5444. {
  5445. this.renderSession = renderSession;
  5446. this.shader = this.renderSession.shaderManager.defaultShader;
  5447. this.start();
  5448. };
  5449. /**
  5450. *
  5451. * @method end
  5452. *
  5453. */
  5454. PIXI.WebGLSpriteBatch.prototype.end = function()
  5455. {
  5456. this.flush();
  5457. };
  5458. /**
  5459. *
  5460. * @method render
  5461. *
  5462. * @param sprite {Sprite} the sprite to render when using this spritebatch
  5463. */
  5464. PIXI.WebGLSpriteBatch.prototype.render = function(sprite)
  5465. {
  5466. var texture = sprite.texture;
  5467. //TODO set blend modes..
  5468. // check texture..
  5469. if(this.currentBatchSize >= this.size)
  5470. {
  5471. //return;
  5472. this.flush();
  5473. this.currentBaseTexture = texture.baseTexture;
  5474. }
  5475. // get the uvs for the texture
  5476. var uvs = texture._uvs;
  5477. // if the uvs have not updated then no point rendering just yet!
  5478. if(!uvs)return;
  5479. // get the sprites current alpha
  5480. var alpha = sprite.worldAlpha;
  5481. var tint = sprite.tint;
  5482. var verticies = this.vertices;
  5483. // TODO trim??
  5484. var aX = sprite.anchor.x;
  5485. var aY = sprite.anchor.y;
  5486. var w0, w1, h0, h1;
  5487. if (texture.trim)
  5488. {
  5489. // if the sprite is trimmed then we need to add the extra space before transforming the sprite coords..
  5490. var trim = texture.trim;
  5491. w1 = trim.x - aX * trim.width;
  5492. w0 = w1 + texture.crop.width;
  5493. h1 = trim.y - aY * trim.height;
  5494. h0 = h1 + texture.crop.height;
  5495. }
  5496. else
  5497. {
  5498. w0 = (texture.frame.width ) * (1-aX);
  5499. w1 = (texture.frame.width ) * -aX;
  5500. h0 = texture.frame.height * (1-aY);
  5501. h1 = texture.frame.height * -aY;
  5502. }
  5503. var index = this.currentBatchSize * 4 * this.vertSize;
  5504. var worldTransform = sprite.worldTransform;
  5505. var a = worldTransform.a;//[0];
  5506. var b = worldTransform.c;//[3];
  5507. var c = worldTransform.b;//[1];
  5508. var d = worldTransform.d;//[4];
  5509. var tx = worldTransform.tx;//[2];
  5510. var ty = worldTransform.ty;///[5];
  5511. // xy
  5512. verticies[index++] = a * w1 + c * h1 + tx;
  5513. verticies[index++] = d * h1 + b * w1 + ty;
  5514. // uv
  5515. verticies[index++] = uvs.x0;
  5516. verticies[index++] = uvs.y0;
  5517. // color
  5518. verticies[index++] = alpha;
  5519. verticies[index++] = tint;
  5520. // xy
  5521. verticies[index++] = a * w0 + c * h1 + tx;
  5522. verticies[index++] = d * h1 + b * w0 + ty;
  5523. // uv
  5524. verticies[index++] = uvs.x1;
  5525. verticies[index++] = uvs.y1;
  5526. // color
  5527. verticies[index++] = alpha;
  5528. verticies[index++] = tint;
  5529. // xy
  5530. verticies[index++] = a * w0 + c * h0 + tx;
  5531. verticies[index++] = d * h0 + b * w0 + ty;
  5532. // uv
  5533. verticies[index++] = uvs.x2;
  5534. verticies[index++] = uvs.y2;
  5535. // color
  5536. verticies[index++] = alpha;
  5537. verticies[index++] = tint;
  5538. // xy
  5539. verticies[index++] = a * w1 + c * h0 + tx;
  5540. verticies[index++] = d * h0 + b * w1 + ty;
  5541. // uv
  5542. verticies[index++] = uvs.x3;
  5543. verticies[index++] = uvs.y3;
  5544. // color
  5545. verticies[index++] = alpha;
  5546. verticies[index++] = tint;
  5547. // increment the batchsize
  5548. this.textures[this.currentBatchSize] = sprite.texture.baseTexture;
  5549. this.blendModes[this.currentBatchSize] = sprite.blendMode;
  5550. this.currentBatchSize++;
  5551. };
  5552. /**
  5553. * Renders a tilingSprite using the spriteBatch
  5554. * @method renderTilingSprite
  5555. *
  5556. * @param sprite {TilingSprite} the tilingSprite to render
  5557. */
  5558. PIXI.WebGLSpriteBatch.prototype.renderTilingSprite = function(tilingSprite)
  5559. {
  5560. var texture = tilingSprite.tilingTexture;
  5561. // check texture..
  5562. if(this.currentBatchSize >= this.size)
  5563. {
  5564. //return;
  5565. this.flush();
  5566. this.currentBaseTexture = texture.baseTexture;
  5567. }
  5568. // set the textures uvs temporarily
  5569. // TODO create a separate texture so that we can tile part of a texture
  5570. if(!tilingSprite._uvs)tilingSprite._uvs = new PIXI.TextureUvs();
  5571. var uvs = tilingSprite._uvs;
  5572. tilingSprite.tilePosition.x %= texture.baseTexture.width * tilingSprite.tileScaleOffset.x;
  5573. tilingSprite.tilePosition.y %= texture.baseTexture.height * tilingSprite.tileScaleOffset.y;
  5574. var offsetX = tilingSprite.tilePosition.x/(texture.baseTexture.width*tilingSprite.tileScaleOffset.x);
  5575. var offsetY = tilingSprite.tilePosition.y/(texture.baseTexture.height*tilingSprite.tileScaleOffset.y);
  5576. var scaleX = (tilingSprite.width / texture.baseTexture.width) / (tilingSprite.tileScale.x * tilingSprite.tileScaleOffset.x);
  5577. var scaleY = (tilingSprite.height / texture.baseTexture.height) / (tilingSprite.tileScale.y * tilingSprite.tileScaleOffset.y);
  5578. uvs.x0 = 0 - offsetX;
  5579. uvs.y0 = 0 - offsetY;
  5580. uvs.x1 = (1 * scaleX) - offsetX;
  5581. uvs.y1 = 0 - offsetY;
  5582. uvs.x2 = (1 * scaleX) - offsetX;
  5583. uvs.y2 = (1 * scaleY) - offsetY;
  5584. uvs.x3 = 0 - offsetX;
  5585. uvs.y3 = (1 *scaleY) - offsetY;
  5586. // get the tilingSprites current alpha
  5587. var alpha = tilingSprite.worldAlpha;
  5588. var tint = tilingSprite.tint;
  5589. var verticies = this.vertices;
  5590. var width = tilingSprite.width;
  5591. var height = tilingSprite.height;
  5592. // TODO trim??
  5593. var aX = tilingSprite.anchor.x;
  5594. var aY = tilingSprite.anchor.y;
  5595. var w0 = width * (1-aX);
  5596. var w1 = width * -aX;
  5597. var h0 = height * (1-aY);
  5598. var h1 = height * -aY;
  5599. var index = this.currentBatchSize * 4 * this.vertSize;
  5600. var worldTransform = tilingSprite.worldTransform;
  5601. var a = worldTransform.a;//[0];
  5602. var b = worldTransform.c;//[3];
  5603. var c = worldTransform.b;//[1];
  5604. var d = worldTransform.d;//[4];
  5605. var tx = worldTransform.tx;//[2];
  5606. var ty = worldTransform.ty;///[5];
  5607. // xy
  5608. verticies[index++] = a * w1 + c * h1 + tx;
  5609. verticies[index++] = d * h1 + b * w1 + ty;
  5610. // uv
  5611. verticies[index++] = uvs.x0;
  5612. verticies[index++] = uvs.y0;
  5613. // color
  5614. verticies[index++] = alpha;
  5615. verticies[index++] = tint;
  5616. // xy
  5617. verticies[index++] = (a * w0 + c * h1 + tx);
  5618. verticies[index++] = d * h1 + b * w0 + ty;
  5619. // uv
  5620. verticies[index++] = uvs.x1;
  5621. verticies[index++] = uvs.y1;
  5622. // color
  5623. verticies[index++] = alpha;
  5624. verticies[index++] = tint;
  5625. // xy
  5626. verticies[index++] = a * w0 + c * h0 + tx;
  5627. verticies[index++] = d * h0 + b * w0 + ty;
  5628. // uv
  5629. verticies[index++] = uvs.x2;
  5630. verticies[index++] = uvs.y2;
  5631. // color
  5632. verticies[index++] = alpha;
  5633. verticies[index++] = tint;
  5634. // xy
  5635. verticies[index++] = a * w1 + c * h0 + tx;
  5636. verticies[index++] = d * h0 + b * w1 + ty;
  5637. // uv
  5638. verticies[index++] = uvs.x3;
  5639. verticies[index++] = uvs.y3;
  5640. // color
  5641. verticies[index++] = alpha;
  5642. verticies[index++] = tint;
  5643. // increment the batchs
  5644. this.textures[this.currentBatchSize] = texture.baseTexture;
  5645. this.blendModes[this.currentBatchSize] = tilingSprite.blendMode;
  5646. this.currentBatchSize++;
  5647. };
  5648. /**
  5649. * Renders the content and empties the current batch
  5650. *
  5651. * @method flush
  5652. *
  5653. */
  5654. PIXI.WebGLSpriteBatch.prototype.flush = function()
  5655. {
  5656. // If the batch is length 0 then return as there is nothing to draw
  5657. if (this.currentBatchSize===0)return;
  5658. var gl = this.gl;
  5659. this.renderSession.shaderManager.setShader(this.renderSession.shaderManager.defaultShader);
  5660. if(this.dirty)
  5661. {
  5662. this.dirty = false;
  5663. // bind the main texture
  5664. gl.activeTexture(gl.TEXTURE0);
  5665. // bind the buffers
  5666. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  5667. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  5668. // set the projection
  5669. var projection = this.renderSession.projection;
  5670. gl.uniform2f(this.shader.projectionVector, projection.x, projection.y);
  5671. // set the pointers
  5672. var stride = this.vertSize * 4;
  5673. gl.vertexAttribPointer(this.shader.aVertexPosition, 2, gl.FLOAT, false, stride, 0);
  5674. gl.vertexAttribPointer(this.shader.aTextureCoord, 2, gl.FLOAT, false, stride, 2 * 4);
  5675. gl.vertexAttribPointer(this.shader.colorAttribute, 2, gl.FLOAT, false, stride, 4 * 4);
  5676. }
  5677. // upload the verts to the buffer
  5678. if(this.currentBatchSize > ( this.size * 0.5 ) )
  5679. {
  5680. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices);
  5681. }
  5682. else
  5683. {
  5684. var view = this.vertices.subarray(0, this.currentBatchSize * 4 * this.vertSize);
  5685. gl.bufferSubData(gl.ARRAY_BUFFER, 0, view);
  5686. }
  5687. var nextTexture, nextBlendMode;
  5688. var batchSize = 0;
  5689. var start = 0;
  5690. var currentBaseTexture = null;
  5691. var currentBlendMode = this.renderSession.blendModeManager.currentBlendMode;
  5692. for (var i = 0, j = this.currentBatchSize; i < j; i++) {
  5693. nextTexture = this.textures[i];
  5694. nextBlendMode = this.blendModes[i];
  5695. if(currentBaseTexture !== nextTexture || currentBlendMode !== nextBlendMode)
  5696. {
  5697. this.renderBatch(currentBaseTexture, batchSize, start);
  5698. start = i;
  5699. batchSize = 0;
  5700. currentBaseTexture = nextTexture;
  5701. currentBlendMode = nextBlendMode;
  5702. this.renderSession.blendModeManager.setBlendMode( currentBlendMode );
  5703. }
  5704. batchSize++;
  5705. }
  5706. this.renderBatch(currentBaseTexture, batchSize, start);
  5707. // then reset the batch!
  5708. this.currentBatchSize = 0;
  5709. };
  5710. PIXI.WebGLSpriteBatch.prototype.renderBatch = function(texture, size, startIndex)
  5711. {
  5712. if(size === 0)return;
  5713. var gl = this.gl;
  5714. // bind the current texture
  5715. gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id] || PIXI.createWebGLTexture(texture, gl));
  5716. // check if a texture is dirty..
  5717. if(texture._dirty[gl.id])
  5718. {
  5719. PIXI.updateWebGLTexture(this.currentBaseTexture, gl);
  5720. }
  5721. // now draw those suckas!
  5722. gl.drawElements(gl.TRIANGLES, size * 6, gl.UNSIGNED_SHORT, startIndex * 6 * 2);
  5723. // increment the draw count
  5724. this.renderSession.drawCount++;
  5725. };
  5726. /**
  5727. *
  5728. * @method stop
  5729. *
  5730. */
  5731. PIXI.WebGLSpriteBatch.prototype.stop = function()
  5732. {
  5733. this.flush();
  5734. };
  5735. /**
  5736. *
  5737. * @method start
  5738. *
  5739. */
  5740. PIXI.WebGLSpriteBatch.prototype.start = function()
  5741. {
  5742. this.dirty = true;
  5743. };
  5744. /**
  5745. * Destroys the SpriteBatch
  5746. * @method destroy
  5747. */
  5748. PIXI.WebGLSpriteBatch.prototype.destroy = function()
  5749. {
  5750. this.vertices = null;
  5751. this.indices = null;
  5752. this.gl.deleteBuffer( this.vertexBuffer );
  5753. this.gl.deleteBuffer( this.indexBuffer );
  5754. this.currentBaseTexture = null;
  5755. this.gl = null;
  5756. };
  5757. /**
  5758. * @author Mat Groves
  5759. *
  5760. * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
  5761. * for creating the original pixi version!
  5762. *
  5763. * Heavily inspired by LibGDX's WebGLSpriteBatch:
  5764. * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java
  5765. */
  5766. PIXI.WebGLFastSpriteBatch = function(gl)
  5767. {
  5768. this.vertSize = 10;
  5769. this.maxSize = 6000;//Math.pow(2, 16) / this.vertSize;
  5770. this.size = this.maxSize;
  5771. //the total number of floats in our batch
  5772. var numVerts = this.size * 4 * this.vertSize;
  5773. //the total number of indices in our batch
  5774. var numIndices = this.maxSize * 6;
  5775. //vertex data
  5776. this.vertices = new Float32Array(numVerts);
  5777. //index data
  5778. this.indices = new Uint16Array(numIndices);
  5779. this.vertexBuffer = null;
  5780. this.indexBuffer = null;
  5781. this.lastIndexCount = 0;
  5782. for (var i=0, j=0; i < numIndices; i += 6, j += 4)
  5783. {
  5784. this.indices[i + 0] = j + 0;
  5785. this.indices[i + 1] = j + 1;
  5786. this.indices[i + 2] = j + 2;
  5787. this.indices[i + 3] = j + 0;
  5788. this.indices[i + 4] = j + 2;
  5789. this.indices[i + 5] = j + 3;
  5790. }
  5791. this.drawing = false;
  5792. this.currentBatchSize = 0;
  5793. this.currentBaseTexture = null;
  5794. this.currentBlendMode = 0;
  5795. this.renderSession = null;
  5796. this.shader = null;
  5797. this.matrix = null;
  5798. this.setContext(gl);
  5799. };
  5800. PIXI.WebGLFastSpriteBatch.prototype.setContext = function(gl)
  5801. {
  5802. this.gl = gl;
  5803. // create a couple of buffers
  5804. this.vertexBuffer = gl.createBuffer();
  5805. this.indexBuffer = gl.createBuffer();
  5806. // 65535 is max index, so 65535 / 6 = 10922.
  5807. //upload the index data
  5808. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  5809. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
  5810. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  5811. gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW);
  5812. };
  5813. PIXI.WebGLFastSpriteBatch.prototype.begin = function(spriteBatch, renderSession)
  5814. {
  5815. this.renderSession = renderSession;
  5816. this.shader = this.renderSession.shaderManager.fastShader;
  5817. this.matrix = spriteBatch.worldTransform.toArray(true);
  5818. this.start();
  5819. };
  5820. PIXI.WebGLFastSpriteBatch.prototype.end = function()
  5821. {
  5822. this.flush();
  5823. };
  5824. PIXI.WebGLFastSpriteBatch.prototype.render = function(spriteBatch)
  5825. {
  5826. var children = spriteBatch.children;
  5827. var sprite = children[0];
  5828. // if the uvs have not updated then no point rendering just yet!
  5829. // check texture.
  5830. if(!sprite.texture._uvs)return;
  5831. this.currentBaseTexture = sprite.texture.baseTexture;
  5832. // check blend mode
  5833. if(sprite.blendMode !== this.renderSession.blendModeManager.currentBlendMode)
  5834. {
  5835. this.flush();
  5836. this.renderSession.blendModeManager.setBlendMode(sprite.blendMode);
  5837. }
  5838. for(var i=0,j= children.length; i<j; i++)
  5839. {
  5840. this.renderSprite(children[i]);
  5841. }
  5842. this.flush();
  5843. };
  5844. PIXI.WebGLFastSpriteBatch.prototype.renderSprite = function(sprite)
  5845. {
  5846. //sprite = children[i];
  5847. if(!sprite.visible)return;
  5848. // TODO trim??
  5849. if(sprite.texture.baseTexture !== this.currentBaseTexture)
  5850. {
  5851. this.flush();
  5852. this.currentBaseTexture = sprite.texture.baseTexture;
  5853. if(!sprite.texture._uvs)return;
  5854. }
  5855. var uvs, verticies = this.vertices, width, height, w0, w1, h0, h1, index;
  5856. uvs = sprite.texture._uvs;
  5857. width = sprite.texture.frame.width;
  5858. height = sprite.texture.frame.height;
  5859. if (sprite.texture.trim)
  5860. {
  5861. // if the sprite is trimmed then we need to add the extra space before transforming the sprite coords..
  5862. var trim = sprite.texture.trim;
  5863. w1 = trim.x - sprite.anchor.x * trim.width;
  5864. w0 = w1 + sprite.texture.crop.width;
  5865. h1 = trim.y - sprite.anchor.y * trim.height;
  5866. h0 = h1 + sprite.texture.crop.height;
  5867. }
  5868. else
  5869. {
  5870. w0 = (sprite.texture.frame.width ) * (1-sprite.anchor.x);
  5871. w1 = (sprite.texture.frame.width ) * -sprite.anchor.x;
  5872. h0 = sprite.texture.frame.height * (1-sprite.anchor.y);
  5873. h1 = sprite.texture.frame.height * -sprite.anchor.y;
  5874. }
  5875. index = this.currentBatchSize * 4 * this.vertSize;
  5876. // xy
  5877. verticies[index++] = w1;
  5878. verticies[index++] = h1;
  5879. verticies[index++] = sprite.position.x;
  5880. verticies[index++] = sprite.position.y;
  5881. //scale
  5882. verticies[index++] = sprite.scale.x;
  5883. verticies[index++] = sprite.scale.y;
  5884. //rotation
  5885. verticies[index++] = sprite.rotation;
  5886. // uv
  5887. verticies[index++] = uvs.x0;
  5888. verticies[index++] = uvs.y1;
  5889. // color
  5890. verticies[index++] = sprite.alpha;
  5891. // xy
  5892. verticies[index++] = w0;
  5893. verticies[index++] = h1;
  5894. verticies[index++] = sprite.position.x;
  5895. verticies[index++] = sprite.position.y;
  5896. //scale
  5897. verticies[index++] = sprite.scale.x;
  5898. verticies[index++] = sprite.scale.y;
  5899. //rotation
  5900. verticies[index++] = sprite.rotation;
  5901. // uv
  5902. verticies[index++] = uvs.x1;
  5903. verticies[index++] = uvs.y1;
  5904. // color
  5905. verticies[index++] = sprite.alpha;
  5906. // xy
  5907. verticies[index++] = w0;
  5908. verticies[index++] = h0;
  5909. verticies[index++] = sprite.position.x;
  5910. verticies[index++] = sprite.position.y;
  5911. //scale
  5912. verticies[index++] = sprite.scale.x;
  5913. verticies[index++] = sprite.scale.y;
  5914. //rotation
  5915. verticies[index++] = sprite.rotation;
  5916. // uv
  5917. verticies[index++] = uvs.x2;
  5918. verticies[index++] = uvs.y2;
  5919. // color
  5920. verticies[index++] = sprite.alpha;
  5921. // xy
  5922. verticies[index++] = w1;
  5923. verticies[index++] = h0;
  5924. verticies[index++] = sprite.position.x;
  5925. verticies[index++] = sprite.position.y;
  5926. //scale
  5927. verticies[index++] = sprite.scale.x;
  5928. verticies[index++] = sprite.scale.y;
  5929. //rotation
  5930. verticies[index++] = sprite.rotation;
  5931. // uv
  5932. verticies[index++] = uvs.x3;
  5933. verticies[index++] = uvs.y3;
  5934. // color
  5935. verticies[index++] = sprite.alpha;
  5936. // increment the batchs
  5937. this.currentBatchSize++;
  5938. if(this.currentBatchSize >= this.size)
  5939. {
  5940. this.flush();
  5941. }
  5942. };
  5943. PIXI.WebGLFastSpriteBatch.prototype.flush = function()
  5944. {
  5945. // If the batch is length 0 then return as there is nothing to draw
  5946. if (this.currentBatchSize===0)return;
  5947. var gl = this.gl;
  5948. // bind the current texture
  5949. if(!this.currentBaseTexture._glTextures[gl.id])PIXI.createWebGLTexture(this.currentBaseTexture, gl);
  5950. gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]);
  5951. // upload the verts to the buffer
  5952. if(this.currentBatchSize > ( this.size * 0.5 ) )
  5953. {
  5954. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices);
  5955. }
  5956. else
  5957. {
  5958. var view = this.vertices.subarray(0, this.currentBatchSize * 4 * this.vertSize);
  5959. gl.bufferSubData(gl.ARRAY_BUFFER, 0, view);
  5960. }
  5961. // now draw those suckas!
  5962. gl.drawElements(gl.TRIANGLES, this.currentBatchSize * 6, gl.UNSIGNED_SHORT, 0);
  5963. // then reset the batch!
  5964. this.currentBatchSize = 0;
  5965. // increment the draw count
  5966. this.renderSession.drawCount++;
  5967. };
  5968. PIXI.WebGLFastSpriteBatch.prototype.stop = function()
  5969. {
  5970. this.flush();
  5971. };
  5972. PIXI.WebGLFastSpriteBatch.prototype.start = function()
  5973. {
  5974. var gl = this.gl;
  5975. // bind the main texture
  5976. gl.activeTexture(gl.TEXTURE0);
  5977. // bind the buffers
  5978. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  5979. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  5980. // set the projection
  5981. var projection = this.renderSession.projection;
  5982. gl.uniform2f(this.shader.projectionVector, projection.x, projection.y);
  5983. // set the matrix
  5984. gl.uniformMatrix3fv(this.shader.uMatrix, false, this.matrix);
  5985. // set the pointers
  5986. var stride = this.vertSize * 4;
  5987. gl.vertexAttribPointer(this.shader.aVertexPosition, 2, gl.FLOAT, false, stride, 0);
  5988. gl.vertexAttribPointer(this.shader.aPositionCoord, 2, gl.FLOAT, false, stride, 2 * 4);
  5989. gl.vertexAttribPointer(this.shader.aScale, 2, gl.FLOAT, false, stride, 4 * 4);
  5990. gl.vertexAttribPointer(this.shader.aRotation, 1, gl.FLOAT, false, stride, 6 * 4);
  5991. gl.vertexAttribPointer(this.shader.aTextureCoord, 2, gl.FLOAT, false, stride, 7 * 4);
  5992. gl.vertexAttribPointer(this.shader.colorAttribute, 1, gl.FLOAT, false, stride, 9 * 4);
  5993. };
  5994. /**
  5995. * @author Mat Groves http://matgroves.com/ @Doormat23
  5996. */
  5997. /**
  5998. * @class WebGLFilterManager
  5999. * @constructor
  6000. * @param gl {WebGLContext} the current WebGL drawing context
  6001. * @param transparent {Boolean} Whether or not the drawing context should be transparent
  6002. * @private
  6003. */
  6004. PIXI.WebGLFilterManager = function(gl, transparent)
  6005. {
  6006. this.transparent = transparent;
  6007. this.filterStack = [];
  6008. this.offsetX = 0;
  6009. this.offsetY = 0;
  6010. this.setContext(gl);
  6011. };
  6012. // API
  6013. /**
  6014. * Initialises the context and the properties
  6015. * @method setContext
  6016. * @param gl {WebGLContext} the current WebGL drawing context
  6017. */
  6018. PIXI.WebGLFilterManager.prototype.setContext = function(gl)
  6019. {
  6020. this.gl = gl;
  6021. this.texturePool = [];
  6022. this.initShaderBuffers();
  6023. };
  6024. /**
  6025. *
  6026. * @method begin
  6027. * @param renderSession {RenderSession}
  6028. * @param buffer {ArrayBuffer}
  6029. */
  6030. PIXI.WebGLFilterManager.prototype.begin = function(renderSession, buffer)
  6031. {
  6032. this.renderSession = renderSession;
  6033. this.defaultShader = renderSession.shaderManager.defaultShader;
  6034. var projection = this.renderSession.projection;
  6035. // console.log(this.width)
  6036. this.width = projection.x * 2;
  6037. this.height = -projection.y * 2;
  6038. this.buffer = buffer;
  6039. };
  6040. /**
  6041. * Applies the filter and adds it to the current filter stack
  6042. * @method pushFilter
  6043. * @param filterBlock {Object} the filter that will be pushed to the current filter stack
  6044. */
  6045. PIXI.WebGLFilterManager.prototype.pushFilter = function(filterBlock)
  6046. {
  6047. var gl = this.gl;
  6048. var projection = this.renderSession.projection;
  6049. var offset = this.renderSession.offset;
  6050. filterBlock._filterArea = filterBlock.target.filterArea || filterBlock.target.getBounds();
  6051. // filter program
  6052. // OPTIMISATION - the first filter is free if its a simple color change?
  6053. this.filterStack.push(filterBlock);
  6054. var filter = filterBlock.filterPasses[0];
  6055. this.offsetX += filterBlock._filterArea.x;
  6056. this.offsetY += filterBlock._filterArea.y;
  6057. var texture = this.texturePool.pop();
  6058. if(!texture)
  6059. {
  6060. texture = new PIXI.FilterTexture(this.gl, this.width, this.height);
  6061. }
  6062. else
  6063. {
  6064. texture.resize(this.width, this.height);
  6065. }
  6066. gl.bindTexture(gl.TEXTURE_2D, texture.texture);
  6067. var filterArea = filterBlock._filterArea;// filterBlock.target.getBounds();///filterBlock.target.filterArea;
  6068. var padding = filter.padding;
  6069. filterArea.x -= padding;
  6070. filterArea.y -= padding;
  6071. filterArea.width += padding * 2;
  6072. filterArea.height += padding * 2;
  6073. // cap filter to screen size..
  6074. if(filterArea.x < 0)filterArea.x = 0;
  6075. if(filterArea.width > this.width)filterArea.width = this.width;
  6076. if(filterArea.y < 0)filterArea.y = 0;
  6077. if(filterArea.height > this.height)filterArea.height = this.height;
  6078. //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, filterArea.width, filterArea.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6079. gl.bindFramebuffer(gl.FRAMEBUFFER, texture.frameBuffer);
  6080. // set view port
  6081. gl.viewport(0, 0, filterArea.width, filterArea.height);
  6082. projection.x = filterArea.width/2;
  6083. projection.y = -filterArea.height/2;
  6084. offset.x = -filterArea.x;
  6085. offset.y = -filterArea.y;
  6086. // update projection
  6087. // now restore the regular shader..
  6088. this.renderSession.shaderManager.setShader(this.defaultShader);
  6089. gl.uniform2f(this.defaultShader.projectionVector, filterArea.width/2, -filterArea.height/2);
  6090. gl.uniform2f(this.defaultShader.offsetVector, -filterArea.x, -filterArea.y);
  6091. gl.colorMask(true, true, true, true);
  6092. gl.clearColor(0,0,0, 0);
  6093. gl.clear(gl.COLOR_BUFFER_BIT);
  6094. filterBlock._glFilterTexture = texture;
  6095. };
  6096. /**
  6097. * Removes the last filter from the filter stack and doesn't return it
  6098. * @method popFilter
  6099. */
  6100. PIXI.WebGLFilterManager.prototype.popFilter = function()
  6101. {
  6102. var gl = this.gl;
  6103. var filterBlock = this.filterStack.pop();
  6104. var filterArea = filterBlock._filterArea;
  6105. var texture = filterBlock._glFilterTexture;
  6106. var projection = this.renderSession.projection;
  6107. var offset = this.renderSession.offset;
  6108. if(filterBlock.filterPasses.length > 1)
  6109. {
  6110. gl.viewport(0, 0, filterArea.width, filterArea.height);
  6111. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  6112. this.vertexArray[0] = 0;
  6113. this.vertexArray[1] = filterArea.height;
  6114. this.vertexArray[2] = filterArea.width;
  6115. this.vertexArray[3] = filterArea.height;
  6116. this.vertexArray[4] = 0;
  6117. this.vertexArray[5] = 0;
  6118. this.vertexArray[6] = filterArea.width;
  6119. this.vertexArray[7] = 0;
  6120. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertexArray);
  6121. gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
  6122. // now set the uvs..
  6123. this.uvArray[2] = filterArea.width/this.width;
  6124. this.uvArray[5] = filterArea.height/this.height;
  6125. this.uvArray[6] = filterArea.width/this.width;
  6126. this.uvArray[7] = filterArea.height/this.height;
  6127. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.uvArray);
  6128. var inputTexture = texture;
  6129. var outputTexture = this.texturePool.pop();
  6130. if(!outputTexture)outputTexture = new PIXI.FilterTexture(this.gl, this.width, this.height);
  6131. outputTexture.resize(this.width, this.height);
  6132. // need to clear this FBO as it may have some left over elements from a previous filter.
  6133. gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer );
  6134. gl.clear(gl.COLOR_BUFFER_BIT);
  6135. gl.disable(gl.BLEND);
  6136. for (var i = 0; i < filterBlock.filterPasses.length-1; i++)
  6137. {
  6138. var filterPass = filterBlock.filterPasses[i];
  6139. gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer );
  6140. // set texture
  6141. gl.activeTexture(gl.TEXTURE0);
  6142. gl.bindTexture(gl.TEXTURE_2D, inputTexture.texture);
  6143. // draw texture..
  6144. //filterPass.applyFilterPass(filterArea.width, filterArea.height);
  6145. this.applyFilterPass(filterPass, filterArea, filterArea.width, filterArea.height);
  6146. // swap the textures..
  6147. var temp = inputTexture;
  6148. inputTexture = outputTexture;
  6149. outputTexture = temp;
  6150. }
  6151. gl.enable(gl.BLEND);
  6152. texture = inputTexture;
  6153. this.texturePool.push(outputTexture);
  6154. }
  6155. var filter = filterBlock.filterPasses[filterBlock.filterPasses.length-1];
  6156. this.offsetX -= filterArea.x;
  6157. this.offsetY -= filterArea.y;
  6158. var sizeX = this.width;
  6159. var sizeY = this.height;
  6160. var offsetX = 0;
  6161. var offsetY = 0;
  6162. var buffer = this.buffer;
  6163. // time to render the filters texture to the previous scene
  6164. if(this.filterStack.length === 0)
  6165. {
  6166. gl.colorMask(true, true, true, true);//this.transparent);
  6167. }
  6168. else
  6169. {
  6170. var currentFilter = this.filterStack[this.filterStack.length-1];
  6171. filterArea = currentFilter._filterArea;
  6172. sizeX = filterArea.width;
  6173. sizeY = filterArea.height;
  6174. offsetX = filterArea.x;
  6175. offsetY = filterArea.y;
  6176. buffer = currentFilter._glFilterTexture.frameBuffer;
  6177. }
  6178. // TODO need toremove thease global elements..
  6179. projection.x = sizeX/2;
  6180. projection.y = -sizeY/2;
  6181. offset.x = offsetX;
  6182. offset.y = offsetY;
  6183. filterArea = filterBlock._filterArea;
  6184. var x = filterArea.x-offsetX;
  6185. var y = filterArea.y-offsetY;
  6186. // update the buffers..
  6187. // make sure to flip the y!
  6188. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  6189. this.vertexArray[0] = x;
  6190. this.vertexArray[1] = y + filterArea.height;
  6191. this.vertexArray[2] = x + filterArea.width;
  6192. this.vertexArray[3] = y + filterArea.height;
  6193. this.vertexArray[4] = x;
  6194. this.vertexArray[5] = y;
  6195. this.vertexArray[6] = x + filterArea.width;
  6196. this.vertexArray[7] = y;
  6197. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertexArray);
  6198. gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
  6199. this.uvArray[2] = filterArea.width/this.width;
  6200. this.uvArray[5] = filterArea.height/this.height;
  6201. this.uvArray[6] = filterArea.width/this.width;
  6202. this.uvArray[7] = filterArea.height/this.height;
  6203. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.uvArray);
  6204. //console.log(this.vertexArray)
  6205. //console.log(this.uvArray)
  6206. //console.log(sizeX + " : " + sizeY)
  6207. gl.viewport(0, 0, sizeX, sizeY);
  6208. // bind the buffer
  6209. gl.bindFramebuffer(gl.FRAMEBUFFER, buffer );
  6210. // set the blend mode!
  6211. //gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
  6212. // set texture
  6213. gl.activeTexture(gl.TEXTURE0);
  6214. gl.bindTexture(gl.TEXTURE_2D, texture.texture);
  6215. // apply!
  6216. this.applyFilterPass(filter, filterArea, sizeX, sizeY);
  6217. // now restore the regular shader..
  6218. this.renderSession.shaderManager.setShader(this.defaultShader);
  6219. gl.uniform2f(this.defaultShader.projectionVector, sizeX/2, -sizeY/2);
  6220. gl.uniform2f(this.defaultShader.offsetVector, -offsetX, -offsetY);
  6221. // return the texture to the pool
  6222. this.texturePool.push(texture);
  6223. filterBlock._glFilterTexture = null;
  6224. };
  6225. /**
  6226. * Applies the filter to the specified area
  6227. * @method applyFilterPass
  6228. * @param filter {AbstractFilter} the filter that needs to be applied
  6229. * @param filterArea {texture} TODO - might need an update
  6230. * @param width {Number} the horizontal range of the filter
  6231. * @param height {Number} the vertical range of the filter
  6232. */
  6233. PIXI.WebGLFilterManager.prototype.applyFilterPass = function(filter, filterArea, width, height)
  6234. {
  6235. // use program
  6236. var gl = this.gl;
  6237. var shader = filter.shaders[gl.id];
  6238. if(!shader)
  6239. {
  6240. shader = new PIXI.PixiShader(gl);
  6241. shader.fragmentSrc = filter.fragmentSrc;
  6242. shader.uniforms = filter.uniforms;
  6243. shader.init();
  6244. filter.shaders[gl.id] = shader;
  6245. }
  6246. // set the shader
  6247. this.renderSession.shaderManager.setShader(shader);
  6248. // gl.useProgram(shader.program);
  6249. gl.uniform2f(shader.projectionVector, width/2, -height/2);
  6250. gl.uniform2f(shader.offsetVector, 0,0);
  6251. if(filter.uniforms.dimensions)
  6252. {
  6253. filter.uniforms.dimensions.value[0] = this.width;//width;
  6254. filter.uniforms.dimensions.value[1] = this.height;//height;
  6255. filter.uniforms.dimensions.value[2] = this.vertexArray[0];
  6256. filter.uniforms.dimensions.value[3] = this.vertexArray[5];//filterArea.height;
  6257. }
  6258. // console.log(this.uvArray )
  6259. shader.syncUniforms();
  6260. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  6261. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
  6262. gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
  6263. gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
  6264. gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);
  6265. gl.vertexAttribPointer(shader.colorAttribute, 2, gl.FLOAT, false, 0, 0);
  6266. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  6267. // draw the filter...
  6268. gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  6269. this.renderSession.drawCount++;
  6270. };
  6271. /**
  6272. * Initialises the shader buffers
  6273. * @method initShaderBuffers
  6274. */
  6275. PIXI.WebGLFilterManager.prototype.initShaderBuffers = function()
  6276. {
  6277. var gl = this.gl;
  6278. // create some buffers
  6279. this.vertexBuffer = gl.createBuffer();
  6280. this.uvBuffer = gl.createBuffer();
  6281. this.colorBuffer = gl.createBuffer();
  6282. this.indexBuffer = gl.createBuffer();
  6283. // bind and upload the vertexs..
  6284. // keep a reference to the vertexFloatData..
  6285. this.vertexArray = new Float32Array([0.0, 0.0,
  6286. 1.0, 0.0,
  6287. 0.0, 1.0,
  6288. 1.0, 1.0]);
  6289. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  6290. gl.bufferData(
  6291. gl.ARRAY_BUFFER,
  6292. this.vertexArray,
  6293. gl.STATIC_DRAW);
  6294. // bind and upload the uv buffer
  6295. this.uvArray = new Float32Array([0.0, 0.0,
  6296. 1.0, 0.0,
  6297. 0.0, 1.0,
  6298. 1.0, 1.0]);
  6299. gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
  6300. gl.bufferData(
  6301. gl.ARRAY_BUFFER,
  6302. this.uvArray,
  6303. gl.STATIC_DRAW);
  6304. this.colorArray = new Float32Array([1.0, 0xFFFFFF,
  6305. 1.0, 0xFFFFFF,
  6306. 1.0, 0xFFFFFF,
  6307. 1.0, 0xFFFFFF]);
  6308. gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);
  6309. gl.bufferData(
  6310. gl.ARRAY_BUFFER,
  6311. this.colorArray,
  6312. gl.STATIC_DRAW);
  6313. // bind and upload the index
  6314. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  6315. gl.bufferData(
  6316. gl.ELEMENT_ARRAY_BUFFER,
  6317. new Uint16Array([0, 1, 2, 1, 3, 2]),
  6318. gl.STATIC_DRAW);
  6319. };
  6320. /**
  6321. * Destroys the filter and removes it from the filter stack
  6322. * @method destroy
  6323. */
  6324. PIXI.WebGLFilterManager.prototype.destroy = function()
  6325. {
  6326. var gl = this.gl;
  6327. this.filterStack = null;
  6328. this.offsetX = 0;
  6329. this.offsetY = 0;
  6330. // destroy textures
  6331. for (var i = 0; i < this.texturePool.length; i++) {
  6332. this.texturePool[i].destroy();
  6333. }
  6334. this.texturePool = null;
  6335. //destroy buffers..
  6336. gl.deleteBuffer(this.vertexBuffer);
  6337. gl.deleteBuffer(this.uvBuffer);
  6338. gl.deleteBuffer(this.colorBuffer);
  6339. gl.deleteBuffer(this.indexBuffer);
  6340. };
  6341. /**
  6342. * @author Mat Groves http://matgroves.com/ @Doormat23
  6343. */
  6344. /**
  6345. * @class FilterTexture
  6346. * @constructor
  6347. * @param gl {WebGLContext} the current WebGL drawing context
  6348. * @param width {Number} the horizontal range of the filter
  6349. * @param height {Number} the vertical range of the filter
  6350. * @param scaleMode {Number} Should be one of the PIXI.scaleMode consts
  6351. * @private
  6352. */
  6353. PIXI.FilterTexture = function(gl, width, height, scaleMode)
  6354. {
  6355. /**
  6356. * @property gl
  6357. * @type WebGLContext
  6358. */
  6359. this.gl = gl;
  6360. // next time to create a frame buffer and texture
  6361. this.frameBuffer = gl.createFramebuffer();
  6362. this.texture = gl.createTexture();
  6363. scaleMode = scaleMode || PIXI.scaleModes.DEFAULT;
  6364. gl.bindTexture(gl.TEXTURE_2D, this.texture);
  6365. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
  6366. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
  6367. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6368. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6369. gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer );
  6370. gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer );
  6371. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture, 0);
  6372. // required for masking a mask??
  6373. this.renderBuffer = gl.createRenderbuffer();
  6374. gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderBuffer);
  6375. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.renderBuffer);
  6376. this.resize(width, height);
  6377. };
  6378. /**
  6379. * Clears the filter texture
  6380. * @method clear
  6381. */
  6382. PIXI.FilterTexture.prototype.clear = function()
  6383. {
  6384. var gl = this.gl;
  6385. gl.clearColor(0,0,0, 0);
  6386. gl.clear(gl.COLOR_BUFFER_BIT);
  6387. };
  6388. /**
  6389. * Resizes the texture to the specified width and height
  6390. *
  6391. * @method resize
  6392. * @param width {Number} the new width of the texture
  6393. * @param height {Number} the new height of the texture
  6394. */
  6395. PIXI.FilterTexture.prototype.resize = function(width, height)
  6396. {
  6397. if(this.width === width && this.height === height) return;
  6398. this.width = width;
  6399. this.height = height;
  6400. var gl = this.gl;
  6401. gl.bindTexture(gl.TEXTURE_2D, this.texture);
  6402. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6403. // update the stencil buffer width and height
  6404. gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderBuffer);
  6405. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  6406. };
  6407. /**
  6408. * Destroys the filter texture
  6409. * @method destroy
  6410. */
  6411. PIXI.FilterTexture.prototype.destroy = function()
  6412. {
  6413. var gl = this.gl;
  6414. gl.deleteFramebuffer( this.frameBuffer );
  6415. gl.deleteTexture( this.texture );
  6416. this.frameBuffer = null;
  6417. this.texture = null;
  6418. };
  6419. /**
  6420. * @author Mat Groves
  6421. *
  6422. *
  6423. */
  6424. /**
  6425. * A set of functions used to handle masking
  6426. *
  6427. * @class CanvasMaskManager
  6428. */
  6429. PIXI.CanvasMaskManager = function()
  6430. {
  6431. };
  6432. /**
  6433. * This method adds it to the current stack of masks
  6434. *
  6435. * @method pushMask
  6436. * @param maskData the maskData that will be pushed
  6437. * @param context {Context2D} the 2d drawing method of the canvas
  6438. */
  6439. PIXI.CanvasMaskManager.prototype.pushMask = function(maskData, context)
  6440. {
  6441. context.save();
  6442. var cacheAlpha = maskData.alpha;
  6443. var transform = maskData.worldTransform;
  6444. context.setTransform(transform.a, transform.c, transform.b, transform.d, transform.tx, transform.ty);
  6445. PIXI.CanvasGraphics.renderGraphicsMask(maskData, context);
  6446. context.clip();
  6447. maskData.worldAlpha = cacheAlpha;
  6448. };
  6449. /**
  6450. * Restores the current drawing context to the state it was before the mask was applied
  6451. *
  6452. * @method popMask
  6453. * @param context {Context2D} the 2d drawing method of the canvas
  6454. */
  6455. PIXI.CanvasMaskManager.prototype.popMask = function(context)
  6456. {
  6457. context.restore();
  6458. };
  6459. /**
  6460. * @author Mat Groves
  6461. *
  6462. *
  6463. */
  6464. /**
  6465. * @class CanvasTinter
  6466. * @constructor
  6467. * @static
  6468. */
  6469. PIXI.CanvasTinter = function()
  6470. {
  6471. /// this.textureCach
  6472. };
  6473. //PIXI.CanvasTinter.cachTint = true;
  6474. /**
  6475. * Basically this method just needs a sprite and a color and tints the sprite
  6476. * with the given color
  6477. *
  6478. * @method getTintedTexture
  6479. * @param sprite {Sprite} the sprite to tint
  6480. * @param color {Number} the color to use to tint the sprite with
  6481. */
  6482. PIXI.CanvasTinter.getTintedTexture = function(sprite, color)
  6483. {
  6484. var texture = sprite.texture;
  6485. color = PIXI.CanvasTinter.roundColor(color);
  6486. var stringColor = "#" + ("00000" + ( color | 0).toString(16)).substr(-6);
  6487. texture.tintCache = texture.tintCache || {};
  6488. if(texture.tintCache[stringColor]) return texture.tintCache[stringColor];
  6489. // clone texture..
  6490. var canvas = PIXI.CanvasTinter.canvas || document.createElement("canvas");
  6491. //PIXI.CanvasTinter.tintWithPerPixel(texture, stringColor, canvas);
  6492. PIXI.CanvasTinter.tintMethod(texture, color, canvas);
  6493. if(PIXI.CanvasTinter.convertTintToImage)
  6494. {
  6495. // is this better?
  6496. var tintImage = new Image();
  6497. tintImage.src = canvas.toDataURL();
  6498. texture.tintCache[stringColor] = tintImage;
  6499. }
  6500. else
  6501. {
  6502. texture.tintCache[stringColor] = canvas;
  6503. // if we are not converting the texture to an image then we need to lose the reference to the canvas
  6504. PIXI.CanvasTinter.canvas = null;
  6505. }
  6506. return canvas;
  6507. };
  6508. /**
  6509. * Tint a texture using the "multiply" operation
  6510. * @method tintWithMultiply
  6511. * @param texture {texture} the texture to tint
  6512. * @param color {Number} the color to use to tint the sprite with
  6513. * @param canvas {HTMLCanvasElement} the current canvas
  6514. */
  6515. PIXI.CanvasTinter.tintWithMultiply = function(texture, color, canvas)
  6516. {
  6517. var context = canvas.getContext( "2d" );
  6518. var frame = texture.frame;
  6519. canvas.width = frame.width;
  6520. canvas.height = frame.height;
  6521. context.fillStyle = "#" + ("00000" + ( color | 0).toString(16)).substr(-6);
  6522. context.fillRect(0, 0, frame.width, frame.height);
  6523. context.globalCompositeOperation = "multiply";
  6524. context.drawImage(texture.baseTexture.source,
  6525. frame.x,
  6526. frame.y,
  6527. frame.width,
  6528. frame.height,
  6529. 0,
  6530. 0,
  6531. frame.width,
  6532. frame.height);
  6533. context.globalCompositeOperation = "destination-atop";
  6534. context.drawImage(texture.baseTexture.source,
  6535. frame.x,
  6536. frame.y,
  6537. frame.width,
  6538. frame.height,
  6539. 0,
  6540. 0,
  6541. frame.width,
  6542. frame.height);
  6543. };
  6544. /**
  6545. * Tint a texture using the "overlay" operation
  6546. * @method tintWithOverlay
  6547. * @param texture {texture} the texture to tint
  6548. * @param color {Number} the color to use to tint the sprite with
  6549. * @param canvas {HTMLCanvasElement} the current canvas
  6550. */
  6551. PIXI.CanvasTinter.tintWithOverlay = function(texture, color, canvas)
  6552. {
  6553. var context = canvas.getContext( "2d" );
  6554. var frame = texture.frame;
  6555. canvas.width = frame.width;
  6556. canvas.height = frame.height;
  6557. context.globalCompositeOperation = "copy";
  6558. context.fillStyle = "#" + ("00000" + ( color | 0).toString(16)).substr(-6);
  6559. context.fillRect(0, 0, frame.width, frame.height);
  6560. context.globalCompositeOperation = "destination-atop";
  6561. context.drawImage(texture.baseTexture.source,
  6562. frame.x,
  6563. frame.y,
  6564. frame.width,
  6565. frame.height,
  6566. 0,
  6567. 0,
  6568. frame.width,
  6569. frame.height);
  6570. //context.globalCompositeOperation = "copy";
  6571. };
  6572. /**
  6573. * Tint a texture pixel per pixel
  6574. * @method tintPerPixel
  6575. * @param texture {texture} the texture to tint
  6576. * @param color {Number} the color to use to tint the sprite with
  6577. * @param canvas {HTMLCanvasElement} the current canvas
  6578. */
  6579. PIXI.CanvasTinter.tintWithPerPixel = function(texture, color, canvas)
  6580. {
  6581. var context = canvas.getContext( "2d" );
  6582. var frame = texture.frame;
  6583. canvas.width = frame.width;
  6584. canvas.height = frame.height;
  6585. context.globalCompositeOperation = "copy";
  6586. context.drawImage(texture.baseTexture.source,
  6587. frame.x,
  6588. frame.y,
  6589. frame.width,
  6590. frame.height,
  6591. 0,
  6592. 0,
  6593. frame.width,
  6594. frame.height);
  6595. var rgbValues = PIXI.hex2rgb(color);
  6596. var r = rgbValues[0], g = rgbValues[1], b = rgbValues[2];
  6597. var pixelData = context.getImageData(0, 0, frame.width, frame.height);
  6598. var pixels = pixelData.data;
  6599. for (var i = 0; i < pixels.length; i += 4)
  6600. {
  6601. pixels[i+0] *= r;
  6602. pixels[i+1] *= g;
  6603. pixels[i+2] *= b;
  6604. }
  6605. context.putImageData(pixelData, 0, 0);
  6606. };
  6607. /**
  6608. * Rounds the specified color according to the PIXI.CanvasTinter.cacheStepsPerColorChannel
  6609. * @method roundColor
  6610. * @param color {number} the color to round, should be a hex color
  6611. */
  6612. PIXI.CanvasTinter.roundColor = function(color)
  6613. {
  6614. var step = PIXI.CanvasTinter.cacheStepsPerColorChannel;
  6615. var rgbValues = PIXI.hex2rgb(color);
  6616. rgbValues[0] = Math.min(255, (rgbValues[0] / step) * step);
  6617. rgbValues[1] = Math.min(255, (rgbValues[1] / step) * step);
  6618. rgbValues[2] = Math.min(255, (rgbValues[2] / step) * step);
  6619. return PIXI.rgb2hex(rgbValues);
  6620. };
  6621. /**
  6622. *
  6623. * Number of steps which will be used as a cap when rounding colors
  6624. *
  6625. * @property cacheStepsPerColorChannel
  6626. * @type Number
  6627. */
  6628. PIXI.CanvasTinter.cacheStepsPerColorChannel = 8;
  6629. /**
  6630. *
  6631. * Number of steps which will be used as a cap when rounding colors
  6632. *
  6633. * @property convertTintToImage
  6634. * @type Boolean
  6635. */
  6636. PIXI.CanvasTinter.convertTintToImage = false;
  6637. /**
  6638. * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method
  6639. *
  6640. * @property canUseMultiply
  6641. * @type Boolean
  6642. */
  6643. PIXI.CanvasTinter.canUseMultiply = PIXI.canUseNewCanvasBlendModes();
  6644. PIXI.CanvasTinter.tintMethod = PIXI.CanvasTinter.canUseMultiply ? PIXI.CanvasTinter.tintWithMultiply : PIXI.CanvasTinter.tintWithPerPixel;
  6645. /**
  6646. * @author Mat Groves http://matgroves.com/ @Doormat23
  6647. */
  6648. /**
  6649. * 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.
  6650. * Dont forget to add the view to your DOM or you will not see anything :)
  6651. *
  6652. * @class CanvasRenderer
  6653. * @constructor
  6654. * @param width=800 {Number} the width of the canvas view
  6655. * @param height=600 {Number} the height of the canvas view
  6656. * @param [view] {HTMLCanvasElement} the canvas to use as a view, optional
  6657. * @param [transparent=false] {Boolean} the transparency of the render view, default false
  6658. */
  6659. PIXI.CanvasRenderer = function(width, height, view, transparent)
  6660. {
  6661. if(!PIXI.defaultRenderer)
  6662. {
  6663. PIXI.sayHello("Canvas");
  6664. PIXI.defaultRenderer = this;
  6665. }
  6666. this.type = PIXI.CANVAS_RENDERER;
  6667. /**
  6668. * This sets if the CanvasRenderer will clear the canvas or not before the new render pass.
  6669. * If the Stage is NOT transparent Pixi will use a canvas sized fillRect operation every frame to set the canvas background color.
  6670. * If the Stage is transparent Pixi will use clearRect to clear the canvas every frame.
  6671. * 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.
  6672. *
  6673. * @property clearBeforeRender
  6674. * @type Boolean
  6675. * @default
  6676. */
  6677. this.clearBeforeRender = true;
  6678. /**
  6679. * Whether the render view is transparent
  6680. *
  6681. * @property transparent
  6682. * @type Boolean
  6683. */
  6684. this.transparent = !!transparent;
  6685. if(!PIXI.blendModesCanvas)
  6686. {
  6687. PIXI.blendModesCanvas = [];
  6688. if(PIXI.canUseNewCanvasBlendModes())
  6689. {
  6690. PIXI.blendModesCanvas[PIXI.blendModes.NORMAL] = "source-over";
  6691. PIXI.blendModesCanvas[PIXI.blendModes.ADD] = "lighter"; //IS THIS OK???
  6692. PIXI.blendModesCanvas[PIXI.blendModes.MULTIPLY] = "multiply";
  6693. PIXI.blendModesCanvas[PIXI.blendModes.SCREEN] = "screen";
  6694. PIXI.blendModesCanvas[PIXI.blendModes.OVERLAY] = "overlay";
  6695. PIXI.blendModesCanvas[PIXI.blendModes.DARKEN] = "darken";
  6696. PIXI.blendModesCanvas[PIXI.blendModes.LIGHTEN] = "lighten";
  6697. PIXI.blendModesCanvas[PIXI.blendModes.COLOR_DODGE] = "color-dodge";
  6698. PIXI.blendModesCanvas[PIXI.blendModes.COLOR_BURN] = "color-burn";
  6699. PIXI.blendModesCanvas[PIXI.blendModes.HARD_LIGHT] = "hard-light";
  6700. PIXI.blendModesCanvas[PIXI.blendModes.SOFT_LIGHT] = "soft-light";
  6701. PIXI.blendModesCanvas[PIXI.blendModes.DIFFERENCE] = "difference";
  6702. PIXI.blendModesCanvas[PIXI.blendModes.EXCLUSION] = "exclusion";
  6703. PIXI.blendModesCanvas[PIXI.blendModes.HUE] = "hue";
  6704. PIXI.blendModesCanvas[PIXI.blendModes.SATURATION] = "saturation";
  6705. PIXI.blendModesCanvas[PIXI.blendModes.COLOR] = "color";
  6706. PIXI.blendModesCanvas[PIXI.blendModes.LUMINOSITY] = "luminosity";
  6707. }
  6708. else
  6709. {
  6710. // this means that the browser does not support the cool new blend modes in canvas "cough" ie "cough"
  6711. PIXI.blendModesCanvas[PIXI.blendModes.NORMAL] = "source-over";
  6712. PIXI.blendModesCanvas[PIXI.blendModes.ADD] = "lighter"; //IS THIS OK???
  6713. PIXI.blendModesCanvas[PIXI.blendModes.MULTIPLY] = "source-over";
  6714. PIXI.blendModesCanvas[PIXI.blendModes.SCREEN] = "source-over";
  6715. PIXI.blendModesCanvas[PIXI.blendModes.OVERLAY] = "source-over";
  6716. PIXI.blendModesCanvas[PIXI.blendModes.DARKEN] = "source-over";
  6717. PIXI.blendModesCanvas[PIXI.blendModes.LIGHTEN] = "source-over";
  6718. PIXI.blendModesCanvas[PIXI.blendModes.COLOR_DODGE] = "source-over";
  6719. PIXI.blendModesCanvas[PIXI.blendModes.COLOR_BURN] = "source-over";
  6720. PIXI.blendModesCanvas[PIXI.blendModes.HARD_LIGHT] = "source-over";
  6721. PIXI.blendModesCanvas[PIXI.blendModes.SOFT_LIGHT] = "source-over";
  6722. PIXI.blendModesCanvas[PIXI.blendModes.DIFFERENCE] = "source-over";
  6723. PIXI.blendModesCanvas[PIXI.blendModes.EXCLUSION] = "source-over";
  6724. PIXI.blendModesCanvas[PIXI.blendModes.HUE] = "source-over";
  6725. PIXI.blendModesCanvas[PIXI.blendModes.SATURATION] = "source-over";
  6726. PIXI.blendModesCanvas[PIXI.blendModes.COLOR] = "source-over";
  6727. PIXI.blendModesCanvas[PIXI.blendModes.LUMINOSITY] = "source-over";
  6728. }
  6729. }
  6730. /**
  6731. * The width of the canvas view
  6732. *
  6733. * @property width
  6734. * @type Number
  6735. * @default 800
  6736. */
  6737. this.width = width || 800;
  6738. /**
  6739. * The height of the canvas view
  6740. *
  6741. * @property height
  6742. * @type Number
  6743. * @default 600
  6744. */
  6745. this.height = height || 600;
  6746. /**
  6747. * The canvas element that everything is drawn to
  6748. *
  6749. * @property view
  6750. * @type HTMLCanvasElement
  6751. */
  6752. this.view = view || document.createElement( "canvas" );
  6753. /**
  6754. * The canvas 2d context that everything is drawn with
  6755. * @property context
  6756. * @type HTMLCanvasElement 2d Context
  6757. */
  6758. this.context = this.view.getContext( "2d", { alpha: this.transparent } );
  6759. this.refresh = true;
  6760. // hack to enable some hardware acceleration!
  6761. //this.view.style["transform"] = "translatez(0)";
  6762. this.view.width = this.width;
  6763. this.view.height = this.height;
  6764. this.count = 0;
  6765. /**
  6766. * Instance of a PIXI.CanvasMaskManager, handles masking when using the canvas renderer
  6767. * @property CanvasMaskManager
  6768. * @type CanvasMaskManager
  6769. */
  6770. this.maskManager = new PIXI.CanvasMaskManager();
  6771. /**
  6772. * The render session is just a bunch of parameter used for rendering
  6773. * @property renderSession
  6774. * @type Object
  6775. */
  6776. this.renderSession = {
  6777. context: this.context,
  6778. maskManager: this.maskManager,
  6779. scaleMode: null,
  6780. smoothProperty: null,
  6781. /**
  6782. * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation.
  6783. * Handy for crisp pixel art and speed on legacy devices.
  6784. *
  6785. */
  6786. roundPixels: false
  6787. };
  6788. if("imageSmoothingEnabled" in this.context)
  6789. this.renderSession.smoothProperty = "imageSmoothingEnabled";
  6790. else if("webkitImageSmoothingEnabled" in this.context)
  6791. this.renderSession.smoothProperty = "webkitImageSmoothingEnabled";
  6792. else if("mozImageSmoothingEnabled" in this.context)
  6793. this.renderSession.smoothProperty = "mozImageSmoothingEnabled";
  6794. else if("oImageSmoothingEnabled" in this.context)
  6795. this.renderSession.smoothProperty = "oImageSmoothingEnabled";
  6796. };
  6797. // constructor
  6798. PIXI.CanvasRenderer.prototype.constructor = PIXI.CanvasRenderer;
  6799. /**
  6800. * Renders the stage to its canvas view
  6801. *
  6802. * @method render
  6803. * @param stage {Stage} the Stage element to be rendered
  6804. */
  6805. PIXI.CanvasRenderer.prototype.render = function(stage)
  6806. {
  6807. // update textures if need be
  6808. PIXI.texturesToUpdate.length = 0;
  6809. PIXI.texturesToDestroy.length = 0;
  6810. stage.updateTransform();
  6811. this.context.setTransform(1,0,0,1,0,0);
  6812. this.context.globalAlpha = 1;
  6813. if (navigator.isCocoonJS && this.view.screencanvas) {
  6814. this.context.fillStyle = "black";
  6815. this.context.clear();
  6816. }
  6817. if (!this.transparent && this.clearBeforeRender)
  6818. {
  6819. this.context.fillStyle = stage.backgroundColorString;
  6820. this.context.fillRect(0, 0, this.width, this.height);
  6821. }
  6822. else if (this.transparent && this.clearBeforeRender)
  6823. {
  6824. this.context.clearRect(0, 0, this.width, this.height);
  6825. }
  6826. this.renderDisplayObject(stage);
  6827. // run interaction!
  6828. if(stage.interactive)
  6829. {
  6830. //need to add some events!
  6831. if(!stage._interactiveEventsAdded)
  6832. {
  6833. stage._interactiveEventsAdded = true;
  6834. stage.interactionManager.setTarget(this);
  6835. }
  6836. }
  6837. // remove frame updates..
  6838. if(PIXI.Texture.frameUpdates.length > 0)
  6839. {
  6840. PIXI.Texture.frameUpdates.length = 0;
  6841. }
  6842. };
  6843. /**
  6844. * Resizes the canvas view to the specified width and height
  6845. *
  6846. * @method resize
  6847. * @param width {Number} the new width of the canvas view
  6848. * @param height {Number} the new height of the canvas view
  6849. */
  6850. PIXI.CanvasRenderer.prototype.resize = function(width, height)
  6851. {
  6852. this.width = width;
  6853. this.height = height;
  6854. this.view.width = width;
  6855. this.view.height = height;
  6856. };
  6857. /**
  6858. * Renders a display object
  6859. *
  6860. * @method renderDisplayObject
  6861. * @param displayObject {DisplayObject} The displayObject to render
  6862. * @param context {Context2D} the context 2d method of the canvas
  6863. * @private
  6864. */
  6865. PIXI.CanvasRenderer.prototype.renderDisplayObject = function(displayObject, context)
  6866. {
  6867. // no longer recursive!
  6868. //var transform;
  6869. //var context = this.context;
  6870. this.renderSession.context = context || this.context;
  6871. displayObject._renderCanvas(this.renderSession);
  6872. };
  6873. /**
  6874. * Renders a flat strip
  6875. *
  6876. * @method renderStripFlat
  6877. * @param strip {Strip} The Strip to render
  6878. * @private
  6879. */
  6880. PIXI.CanvasRenderer.prototype.renderStripFlat = function(strip)
  6881. {
  6882. var context = this.context;
  6883. var verticies = strip.verticies;
  6884. var length = verticies.length/2;
  6885. this.count++;
  6886. context.beginPath();
  6887. for (var i=1; i < length-2; i++)
  6888. {
  6889. // draw some triangles!
  6890. var index = i*2;
  6891. var x0 = verticies[index], x1 = verticies[index+2], x2 = verticies[index+4];
  6892. var y0 = verticies[index+1], y1 = verticies[index+3], y2 = verticies[index+5];
  6893. context.moveTo(x0, y0);
  6894. context.lineTo(x1, y1);
  6895. context.lineTo(x2, y2);
  6896. }
  6897. context.fillStyle = "#FF0000";
  6898. context.fill();
  6899. context.closePath();
  6900. };
  6901. /**
  6902. * Renders a strip
  6903. *
  6904. * @method renderStrip
  6905. * @param strip {Strip} The Strip to render
  6906. * @private
  6907. */
  6908. PIXI.CanvasRenderer.prototype.renderStrip = function(strip)
  6909. {
  6910. var context = this.context;
  6911. // draw triangles!!
  6912. var verticies = strip.verticies;
  6913. var uvs = strip.uvs;
  6914. var length = verticies.length/2;
  6915. this.count++;
  6916. for (var i = 1; i < length-2; i++)
  6917. {
  6918. // draw some triangles!
  6919. var index = i*2;
  6920. var x0 = verticies[index], x1 = verticies[index+2], x2 = verticies[index+4];
  6921. var y0 = verticies[index+1], y1 = verticies[index+3], y2 = verticies[index+5];
  6922. var u0 = uvs[index] * strip.texture.width, u1 = uvs[index+2] * strip.texture.width, u2 = uvs[index+4]* strip.texture.width;
  6923. var v0 = uvs[index+1]* strip.texture.height, v1 = uvs[index+3] * strip.texture.height, v2 = uvs[index+5]* strip.texture.height;
  6924. context.save();
  6925. context.beginPath();
  6926. context.moveTo(x0, y0);
  6927. context.lineTo(x1, y1);
  6928. context.lineTo(x2, y2);
  6929. context.closePath();
  6930. context.clip();
  6931. // Compute matrix transform
  6932. var delta = u0*v1 + v0*u2 + u1*v2 - v1*u2 - v0*u1 - u0*v2;
  6933. var deltaA = x0*v1 + v0*x2 + x1*v2 - v1*x2 - v0*x1 - x0*v2;
  6934. var deltaB = u0*x1 + x0*u2 + u1*x2 - x1*u2 - x0*u1 - u0*x2;
  6935. var deltaC = u0*v1*x2 + v0*x1*u2 + x0*u1*v2 - x0*v1*u2 - v0*u1*x2 - u0*x1*v2;
  6936. var deltaD = y0*v1 + v0*y2 + y1*v2 - v1*y2 - v0*y1 - y0*v2;
  6937. var deltaE = u0*y1 + y0*u2 + u1*y2 - y1*u2 - y0*u1 - u0*y2;
  6938. var deltaF = u0*v1*y2 + v0*y1*u2 + y0*u1*v2 - y0*v1*u2 - v0*u1*y2 - u0*y1*v2;
  6939. context.transform(deltaA / delta, deltaD / delta,
  6940. deltaB / delta, deltaE / delta,
  6941. deltaC / delta, deltaF / delta);
  6942. context.drawImage(strip.texture.baseTexture.source, 0, 0);
  6943. context.restore();
  6944. }
  6945. };
  6946. /**
  6947. * Creates a Canvas element of the given size
  6948. *
  6949. * @method CanvasBuffer
  6950. * @param width {Number} the width for the newly created canvas
  6951. * @param height {Number} the height for the newly created canvas
  6952. * @static
  6953. * @private
  6954. */
  6955. PIXI.CanvasBuffer = function(width, height)
  6956. {
  6957. this.width = width;
  6958. this.height = height;
  6959. this.canvas = document.createElement( "canvas" );
  6960. this.context = this.canvas.getContext( "2d" );
  6961. this.canvas.width = width;
  6962. this.canvas.height = height;
  6963. };
  6964. /**
  6965. * Clears the canvas that was created by the CanvasBuffer class
  6966. *
  6967. * @method clear
  6968. * @private
  6969. */
  6970. PIXI.CanvasBuffer.prototype.clear = function()
  6971. {
  6972. this.context.clearRect(0,0, this.width, this.height);
  6973. };
  6974. /**
  6975. * Resizes the canvas that was created by the CanvasBuffer class to the specified width and height
  6976. *
  6977. * @method resize
  6978. * @param width {Number} the new width of the canvas
  6979. * @param height {Number} the new height of the canvas
  6980. * @private
  6981. */
  6982. PIXI.CanvasBuffer.prototype.resize = function(width, height)
  6983. {
  6984. this.width = this.canvas.width = width;
  6985. this.height = this.canvas.height = height;
  6986. };
  6987. /**
  6988. * @author Mat Groves http://matgroves.com/ @Doormat23
  6989. */
  6990. /**
  6991. * A set of functions used by the canvas renderer to draw the primitive graphics data
  6992. *
  6993. * @class CanvasGraphics
  6994. */
  6995. PIXI.CanvasGraphics = function()
  6996. {
  6997. };
  6998. /*
  6999. * Renders the graphics object
  7000. *
  7001. * @static
  7002. * @private
  7003. * @method renderGraphics
  7004. * @param graphics {Graphics} the actual graphics object to render
  7005. * @param context {Context2D} the 2d drawing method of the canvas
  7006. */
  7007. PIXI.CanvasGraphics.renderGraphics = function(graphics, context)
  7008. {
  7009. var worldAlpha = graphics.worldAlpha;
  7010. var color = '';
  7011. for (var i = 0; i < graphics.graphicsData.length; i++)
  7012. {
  7013. var data = graphics.graphicsData[i];
  7014. var points = data.points;
  7015. context.strokeStyle = color = '#' + ('00000' + ( data.lineColor | 0).toString(16)).substr(-6);
  7016. context.lineWidth = data.lineWidth;
  7017. if(data.type === PIXI.Graphics.POLY)
  7018. {
  7019. context.beginPath();
  7020. context.moveTo(points[0], points[1]);
  7021. for (var j=1; j < points.length/2; j++)
  7022. {
  7023. context.lineTo(points[j * 2], points[j * 2 + 1]);
  7024. }
  7025. // if the first and last point are the same close the path - much neater :)
  7026. if(points[0] === points[points.length-2] && points[1] === points[points.length-1])
  7027. {
  7028. context.closePath();
  7029. }
  7030. if(data.fill)
  7031. {
  7032. context.globalAlpha = data.fillAlpha * worldAlpha;
  7033. context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
  7034. context.fill();
  7035. }
  7036. if(data.lineWidth)
  7037. {
  7038. context.globalAlpha = data.lineAlpha * worldAlpha;
  7039. context.stroke();
  7040. }
  7041. }
  7042. else if(data.type === PIXI.Graphics.RECT)
  7043. {
  7044. if(data.fillColor || data.fillColor === 0)
  7045. {
  7046. context.globalAlpha = data.fillAlpha * worldAlpha;
  7047. context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
  7048. context.fillRect(points[0], points[1], points[2], points[3]);
  7049. }
  7050. if(data.lineWidth)
  7051. {
  7052. context.globalAlpha = data.lineAlpha * worldAlpha;
  7053. context.strokeRect(points[0], points[1], points[2], points[3]);
  7054. }
  7055. }
  7056. else if(data.type === PIXI.Graphics.CIRC)
  7057. {
  7058. // TODO - need to be Undefined!
  7059. context.beginPath();
  7060. context.arc(points[0], points[1], points[2],0,2*Math.PI);
  7061. context.closePath();
  7062. if(data.fill)
  7063. {
  7064. context.globalAlpha = data.fillAlpha * worldAlpha;
  7065. context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
  7066. context.fill();
  7067. }
  7068. if(data.lineWidth)
  7069. {
  7070. context.globalAlpha = data.lineAlpha * worldAlpha;
  7071. context.stroke();
  7072. }
  7073. }
  7074. else if(data.type === PIXI.Graphics.ELIP)
  7075. {
  7076. // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7077. var ellipseData = data.points;
  7078. var w = ellipseData[2] * 2;
  7079. var h = ellipseData[3] * 2;
  7080. var x = ellipseData[0] - w/2;
  7081. var y = ellipseData[1] - h/2;
  7082. context.beginPath();
  7083. var kappa = 0.5522848,
  7084. ox = (w / 2) * kappa, // control point offset horizontal
  7085. oy = (h / 2) * kappa, // control point offset vertical
  7086. xe = x + w, // x-end
  7087. ye = y + h, // y-end
  7088. xm = x + w / 2, // x-middle
  7089. ym = y + h / 2; // y-middle
  7090. context.moveTo(x, ym);
  7091. context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7092. context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7093. context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7094. context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7095. context.closePath();
  7096. if(data.fill)
  7097. {
  7098. context.globalAlpha = data.fillAlpha * worldAlpha;
  7099. context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
  7100. context.fill();
  7101. }
  7102. if(data.lineWidth)
  7103. {
  7104. context.globalAlpha = data.lineAlpha * worldAlpha;
  7105. context.stroke();
  7106. }
  7107. }
  7108. else if (data.type === PIXI.Graphics.RREC)
  7109. {
  7110. var rx = points[0];
  7111. var ry = points[1];
  7112. var width = points[2];
  7113. var height = points[3];
  7114. var radius = points[4];
  7115. var maxRadius = Math.min(width, height) / 2 | 0;
  7116. radius = radius > maxRadius ? maxRadius : radius;
  7117. context.beginPath();
  7118. context.moveTo(rx, ry + radius);
  7119. context.lineTo(rx, ry + height - radius);
  7120. context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height);
  7121. context.lineTo(rx + width - radius, ry + height);
  7122. context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius);
  7123. context.lineTo(rx + width, ry + radius);
  7124. context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry);
  7125. context.lineTo(rx + radius, ry);
  7126. context.quadraticCurveTo(rx, ry, rx, ry + radius);
  7127. context.closePath();
  7128. if(data.fillColor || data.fillColor === 0)
  7129. {
  7130. context.globalAlpha = data.fillAlpha * worldAlpha;
  7131. context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
  7132. context.fill();
  7133. }
  7134. if(data.lineWidth)
  7135. {
  7136. context.globalAlpha = data.lineAlpha * worldAlpha;
  7137. context.stroke();
  7138. }
  7139. }
  7140. }
  7141. };
  7142. /*
  7143. * Renders a graphics mask
  7144. *
  7145. * @static
  7146. * @private
  7147. * @method renderGraphicsMask
  7148. * @param graphics {Graphics} the graphics which will be used as a mask
  7149. * @param context {Context2D} the context 2d method of the canvas
  7150. */
  7151. PIXI.CanvasGraphics.renderGraphicsMask = function(graphics, context)
  7152. {
  7153. var len = graphics.graphicsData.length;
  7154. if(len === 0) return;
  7155. if(len > 1)
  7156. {
  7157. len = 1;
  7158. window.console.log('Pixi.js warning: masks in canvas can only mask using the first path in the graphics object');
  7159. }
  7160. for (var i = 0; i < 1; i++)
  7161. {
  7162. var data = graphics.graphicsData[i];
  7163. var points = data.points;
  7164. if(data.type === PIXI.Graphics.POLY)
  7165. {
  7166. context.beginPath();
  7167. context.moveTo(points[0], points[1]);
  7168. for (var j=1; j < points.length/2; j++)
  7169. {
  7170. context.lineTo(points[j * 2], points[j * 2 + 1]);
  7171. }
  7172. // if the first and last point are the same close the path - much neater :)
  7173. if(points[0] === points[points.length-2] && points[1] === points[points.length-1])
  7174. {
  7175. context.closePath();
  7176. }
  7177. }
  7178. else if(data.type === PIXI.Graphics.RECT)
  7179. {
  7180. context.beginPath();
  7181. context.rect(points[0], points[1], points[2], points[3]);
  7182. context.closePath();
  7183. }
  7184. else if(data.type === PIXI.Graphics.CIRC)
  7185. {
  7186. // TODO - need to be Undefined!
  7187. context.beginPath();
  7188. context.arc(points[0], points[1], points[2],0,2*Math.PI);
  7189. context.closePath();
  7190. }
  7191. else if(data.type === PIXI.Graphics.ELIP)
  7192. {
  7193. // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7194. var ellipseData = data.points;
  7195. var w = ellipseData[2] * 2;
  7196. var h = ellipseData[3] * 2;
  7197. var x = ellipseData[0] - w/2;
  7198. var y = ellipseData[1] - h/2;
  7199. context.beginPath();
  7200. var kappa = 0.5522848,
  7201. ox = (w / 2) * kappa, // control point offset horizontal
  7202. oy = (h / 2) * kappa, // control point offset vertical
  7203. xe = x + w, // x-end
  7204. ye = y + h, // y-end
  7205. xm = x + w / 2, // x-middle
  7206. ym = y + h / 2; // y-middle
  7207. context.moveTo(x, ym);
  7208. context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7209. context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7210. context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7211. context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7212. context.closePath();
  7213. }
  7214. else if (data.type === PIXI.Graphics.RREC)
  7215. {
  7216. var rx = points[0];
  7217. var ry = points[1];
  7218. var width = points[2];
  7219. var height = points[3];
  7220. var radius = points[4];
  7221. var maxRadius = Math.min(width, height) / 2 | 0;
  7222. radius = radius > maxRadius ? maxRadius : radius;
  7223. context.beginPath();
  7224. context.moveTo(rx, ry + radius);
  7225. context.lineTo(rx, ry + height - radius);
  7226. context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height);
  7227. context.lineTo(rx + width - radius, ry + height);
  7228. context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius);
  7229. context.lineTo(rx + width, ry + radius);
  7230. context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry);
  7231. context.lineTo(rx + radius, ry);
  7232. context.quadraticCurveTo(rx, ry, rx, ry + radius);
  7233. context.closePath();
  7234. }
  7235. }
  7236. };
  7237. /**
  7238. * @author Mat Groves http://matgroves.com/ @Doormat23
  7239. */
  7240. /**
  7241. * The Graphics class contains a set of methods that you can use to create primitive shapes and lines.
  7242. * It is important to know that with the webGL renderer only simple polygons can be filled at this stage
  7243. * Complex polygons will not be filled. Heres an example of a complex polygon: http://www.goodboydigital.com/wp-content/uploads/2013/06/complexPolygon.png
  7244. *
  7245. * @class Graphics
  7246. * @extends DisplayObjectContainer
  7247. * @constructor
  7248. */
  7249. PIXI.Graphics = function()
  7250. {
  7251. PIXI.DisplayObjectContainer.call( this );
  7252. this.renderable = true;
  7253. /**
  7254. * The alpha of the fill of this graphics object
  7255. *
  7256. * @property fillAlpha
  7257. * @type Number
  7258. */
  7259. this.fillAlpha = 1;
  7260. /**
  7261. * The width of any lines drawn
  7262. *
  7263. * @property lineWidth
  7264. * @type Number
  7265. */
  7266. this.lineWidth = 0;
  7267. /**
  7268. * The color of any lines drawn
  7269. *
  7270. * @property lineColor
  7271. * @type String
  7272. */
  7273. this.lineColor = "black";
  7274. /**
  7275. * Graphics data
  7276. *
  7277. * @property graphicsData
  7278. * @type Array
  7279. * @private
  7280. */
  7281. this.graphicsData = [];
  7282. /**
  7283. * The tint applied to the graphic shape. This is a hex value
  7284. *
  7285. * @property tint
  7286. * @type Number
  7287. * @default 0xFFFFFF
  7288. */
  7289. this.tint = 0xFFFFFF;// * Math.random();
  7290. /**
  7291. * The blend mode to be applied to the graphic shape
  7292. *
  7293. * @property blendMode
  7294. * @type Number
  7295. * @default PIXI.blendModes.NORMAL;
  7296. */
  7297. this.blendMode = PIXI.blendModes.NORMAL;
  7298. /**
  7299. * Current path
  7300. *
  7301. * @property currentPath
  7302. * @type Object
  7303. * @private
  7304. */
  7305. this.currentPath = {points:[]};
  7306. /**
  7307. * Array containing some WebGL-related properties used by the WebGL renderer
  7308. *
  7309. * @property _webGL
  7310. * @type Array
  7311. * @private
  7312. */
  7313. this._webGL = [];
  7314. /**
  7315. * Whether this shape is being used as a mask
  7316. *
  7317. * @property isMask
  7318. * @type isMask
  7319. */
  7320. this.isMask = false;
  7321. /**
  7322. * The bounds of the graphic shape as rectangle object
  7323. *
  7324. * @property bounds
  7325. * @type Rectangle
  7326. */
  7327. this.bounds = null;
  7328. /**
  7329. * the bounds' padding used for bounds calculation
  7330. *
  7331. * @property boundsPadding
  7332. * @type Number
  7333. */
  7334. this.boundsPadding = 10;
  7335. /**
  7336. * Used to detect if the graphics object has changed if this is set to true then the graphics object will be recalculated
  7337. *
  7338. * @type {Boolean}
  7339. */
  7340. this.dirty = true;
  7341. };
  7342. // constructor
  7343. PIXI.Graphics.prototype = Object.create( PIXI.DisplayObjectContainer.prototype );
  7344. PIXI.Graphics.prototype.constructor = PIXI.Graphics;
  7345. /**
  7346. * If cacheAsBitmap is true the graphics object will then be rendered as if it was a sprite.
  7347. * This is useful if your graphics element does not change often as it will speed up the rendering of the object
  7348. * It is also usful as the graphics object will always be antialiased because it will be rendered using canvas
  7349. * Not recommended if you are constanly redrawing the graphics element.
  7350. *
  7351. * @property cacheAsBitmap
  7352. * @default false
  7353. * @type Boolean
  7354. * @private
  7355. */
  7356. Object.defineProperty(PIXI.Graphics.prototype, "cacheAsBitmap", {
  7357. get: function() {
  7358. return this._cacheAsBitmap;
  7359. },
  7360. set: function(value) {
  7361. this._cacheAsBitmap = value;
  7362. if(this._cacheAsBitmap)
  7363. {
  7364. this._generateCachedSprite();
  7365. }
  7366. else
  7367. {
  7368. this.destroyCachedSprite();
  7369. this.dirty = true;
  7370. }
  7371. }
  7372. });
  7373. /**
  7374. * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method.
  7375. *
  7376. * @method lineStyle
  7377. * @param lineWidth {Number} width of the line to draw, will update the object's stored style
  7378. * @param color {Number} color of the line to draw, will update the object's stored style
  7379. * @param alpha {Number} alpha of the line to draw, will update the object's stored style
  7380. */
  7381. PIXI.Graphics.prototype.lineStyle = function(lineWidth, color, alpha)
  7382. {
  7383. if (!this.currentPath.points.length) this.graphicsData.pop();
  7384. this.lineWidth = lineWidth || 0;
  7385. this.lineColor = color || 0;
  7386. this.lineAlpha = (arguments.length < 3) ? 1 : alpha;
  7387. this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha,
  7388. fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling, points:[], type:PIXI.Graphics.POLY};
  7389. this.graphicsData.push(this.currentPath);
  7390. return this;
  7391. };
  7392. /**
  7393. * Moves the current drawing position to (x, y).
  7394. *
  7395. * @method moveTo
  7396. * @param x {Number} the X coordinate to move to
  7397. * @param y {Number} the Y coordinate to move to
  7398. */
  7399. PIXI.Graphics.prototype.moveTo = function(x, y)
  7400. {
  7401. if (!this.currentPath.points.length) this.graphicsData.pop();
  7402. this.currentPath = this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha,
  7403. fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling, points:[], type:PIXI.Graphics.POLY};
  7404. this.currentPath.points.push(x, y);
  7405. this.graphicsData.push(this.currentPath);
  7406. return this;
  7407. };
  7408. /**
  7409. * Draws a line using the current line style from the current drawing position to (x, y);
  7410. * the current drawing position is then set to (x, y).
  7411. *
  7412. * @method lineTo
  7413. * @param x {Number} the X coordinate to draw to
  7414. * @param y {Number} the Y coordinate to draw to
  7415. */
  7416. PIXI.Graphics.prototype.lineTo = function(x, y)
  7417. {
  7418. this.currentPath.points.push(x, y);
  7419. this.dirty = true;
  7420. return this;
  7421. };
  7422. /**
  7423. * Calculate the points for a quadratic bezier curve.
  7424. * Based on : https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
  7425. *
  7426. * @method quadraticCurveTo
  7427. * @param {number} cpX Control point x
  7428. * @param {number} cpY Control point y
  7429. * @param {number} toX Destination point x
  7430. * @param {number} toY Destination point y
  7431. * @return {PIXI.Graphics}
  7432. */
  7433. PIXI.Graphics.prototype.quadraticCurveTo = function(cpX, cpY, toX, toY)
  7434. {
  7435. if( this.currentPath.points.length === 0)this.moveTo(0,0);
  7436. var xa,
  7437. ya,
  7438. n = 20,
  7439. points = this.currentPath.points;
  7440. if(points.length === 0)this.moveTo(0, 0);
  7441. var fromX = points[points.length-2];
  7442. var fromY = points[points.length-1];
  7443. var j = 0;
  7444. for (var i = 1; i <= n; i++ )
  7445. {
  7446. j = i / n;
  7447. xa = fromX + ( (cpX - fromX) * j );
  7448. ya = fromY + ( (cpY - fromY) * j );
  7449. points.push( xa + ( ((cpX + ( (toX - cpX) * j )) - xa) * j ),
  7450. ya + ( ((cpY + ( (toY - cpY) * j )) - ya) * j ) );
  7451. }
  7452. this.dirty = true;
  7453. return this;
  7454. };
  7455. /**
  7456. * Calculate the points for a bezier curve.
  7457. *
  7458. * @method bezierCurveTo
  7459. * @param {number} cpX Control point x
  7460. * @param {number} cpY Control point y
  7461. * @param {number} cpX2 Second Control point x
  7462. * @param {number} cpY2 Second Control point y
  7463. * @param {number} toX Destination point x
  7464. * @param {number} toY Destination point y
  7465. * @return {PIXI.Graphics}
  7466. */
  7467. PIXI.Graphics.prototype.bezierCurveTo = function(cpX, cpY, cpX2, cpY2, toX, toY)
  7468. {
  7469. if( this.currentPath.points.length === 0)this.moveTo(0,0);
  7470. var n = 20,
  7471. dt,
  7472. dt2,
  7473. dt3,
  7474. t2,
  7475. t3,
  7476. points = this.currentPath.points;
  7477. var fromX = points[points.length-2];
  7478. var fromY = points[points.length-1];
  7479. var j = 0;
  7480. for (var i=1; i<n; i++)
  7481. {
  7482. j = i / n;
  7483. dt = (1 - j);
  7484. dt2 = dt * dt;
  7485. dt3 = dt2 * dt;
  7486. t2 = j * j;
  7487. t3 = t2 * j;
  7488. points.push( dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX,
  7489. dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY);
  7490. }
  7491. this.dirty = true;
  7492. return this;
  7493. };
  7494. /*
  7495. * the arcTo() method creates an arc/curve between two tangents on the canvas.
  7496. *
  7497. * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google!
  7498. *
  7499. * @method arcTo
  7500. * @param {number} x1 The x-coordinate of the beginning of the arc
  7501. * @param {number} y1 The y-coordinate of the beginning of the arc
  7502. * @param {number} x2 The x-coordinate of the end of the arc
  7503. * @param {number} y2 The y-coordinate of the end of the arc
  7504. * @param {number} radius The radius of the arc
  7505. * @return {PIXI.Graphics}
  7506. */
  7507. PIXI.Graphics.prototype.arcTo = function(x1, y1, x2, y2, radius)
  7508. {
  7509. // check that path contains subpaths
  7510. if( this.currentPath.points.length === 0)this.moveTo(x1, y1);
  7511. var points = this.currentPath.points;
  7512. var fromX = points[points.length-2];
  7513. var fromY = points[points.length-1];
  7514. // points.push( x1, y1);
  7515. var a1 = fromY - y1;
  7516. var b1 = fromX - x1;
  7517. var a2 = y2 - y1;
  7518. var b2 = x2 - x1;
  7519. var mm = Math.abs(a1 * b2 - b1 * a2);
  7520. if (mm < 1.0e-8 || radius === 0)
  7521. {
  7522. points.push(x1, y1);
  7523. }
  7524. else
  7525. {
  7526. var dd = a1 * a1 + b1 * b1;
  7527. var cc = a2 * a2 + b2 * b2;
  7528. var tt = a1 * a2 + b1 * b2;
  7529. var k1 = radius * Math.sqrt(dd) / mm;
  7530. var k2 = radius * Math.sqrt(cc) / mm;
  7531. var j1 = k1 * tt / dd;
  7532. var j2 = k2 * tt / cc;
  7533. var cx = k1 * b2 + k2 * b1;
  7534. var cy = k1 * a2 + k2 * a1;
  7535. var px = b1 * (k2 + j1);
  7536. var py = a1 * (k2 + j1);
  7537. var qx = b2 * (k1 + j2);
  7538. var qy = a2 * (k1 + j2);
  7539. var startAngle = Math.atan2(py - cy, px - cx);
  7540. var endAngle = Math.atan2(qy - cy, qx - cx);
  7541. // not required?
  7542. // points.push(px + x1 , py + y1);
  7543. this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1);
  7544. }
  7545. this.dirty = true;
  7546. return this;
  7547. };
  7548. /**
  7549. * The arc() method creates an arc/curve (used to create circles, or parts of circles).
  7550. *
  7551. * @method arc
  7552. * @param {number} cx The x-coordinate of the center of the circle
  7553. * @param {number} cy The y-coordinate of the center of the circle
  7554. * @param {number} radius The radius of the circle
  7555. * @param {number} startAngle The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle)
  7556. * @param {number} endAngle The ending angle, in radians
  7557. * @param {number} anticlockwise Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise.
  7558. * @return {PIXI.Graphics}
  7559. */
  7560. PIXI.Graphics.prototype.arc = function(cx, cy, radius, startAngle, endAngle, anticlockwise)
  7561. {
  7562. var startX = cx + Math.cos(startAngle) * radius;
  7563. var startY = cy + Math.sin(startAngle) * radius;
  7564. var points = this.currentPath.points;
  7565. if(points.length !== 0 && points[points.length-2] !== startX || points[points.length-1] !== startY)
  7566. {
  7567. this.moveTo(startX, startY);
  7568. points = this.currentPath.points;
  7569. }
  7570. if (startAngle === endAngle)return this;
  7571. if( !anticlockwise && endAngle <= startAngle )
  7572. {
  7573. endAngle += Math.PI * 2;
  7574. }
  7575. else if( anticlockwise && startAngle <= endAngle )
  7576. {
  7577. startAngle += Math.PI * 2;
  7578. }
  7579. var sweep = anticlockwise ? (startAngle - endAngle) *-1 : (endAngle - startAngle);
  7580. var segs = ( Math.abs(sweep)/ (Math.PI * 2) ) * 40;
  7581. if( sweep === 0 ) return this;
  7582. var theta = sweep/(segs*2);
  7583. var theta2 = theta*2;
  7584. var cTheta = Math.cos(theta);
  7585. var sTheta = Math.sin(theta);
  7586. var segMinus = segs - 1;
  7587. var remainder = ( segMinus % 1 ) / segMinus;
  7588. for(var i=0; i<=segMinus; i++)
  7589. {
  7590. var real = i + remainder * i;
  7591. var angle = ((theta) + startAngle + (theta2 * real));
  7592. var c = Math.cos(angle);
  7593. var s = -Math.sin(angle);
  7594. points.push(( (cTheta * c) + (sTheta * s) ) * radius + cx,
  7595. ( (cTheta * -s) + (sTheta * c) ) * radius + cy);
  7596. }
  7597. this.dirty = true;
  7598. return this;
  7599. };
  7600. /**
  7601. * Draws a line using the current line style from the current drawing position to (x, y);
  7602. * the current drawing position is then set to (x, y).
  7603. *
  7604. * @method lineTo
  7605. * @param x {Number} the X coordinate to draw to
  7606. * @param y {Number} the Y coordinate to draw to
  7607. */
  7608. PIXI.Graphics.prototype.drawPath = function(path)
  7609. {
  7610. if (!this.currentPath.points.length) this.graphicsData.pop();
  7611. this.currentPath = this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha,
  7612. fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling, points:[], type:PIXI.Graphics.POLY};
  7613. this.graphicsData.push(this.currentPath);
  7614. this.currentPath.points = this.currentPath.points.concat(path);
  7615. this.dirty = true;
  7616. return this;
  7617. };
  7618. /**
  7619. * Specifies a simple one-color fill that subsequent calls to other Graphics methods
  7620. * (such as lineTo() or drawCircle()) use when drawing.
  7621. *
  7622. * @method beginFill
  7623. * @param color {Number} the color of the fill
  7624. * @param alpha {Number} the alpha of the fill
  7625. */
  7626. PIXI.Graphics.prototype.beginFill = function(color, alpha)
  7627. {
  7628. this.filling = true;
  7629. this.fillColor = color || 0;
  7630. this.fillAlpha = (arguments.length < 2) ? 1 : alpha;
  7631. return this;
  7632. };
  7633. /**
  7634. * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method.
  7635. *
  7636. * @method endFill
  7637. */
  7638. PIXI.Graphics.prototype.endFill = function()
  7639. {
  7640. this.filling = false;
  7641. this.fillColor = null;
  7642. this.fillAlpha = 1;
  7643. return this;
  7644. };
  7645. /**
  7646. * @method drawRect
  7647. *
  7648. * @param x {Number} The X coord of the top-left of the rectangle
  7649. * @param y {Number} The Y coord of the top-left of the rectangle
  7650. * @param width {Number} The width of the rectangle
  7651. * @param height {Number} The height of the rectangle
  7652. */
  7653. PIXI.Graphics.prototype.drawRect = function( x, y, width, height )
  7654. {
  7655. if (!this.currentPath.points.length) this.graphicsData.pop();
  7656. this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha,
  7657. fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling,
  7658. points:[x, y, width, height], type:PIXI.Graphics.RECT};
  7659. this.graphicsData.push(this.currentPath);
  7660. this.dirty = true;
  7661. return this;
  7662. };
  7663. /**
  7664. * @method drawRoundedRect
  7665. *
  7666. * @param x {Number} The X coord of the top-left of the rectangle
  7667. * @param y {Number} The Y coord of the top-left of the rectangle
  7668. * @param width {Number} The width of the rectangle
  7669. * @param height {Number} The height of the rectangle
  7670. * @param radius {Number} Radius of the rectangle corners
  7671. */
  7672. PIXI.Graphics.prototype.drawRoundedRect = function( x, y, width, height, radius )
  7673. {
  7674. if (!this.currentPath.points.length) this.graphicsData.pop();
  7675. this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha,
  7676. fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling,
  7677. points:[x, y, width, height, radius], type:PIXI.Graphics.RREC};
  7678. this.graphicsData.push(this.currentPath);
  7679. this.dirty = true;
  7680. return this;
  7681. };
  7682. /**
  7683. * Draws a circle.
  7684. *
  7685. * @method drawCircle
  7686. * @param x {Number} The X coordinate of the center of the circle
  7687. * @param y {Number} The Y coordinate of the center of the circle
  7688. * @param radius {Number} The radius of the circle
  7689. */
  7690. PIXI.Graphics.prototype.drawCircle = function(x, y, radius)
  7691. {
  7692. if (!this.currentPath.points.length) this.graphicsData.pop();
  7693. this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha,
  7694. fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling,
  7695. points:[x, y, radius, radius], type:PIXI.Graphics.CIRC};
  7696. this.graphicsData.push(this.currentPath);
  7697. this.dirty = true;
  7698. return this;
  7699. };
  7700. /**
  7701. * Draws an ellipse.
  7702. *
  7703. * @method drawEllipse
  7704. * @param x {Number} The X coordinate of the center of the ellipse
  7705. * @param y {Number} The Y coordinate of the center of the ellipse
  7706. * @param width {Number} The half width of the ellipse
  7707. * @param height {Number} The half height of the ellipse
  7708. */
  7709. PIXI.Graphics.prototype.drawEllipse = function(x, y, width, height)
  7710. {
  7711. if (!this.currentPath.points.length) this.graphicsData.pop();
  7712. this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha,
  7713. fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling,
  7714. points:[x, y, width, height], type:PIXI.Graphics.ELIP};
  7715. this.graphicsData.push(this.currentPath);
  7716. this.dirty = true;
  7717. return this;
  7718. };
  7719. /**
  7720. * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
  7721. *
  7722. * @method clear
  7723. */
  7724. PIXI.Graphics.prototype.clear = function()
  7725. {
  7726. this.lineWidth = 0;
  7727. this.filling = false;
  7728. this.dirty = true;
  7729. this.clearDirty = true;
  7730. this.graphicsData = [];
  7731. this.bounds = null; //new PIXI.Rectangle();
  7732. return this;
  7733. };
  7734. /**
  7735. * Useful function that returns a texture of the graphics object that can then be used to create sprites
  7736. * This can be quite useful if your geometry is complicated and needs to be reused multiple times.
  7737. *
  7738. * @method generateTexture
  7739. * @return {Texture} a texture of the graphics object
  7740. */
  7741. PIXI.Graphics.prototype.generateTexture = function()
  7742. {
  7743. var bounds = this.getBounds();
  7744. var canvasBuffer = new PIXI.CanvasBuffer(bounds.width, bounds.height);
  7745. var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas);
  7746. canvasBuffer.context.translate(-bounds.x,-bounds.y);
  7747. PIXI.CanvasGraphics.renderGraphics(this, canvasBuffer.context);
  7748. return texture;
  7749. };
  7750. /**
  7751. * Renders the object using the WebGL renderer
  7752. *
  7753. * @method _renderWebGL
  7754. * @param renderSession {RenderSession}
  7755. * @private
  7756. */
  7757. PIXI.Graphics.prototype._renderWebGL = function(renderSession)
  7758. {
  7759. // if the sprite is not visible or the alpha is 0 then no need to render this element
  7760. if(this.visible === false || this.alpha === 0 || this.isMask === true)return;
  7761. if(this._cacheAsBitmap)
  7762. {
  7763. if(this.dirty)
  7764. {
  7765. this._generateCachedSprite();
  7766. // we will also need to update the texture on the gpu too!
  7767. PIXI.updateWebGLTexture(this._cachedSprite.texture.baseTexture, renderSession.gl);
  7768. this.dirty = false;
  7769. }
  7770. this._cachedSprite.alpha = this.alpha;
  7771. PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession);
  7772. return;
  7773. }
  7774. else
  7775. {
  7776. renderSession.spriteBatch.stop();
  7777. renderSession.blendModeManager.setBlendMode(this.blendMode);
  7778. if(this._mask)renderSession.maskManager.pushMask(this._mask, renderSession);
  7779. if(this._filters)renderSession.filterManager.pushFilter(this._filterBlock);
  7780. // check blend mode
  7781. if(this.blendMode !== renderSession.spriteBatch.currentBlendMode)
  7782. {
  7783. renderSession.spriteBatch.currentBlendMode = this.blendMode;
  7784. var blendModeWebGL = PIXI.blendModesWebGL[renderSession.spriteBatch.currentBlendMode];
  7785. renderSession.spriteBatch.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]);
  7786. }
  7787. // for (var i = this.graphicsData.length - 1; i >= 0; i--) {
  7788. // this.graphicsData[i]
  7789. // };
  7790. PIXI.WebGLGraphics.renderGraphics(this, renderSession);
  7791. // only render if it has children!
  7792. if(this.children.length)
  7793. {
  7794. renderSession.spriteBatch.start();
  7795. // simple render children!
  7796. for(var i=0, j=this.children.length; i<j; i++)
  7797. {
  7798. this.children[i]._renderWebGL(renderSession);
  7799. }
  7800. renderSession.spriteBatch.stop();
  7801. }
  7802. if(this._filters)renderSession.filterManager.popFilter();
  7803. if(this._mask)renderSession.maskManager.popMask(this.mask, renderSession);
  7804. renderSession.drawCount++;
  7805. renderSession.spriteBatch.start();
  7806. }
  7807. };
  7808. /**
  7809. * Renders the object using the Canvas renderer
  7810. *
  7811. * @method _renderCanvas
  7812. * @param renderSession {RenderSession}
  7813. * @private
  7814. */
  7815. PIXI.Graphics.prototype._renderCanvas = function(renderSession)
  7816. {
  7817. // if the sprite is not visible or the alpha is 0 then no need to render this element
  7818. if(this.visible === false || this.alpha === 0 || this.isMask === true)return;
  7819. var context = renderSession.context;
  7820. var transform = this.worldTransform;
  7821. if(this.blendMode !== renderSession.currentBlendMode)
  7822. {
  7823. renderSession.currentBlendMode = this.blendMode;
  7824. context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
  7825. }
  7826. if(this._mask)
  7827. {
  7828. renderSession.maskManager.pushMask(this._mask, renderSession.context);
  7829. }
  7830. context.setTransform(transform.a, transform.c, transform.b, transform.d, transform.tx, transform.ty);
  7831. PIXI.CanvasGraphics.renderGraphics(this, context);
  7832. // simple render children!
  7833. for(var i=0, j=this.children.length; i<j; i++)
  7834. {
  7835. this.children[i]._renderCanvas(renderSession);
  7836. }
  7837. if(this._mask)
  7838. {
  7839. renderSession.maskManager.popMask(renderSession.context);
  7840. }
  7841. };
  7842. /**
  7843. * Retrieves the bounds of the graphic shape as a rectangle object
  7844. *
  7845. * @method getBounds
  7846. * @return {Rectangle} the rectangular bounding area
  7847. */
  7848. PIXI.Graphics.prototype.getBounds = function( matrix )
  7849. {
  7850. if(!this.bounds)this.updateBounds();
  7851. var w0 = this.bounds.x;
  7852. var w1 = this.bounds.width + this.bounds.x;
  7853. var h0 = this.bounds.y;
  7854. var h1 = this.bounds.height + this.bounds.y;
  7855. var worldTransform = matrix || this.worldTransform;
  7856. var a = worldTransform.a;
  7857. var b = worldTransform.c;
  7858. var c = worldTransform.b;
  7859. var d = worldTransform.d;
  7860. var tx = worldTransform.tx;
  7861. var ty = worldTransform.ty;
  7862. var x1 = a * w1 + c * h1 + tx;
  7863. var y1 = d * h1 + b * w1 + ty;
  7864. var x2 = a * w0 + c * h1 + tx;
  7865. var y2 = d * h1 + b * w0 + ty;
  7866. var x3 = a * w0 + c * h0 + tx;
  7867. var y3 = d * h0 + b * w0 + ty;
  7868. var x4 = a * w1 + c * h0 + tx;
  7869. var y4 = d * h0 + b * w1 + ty;
  7870. var maxX = x1;
  7871. var maxY = y1;
  7872. var minX = x1;
  7873. var minY = y1;
  7874. minX = x2 < minX ? x2 : minX;
  7875. minX = x3 < minX ? x3 : minX;
  7876. minX = x4 < minX ? x4 : minX;
  7877. minY = y2 < minY ? y2 : minY;
  7878. minY = y3 < minY ? y3 : minY;
  7879. minY = y4 < minY ? y4 : minY;
  7880. maxX = x2 > maxX ? x2 : maxX;
  7881. maxX = x3 > maxX ? x3 : maxX;
  7882. maxX = x4 > maxX ? x4 : maxX;
  7883. maxY = y2 > maxY ? y2 : maxY;
  7884. maxY = y3 > maxY ? y3 : maxY;
  7885. maxY = y4 > maxY ? y4 : maxY;
  7886. var bounds = this._bounds;
  7887. bounds.x = minX;
  7888. bounds.width = maxX - minX;
  7889. bounds.y = minY;
  7890. bounds.height = maxY - minY;
  7891. return bounds;
  7892. };
  7893. /**
  7894. * Update the bounds of the object
  7895. *
  7896. * @method updateBounds
  7897. */
  7898. PIXI.Graphics.prototype.updateBounds = function()
  7899. {
  7900. var minX = Infinity;
  7901. var maxX = -Infinity;
  7902. var minY = Infinity;
  7903. var maxY = -Infinity;
  7904. var points, x, y, w, h;
  7905. for (var i = 0; i < this.graphicsData.length; i++) {
  7906. var data = this.graphicsData[i];
  7907. var type = data.type;
  7908. var lineWidth = data.lineWidth;
  7909. points = data.points;
  7910. if(type === PIXI.Graphics.RECT)
  7911. {
  7912. x = points[0] - lineWidth/2;
  7913. y = points[1] - lineWidth/2;
  7914. w = points[2] + lineWidth;
  7915. h = points[3] + lineWidth;
  7916. minX = x < minX ? x : minX;
  7917. maxX = x + w > maxX ? x + w : maxX;
  7918. minY = y < minY ? x : minY;
  7919. maxY = y + h > maxY ? y + h : maxY;
  7920. }
  7921. else if(type === PIXI.Graphics.CIRC || type === PIXI.Graphics.ELIP)
  7922. {
  7923. x = points[0];
  7924. y = points[1];
  7925. w = points[2] + lineWidth/2;
  7926. h = points[3] + lineWidth/2;
  7927. minX = x - w < minX ? x - w : minX;
  7928. maxX = x + w > maxX ? x + w : maxX;
  7929. minY = y - h < minY ? y - h : minY;
  7930. maxY = y + h > maxY ? y + h : maxY;
  7931. }
  7932. else
  7933. {
  7934. // POLY
  7935. for (var j = 0; j < points.length; j+=2)
  7936. {
  7937. x = points[j];
  7938. y = points[j+1];
  7939. minX = x-lineWidth < minX ? x-lineWidth : minX;
  7940. maxX = x+lineWidth > maxX ? x+lineWidth : maxX;
  7941. minY = y-lineWidth < minY ? y-lineWidth : minY;
  7942. maxY = y+lineWidth > maxY ? y+lineWidth : maxY;
  7943. }
  7944. }
  7945. }
  7946. var padding = this.boundsPadding;
  7947. this.bounds = new PIXI.Rectangle(minX - padding, minY - padding, (maxX - minX) + padding * 2, (maxY - minY) + padding * 2);
  7948. };
  7949. /**
  7950. * Generates the cached sprite when the sprite has cacheAsBitmap = true
  7951. *
  7952. * @method _generateCachedSprite
  7953. * @private
  7954. */
  7955. PIXI.Graphics.prototype._generateCachedSprite = function()
  7956. {
  7957. var bounds = this.getLocalBounds();
  7958. if(!this._cachedSprite)
  7959. {
  7960. var canvasBuffer = new PIXI.CanvasBuffer(bounds.width, bounds.height);
  7961. var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas);
  7962. this._cachedSprite = new PIXI.Sprite(texture);
  7963. this._cachedSprite.buffer = canvasBuffer;
  7964. this._cachedSprite.worldTransform = this.worldTransform;
  7965. }
  7966. else
  7967. {
  7968. this._cachedSprite.buffer.resize(bounds.width, bounds.height);
  7969. }
  7970. // leverage the anchor to account for the offset of the element
  7971. this._cachedSprite.anchor.x = -( bounds.x / bounds.width );
  7972. this._cachedSprite.anchor.y = -( bounds.y / bounds.height );
  7973. // this._cachedSprite.buffer.context.save();
  7974. this._cachedSprite.buffer.context.translate(-bounds.x,-bounds.y);
  7975. PIXI.CanvasGraphics.renderGraphics(this, this._cachedSprite.buffer.context);
  7976. this._cachedSprite.alpha = this.alpha;
  7977. // this._cachedSprite.buffer.context.restore();
  7978. };
  7979. PIXI.Graphics.prototype.destroyCachedSprite = function()
  7980. {
  7981. this._cachedSprite.texture.destroy(true);
  7982. // let the gc collect the unused sprite
  7983. // TODO could be object pooled!
  7984. this._cachedSprite = null;
  7985. };
  7986. // SOME TYPES:
  7987. PIXI.Graphics.POLY = 0;
  7988. PIXI.Graphics.RECT = 1;
  7989. PIXI.Graphics.CIRC = 2;
  7990. PIXI.Graphics.ELIP = 3;
  7991. PIXI.Graphics.RREC = 4;
  7992. /**
  7993. * @author Mat Groves http://matgroves.com/
  7994. */
  7995. /**
  7996. *
  7997. * @class Strip
  7998. * @extends DisplayObjectContainer
  7999. * @constructor
  8000. * @param texture {Texture} The texture to use
  8001. * @param width {Number} the width
  8002. * @param height {Number} the height
  8003. *
  8004. */
  8005. PIXI.Strip = function(texture)
  8006. {
  8007. PIXI.DisplayObjectContainer.call( this );
  8008. this.texture = texture;
  8009. // set up the main bits..
  8010. this.uvs = new PIXI.Float32Array([0, 1,
  8011. 1, 1,
  8012. 1, 0,
  8013. 0,1]);
  8014. this.verticies = new PIXI.Float32Array([0, 0,
  8015. 100,0,
  8016. 100,100,
  8017. 0, 100]);
  8018. this.colors = new PIXI.Float32Array([1, 1, 1, 1]);
  8019. this.indices = new PIXI.Uint16Array([0, 1, 2, 3]);
  8020. this.dirty = true;
  8021. };
  8022. // constructor
  8023. PIXI.Strip.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  8024. PIXI.Strip.prototype.constructor = PIXI.Strip;
  8025. PIXI.Strip.prototype._renderWebGL = function(renderSession)
  8026. {
  8027. // if the sprite is not visible or the alpha is 0 then no need to render this element
  8028. if(!this.visible || this.alpha <= 0)return;
  8029. // render triangle strip..
  8030. renderSession.spriteBatch.stop();
  8031. // init! init!
  8032. if(!this._vertexBuffer)this._initWebGL(renderSession);
  8033. renderSession.shaderManager.setShader(renderSession.shaderManager.stripShader);
  8034. this._renderStrip(renderSession);
  8035. ///renderSession.shaderManager.activateDefaultShader();
  8036. renderSession.spriteBatch.start();
  8037. //TODO check culling
  8038. };
  8039. PIXI.Strip.prototype._initWebGL = function(renderSession)
  8040. {
  8041. // build the strip!
  8042. var gl = renderSession.gl;
  8043. this._vertexBuffer = gl.createBuffer();
  8044. this._indexBuffer = gl.createBuffer();
  8045. this._uvBuffer = gl.createBuffer();
  8046. this._colorBuffer = gl.createBuffer();
  8047. gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
  8048. gl.bufferData(gl.ARRAY_BUFFER, this.verticies, gl.DYNAMIC_DRAW);
  8049. gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer);
  8050. gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW);
  8051. gl.bindBuffer(gl.ARRAY_BUFFER, this._colorBuffer);
  8052. gl.bufferData(gl.ARRAY_BUFFER, this.colors, gl.STATIC_DRAW);
  8053. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer);
  8054. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
  8055. };
  8056. PIXI.Strip.prototype._renderStrip = function(renderSession)
  8057. {
  8058. var gl = renderSession.gl;
  8059. var projection = renderSession.projection,
  8060. offset = renderSession.offset,
  8061. shader = renderSession.shaderManager.stripShader;
  8062. // gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mat4Real);
  8063. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  8064. // set uniforms
  8065. gl.uniformMatrix3fv(shader.translationMatrix, false, this.worldTransform.toArray(true));
  8066. gl.uniform2f(shader.projectionVector, projection.x, -projection.y);
  8067. gl.uniform2f(shader.offsetVector, -offset.x, -offset.y);
  8068. gl.uniform1f(shader.alpha, 1);
  8069. if(!this.dirty)
  8070. {
  8071. gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
  8072. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.verticies);
  8073. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
  8074. // update the uvs
  8075. gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer);
  8076. gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
  8077. gl.activeTexture(gl.TEXTURE0);
  8078. // bind the current texture
  8079. gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id] || PIXI.createWebGLTexture(this.texture.baseTexture, gl));
  8080. // dont need to upload!
  8081. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer);
  8082. }
  8083. else
  8084. {
  8085. this.dirty = false;
  8086. gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
  8087. gl.bufferData(gl.ARRAY_BUFFER, this.verticies, gl.STATIC_DRAW);
  8088. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
  8089. // update the uvs
  8090. gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer);
  8091. gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW);
  8092. gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
  8093. gl.activeTexture(gl.TEXTURE0);
  8094. gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id] || PIXI.createWebGLTexture(this.texture.baseTexture, gl));
  8095. // dont need to upload!
  8096. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer);
  8097. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
  8098. }
  8099. //console.log(gl.TRIANGLE_STRIP)
  8100. //
  8101. //
  8102. gl.drawElements(gl.TRIANGLE_STRIP, this.indices.length, gl.UNSIGNED_SHORT, 0);
  8103. };
  8104. PIXI.Strip.prototype._renderCanvas = function(renderSession)
  8105. {
  8106. var context = renderSession.context;
  8107. var transform = this.worldTransform;
  8108. if (renderSession.roundPixels)
  8109. {
  8110. context.setTransform(transform.a, transform.c, transform.b, transform.d, transform.tx | 0, transform.ty | 0);
  8111. }
  8112. else
  8113. {
  8114. context.setTransform(transform.a, transform.c, transform.b, transform.d, transform.tx, transform.ty);
  8115. }
  8116. var strip = this;
  8117. // draw triangles!!
  8118. var verticies = strip.verticies;
  8119. var uvs = strip.uvs;
  8120. var length = verticies.length/2;
  8121. this.count++;
  8122. for (var i = 0; i < length-2; i++)
  8123. {
  8124. // draw some triangles!
  8125. var index = i*2;
  8126. var x0 = verticies[index], x1 = verticies[index+2], x2 = verticies[index+4];
  8127. var y0 = verticies[index+1], y1 = verticies[index+3], y2 = verticies[index+5];
  8128. if(true)
  8129. {
  8130. //expand();
  8131. var centerX = (x0 + x1 + x2)/3;
  8132. var centerY = (y0 + y1 + y2)/3;
  8133. var normX = x0 - centerX;
  8134. var normY = y0 - centerY;
  8135. var dist = Math.sqrt( normX * normX + normY * normY );
  8136. x0 = centerX + (normX / dist) * (dist + 3);
  8137. y0 = centerY + (normY / dist) * (dist + 3);
  8138. //
  8139. normX = x1 - centerX;
  8140. normY = y1 - centerY;
  8141. dist = Math.sqrt( normX * normX + normY * normY );
  8142. x1 = centerX + (normX / dist) * (dist + 3);
  8143. y1 = centerY + (normY / dist) * (dist + 3);
  8144. normX = x2 - centerX;
  8145. normY = y2 - centerY;
  8146. dist = Math.sqrt( normX * normX + normY * normY );
  8147. x2 = centerX + (normX / dist) * (dist + 3);
  8148. y2 = centerY + (normY / dist) * (dist + 3);
  8149. }
  8150. var u0 = uvs[index] * strip.texture.width, u1 = uvs[index+2] * strip.texture.width, u2 = uvs[index+4]* strip.texture.width;
  8151. var v0 = uvs[index+1]* strip.texture.height, v1 = uvs[index+3] * strip.texture.height, v2 = uvs[index+5]* strip.texture.height;
  8152. context.save();
  8153. context.beginPath();
  8154. context.moveTo(x0, y0);
  8155. context.lineTo(x1, y1);
  8156. context.lineTo(x2, y2);
  8157. context.closePath();
  8158. context.clip();
  8159. // Compute matrix transform
  8160. var delta = u0*v1 + v0*u2 + u1*v2 - v1*u2 - v0*u1 - u0*v2;
  8161. var deltaA = x0*v1 + v0*x2 + x1*v2 - v1*x2 - v0*x1 - x0*v2;
  8162. var deltaB = u0*x1 + x0*u2 + u1*x2 - x1*u2 - x0*u1 - u0*x2;
  8163. var deltaC = u0*v1*x2 + v0*x1*u2 + x0*u1*v2 - x0*v1*u2 - v0*u1*x2 - u0*x1*v2;
  8164. var deltaD = y0*v1 + v0*y2 + y1*v2 - v1*y2 - v0*y1 - y0*v2;
  8165. var deltaE = u0*y1 + y0*u2 + u1*y2 - y1*u2 - y0*u1 - u0*y2;
  8166. var deltaF = u0*v1*y2 + v0*y1*u2 + y0*u1*v2 - y0*v1*u2 - v0*u1*y2 - u0*y1*v2;
  8167. context.transform(deltaA / delta, deltaD / delta,
  8168. deltaB / delta, deltaE / delta,
  8169. deltaC / delta, deltaF / delta);
  8170. context.drawImage(strip.texture.baseTexture.source, 0, 0);
  8171. context.restore();
  8172. }
  8173. };
  8174. /*
  8175. * Sets the texture that the Strip will use
  8176. *
  8177. * @method setTexture
  8178. * @param texture {Texture} the texture that will be used
  8179. * @private
  8180. */
  8181. /*
  8182. PIXI.Strip.prototype.setTexture = function(texture)
  8183. {
  8184. //TODO SET THE TEXTURES
  8185. //TODO VISIBILITY
  8186. // stop current texture
  8187. this.texture = texture;
  8188. this.width = texture.frame.width;
  8189. this.height = texture.frame.height;
  8190. this.updateFrame = true;
  8191. };
  8192. */
  8193. /**
  8194. * When the texture is updated, this event will fire to update the scale and frame
  8195. *
  8196. * @method onTextureUpdate
  8197. * @param event
  8198. * @private
  8199. */
  8200. PIXI.Strip.prototype.onTextureUpdate = function()
  8201. {
  8202. this.updateFrame = true;
  8203. };
  8204. /* @author Mat Groves http://matgroves.com/ @Doormat23
  8205. */
  8206. /**
  8207. *
  8208. * @class Rope
  8209. * @constructor
  8210. * @param texture {Texture} The texture to use
  8211. * @param points {Array}
  8212. *
  8213. */
  8214. PIXI.Rope = function(texture, points)
  8215. {
  8216. PIXI.Strip.call( this, texture );
  8217. this.points = points;
  8218. this.verticies = new PIXI.Float32Array(points.length * 4);
  8219. this.uvs = new PIXI.Float32Array(points.length * 4);
  8220. this.colors = new PIXI.Float32Array(points.length * 2);
  8221. this.indices = new PIXI.Uint16Array(points.length * 2);
  8222. this.refresh();
  8223. };
  8224. // constructor
  8225. PIXI.Rope.prototype = Object.create( PIXI.Strip.prototype );
  8226. PIXI.Rope.prototype.constructor = PIXI.Rope;
  8227. /*
  8228. * Refreshes
  8229. *
  8230. * @method refresh
  8231. */
  8232. PIXI.Rope.prototype.refresh = function()
  8233. {
  8234. var points = this.points;
  8235. if(points.length < 1) return;
  8236. var uvs = this.uvs;
  8237. var lastPoint = points[0];
  8238. var indices = this.indices;
  8239. var colors = this.colors;
  8240. this.count-=0.2;
  8241. uvs[0] = 0;
  8242. uvs[1] = 0;
  8243. uvs[2] = 0;
  8244. uvs[3] = 1;
  8245. colors[0] = 1;
  8246. colors[1] = 1;
  8247. indices[0] = 0;
  8248. indices[1] = 1;
  8249. var total = points.length,
  8250. point, index, amount;
  8251. for (var i = 1; i < total; i++)
  8252. {
  8253. point = points[i];
  8254. index = i * 4;
  8255. // time to do some smart drawing!
  8256. amount = i / (total-1);
  8257. if(i%2)
  8258. {
  8259. uvs[index] = amount;
  8260. uvs[index+1] = 0;
  8261. uvs[index+2] = amount;
  8262. uvs[index+3] = 1;
  8263. }
  8264. else
  8265. {
  8266. uvs[index] = amount;
  8267. uvs[index+1] = 0;
  8268. uvs[index+2] = amount;
  8269. uvs[index+3] = 1;
  8270. }
  8271. index = i * 2;
  8272. colors[index] = 1;
  8273. colors[index+1] = 1;
  8274. index = i * 2;
  8275. indices[index] = index;
  8276. indices[index + 1] = index + 1;
  8277. lastPoint = point;
  8278. }
  8279. };
  8280. /*
  8281. * Updates the object transform for rendering
  8282. *
  8283. * @method updateTransform
  8284. * @private
  8285. */
  8286. PIXI.Rope.prototype.updateTransform = function()
  8287. {
  8288. var points = this.points;
  8289. if(points.length < 1)return;
  8290. var lastPoint = points[0];
  8291. var nextPoint;
  8292. var perp = {x:0, y:0};
  8293. this.count-=0.2;
  8294. var verticies = this.verticies;
  8295. var total = points.length,
  8296. point, index, ratio, perpLength, num;
  8297. for (var i = 0; i < total; i++)
  8298. {
  8299. point = points[i];
  8300. index = i * 4;
  8301. if(i < points.length-1)
  8302. {
  8303. nextPoint = points[i+1];
  8304. }
  8305. else
  8306. {
  8307. nextPoint = point;
  8308. }
  8309. perp.y = -(nextPoint.x - lastPoint.x);
  8310. perp.x = nextPoint.y - lastPoint.y;
  8311. ratio = (1 - (i / (total-1))) * 10;
  8312. if(ratio > 1) ratio = 1;
  8313. perpLength = Math.sqrt(perp.x * perp.x + perp.y * perp.y);
  8314. num = this.texture.height / 2; //(20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio;
  8315. perp.x /= perpLength;
  8316. perp.y /= perpLength;
  8317. perp.x *= num;
  8318. perp.y *= num;
  8319. verticies[index] = point.x + perp.x;
  8320. verticies[index+1] = point.y + perp.y;
  8321. verticies[index+2] = point.x - perp.x;
  8322. verticies[index+3] = point.y - perp.y;
  8323. lastPoint = point;
  8324. }
  8325. PIXI.DisplayObjectContainer.prototype.updateTransform.call( this );
  8326. };
  8327. /*
  8328. * Sets the texture that the Rope will use
  8329. *
  8330. * @method setTexture
  8331. * @param texture {Texture} the texture that will be used
  8332. */
  8333. PIXI.Rope.prototype.setTexture = function(texture)
  8334. {
  8335. // stop current texture
  8336. this.texture = texture;
  8337. //this.updateFrame = true;
  8338. };
  8339. /**
  8340. * @author Mat Groves http://matgroves.com/
  8341. */
  8342. /**
  8343. * A tiling sprite is a fast way of rendering a tiling image
  8344. *
  8345. * @class TilingSprite
  8346. * @extends Sprite
  8347. * @constructor
  8348. * @param texture {Texture} the texture of the tiling sprite
  8349. * @param width {Number} the width of the tiling sprite
  8350. * @param height {Number} the height of the tiling sprite
  8351. */
  8352. PIXI.TilingSprite = function(texture, width, height)
  8353. {
  8354. PIXI.Sprite.call( this, texture);
  8355. /**
  8356. * The with of the tiling sprite
  8357. *
  8358. * @property width
  8359. * @type Number
  8360. */
  8361. this._width = width || 100;
  8362. /**
  8363. * The height of the tiling sprite
  8364. *
  8365. * @property height
  8366. * @type Number
  8367. */
  8368. this._height = height || 100;
  8369. /**
  8370. * The scaling of the image that is being tiled
  8371. *
  8372. * @property tileScale
  8373. * @type Point
  8374. */
  8375. this.tileScale = new PIXI.Point(1,1);
  8376. /**
  8377. * A point that represents the scale of the texture object
  8378. *
  8379. * @property tileScaleOffset
  8380. * @type Point
  8381. */
  8382. this.tileScaleOffset = new PIXI.Point(1,1);
  8383. /**
  8384. * The offset position of the image that is being tiled
  8385. *
  8386. * @property tilePosition
  8387. * @type Point
  8388. */
  8389. this.tilePosition = new PIXI.Point(0,0);
  8390. /**
  8391. * Whether this sprite is renderable or not
  8392. *
  8393. * @property renderable
  8394. * @type Boolean
  8395. * @default true
  8396. */
  8397. this.renderable = true;
  8398. /**
  8399. * The tint applied to the sprite. This is a hex value
  8400. *
  8401. * @property tint
  8402. * @type Number
  8403. * @default 0xFFFFFF
  8404. */
  8405. this.tint = 0xFFFFFF;
  8406. /**
  8407. * The blend mode to be applied to the sprite
  8408. *
  8409. * @property blendMode
  8410. * @type Number
  8411. * @default PIXI.blendModes.NORMAL;
  8412. */
  8413. this.blendMode = PIXI.blendModes.NORMAL;
  8414. };
  8415. // constructor
  8416. PIXI.TilingSprite.prototype = Object.create(PIXI.Sprite.prototype);
  8417. PIXI.TilingSprite.prototype.constructor = PIXI.TilingSprite;
  8418. /**
  8419. * The width of the sprite, setting this will actually modify the scale to achieve the value set
  8420. *
  8421. * @property width
  8422. * @type Number
  8423. */
  8424. Object.defineProperty(PIXI.TilingSprite.prototype, 'width', {
  8425. get: function() {
  8426. return this._width;
  8427. },
  8428. set: function(value) {
  8429. this._width = value;
  8430. }
  8431. });
  8432. /**
  8433. * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set
  8434. *
  8435. * @property height
  8436. * @type Number
  8437. */
  8438. Object.defineProperty(PIXI.TilingSprite.prototype, 'height', {
  8439. get: function() {
  8440. return this._height;
  8441. },
  8442. set: function(value) {
  8443. this._height = value;
  8444. }
  8445. });
  8446. PIXI.TilingSprite.prototype.setTexture = function(texture)
  8447. {
  8448. if (this.texture === texture) return;
  8449. this.texture = texture;
  8450. this.refreshTexture = true;
  8451. this.cachedTint = 0xFFFFFF;
  8452. };
  8453. /**
  8454. * Renders the object using the WebGL renderer
  8455. *
  8456. * @method _renderWebGL
  8457. * @param renderSession {RenderSession}
  8458. * @private
  8459. */
  8460. PIXI.TilingSprite.prototype._renderWebGL = function(renderSession)
  8461. {
  8462. if (this.visible === false || this.alpha === 0) return;
  8463. var i,j;
  8464. if (this._mask)
  8465. {
  8466. renderSession.spriteBatch.stop();
  8467. renderSession.maskManager.pushMask(this.mask, renderSession);
  8468. renderSession.spriteBatch.start();
  8469. }
  8470. if (this._filters)
  8471. {
  8472. renderSession.spriteBatch.flush();
  8473. renderSession.filterManager.pushFilter(this._filterBlock);
  8474. }
  8475. if (!this.tilingTexture || this.refreshTexture)
  8476. {
  8477. this.generateTilingTexture(true);
  8478. if (this.tilingTexture && this.tilingTexture.needsUpdate)
  8479. {
  8480. //TODO - tweaking
  8481. PIXI.updateWebGLTexture(this.tilingTexture.baseTexture, renderSession.gl);
  8482. this.tilingTexture.needsUpdate = false;
  8483. // this.tilingTexture._uvs = null;
  8484. }
  8485. }
  8486. else
  8487. {
  8488. renderSession.spriteBatch.renderTilingSprite(this);
  8489. }
  8490. // simple render children!
  8491. for (i=0,j=this.children.length; i<j; i++)
  8492. {
  8493. this.children[i]._renderWebGL(renderSession);
  8494. }
  8495. renderSession.spriteBatch.stop();
  8496. if (this._filters) renderSession.filterManager.popFilter();
  8497. if (this._mask) renderSession.maskManager.popMask(renderSession);
  8498. renderSession.spriteBatch.start();
  8499. };
  8500. /**
  8501. * Renders the object using the Canvas renderer
  8502. *
  8503. * @method _renderCanvas
  8504. * @param renderSession {RenderSession}
  8505. * @private
  8506. */
  8507. PIXI.TilingSprite.prototype._renderCanvas = function(renderSession)
  8508. {
  8509. if (this.visible === false || this.alpha === 0)return;
  8510. var context = renderSession.context;
  8511. if (this._mask)
  8512. {
  8513. renderSession.maskManager.pushMask(this._mask, context);
  8514. }
  8515. context.globalAlpha = this.worldAlpha;
  8516. var transform = this.worldTransform;
  8517. var i,j;
  8518. context.setTransform(transform.a, transform.c, transform.b, transform.d, transform.tx , transform.ty);
  8519. if (!this.__tilePattern || this.refreshTexture)
  8520. {
  8521. this.generateTilingTexture(false);
  8522. if (this.tilingTexture)
  8523. {
  8524. this.__tilePattern = context.createPattern(this.tilingTexture.baseTexture.source, 'repeat');
  8525. }
  8526. else
  8527. {
  8528. return;
  8529. }
  8530. }
  8531. // check blend mode
  8532. if (this.blendMode !== renderSession.currentBlendMode)
  8533. {
  8534. renderSession.currentBlendMode = this.blendMode;
  8535. context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
  8536. }
  8537. var tilePosition = this.tilePosition;
  8538. var tileScale = this.tileScale;
  8539. tilePosition.x %= this.tilingTexture.baseTexture.width;
  8540. tilePosition.y %= this.tilingTexture.baseTexture.height;
  8541. // offset
  8542. context.scale(tileScale.x,tileScale.y);
  8543. context.translate(tilePosition.x, tilePosition.y);
  8544. context.fillStyle = this.__tilePattern;
  8545. // make sure to account for the anchor point..
  8546. context.fillRect(-tilePosition.x + (this.anchor.x * -this._width),
  8547. -tilePosition.y + (this.anchor.y * -this._height),
  8548. this._width / tileScale.x,
  8549. this._height / tileScale.y);
  8550. context.scale(1 / tileScale.x, 1 / tileScale.y);
  8551. context.translate(-tilePosition.x, -tilePosition.y);
  8552. if (this._mask)
  8553. {
  8554. renderSession.maskManager.popMask(renderSession.context);
  8555. }
  8556. for (i=0,j=this.children.length; i<j; i++)
  8557. {
  8558. this.children[i]._renderCanvas(renderSession);
  8559. }
  8560. };
  8561. /**
  8562. * Returns the framing rectangle of the sprite as a PIXI.Rectangle object
  8563. *
  8564. * @method getBounds
  8565. * @return {Rectangle} the framing rectangle
  8566. */
  8567. PIXI.TilingSprite.prototype.getBounds = function()
  8568. {
  8569. var width = this._width;
  8570. var height = this._height;
  8571. var w0 = width * (1-this.anchor.x);
  8572. var w1 = width * -this.anchor.x;
  8573. var h0 = height * (1-this.anchor.y);
  8574. var h1 = height * -this.anchor.y;
  8575. var worldTransform = this.worldTransform;
  8576. var a = worldTransform.a;
  8577. var b = worldTransform.c;
  8578. var c = worldTransform.b;
  8579. var d = worldTransform.d;
  8580. var tx = worldTransform.tx;
  8581. var ty = worldTransform.ty;
  8582. var x1 = a * w1 + c * h1 + tx;
  8583. var y1 = d * h1 + b * w1 + ty;
  8584. var x2 = a * w0 + c * h1 + tx;
  8585. var y2 = d * h1 + b * w0 + ty;
  8586. var x3 = a * w0 + c * h0 + tx;
  8587. var y3 = d * h0 + b * w0 + ty;
  8588. var x4 = a * w1 + c * h0 + tx;
  8589. var y4 = d * h0 + b * w1 + ty;
  8590. var maxX = -Infinity;
  8591. var maxY = -Infinity;
  8592. var minX = Infinity;
  8593. var minY = Infinity;
  8594. minX = x1 < minX ? x1 : minX;
  8595. minX = x2 < minX ? x2 : minX;
  8596. minX = x3 < minX ? x3 : minX;
  8597. minX = x4 < minX ? x4 : minX;
  8598. minY = y1 < minY ? y1 : minY;
  8599. minY = y2 < minY ? y2 : minY;
  8600. minY = y3 < minY ? y3 : minY;
  8601. minY = y4 < minY ? y4 : minY;
  8602. maxX = x1 > maxX ? x1 : maxX;
  8603. maxX = x2 > maxX ? x2 : maxX;
  8604. maxX = x3 > maxX ? x3 : maxX;
  8605. maxX = x4 > maxX ? x4 : maxX;
  8606. maxY = y1 > maxY ? y1 : maxY;
  8607. maxY = y2 > maxY ? y2 : maxY;
  8608. maxY = y3 > maxY ? y3 : maxY;
  8609. maxY = y4 > maxY ? y4 : maxY;
  8610. var bounds = this._bounds;
  8611. bounds.x = minX;
  8612. bounds.width = maxX - minX;
  8613. bounds.y = minY;
  8614. bounds.height = maxY - minY;
  8615. // store a reference so that if this function gets called again in the render cycle we do not have to recalculate
  8616. this._currentBounds = bounds;
  8617. return bounds;
  8618. };
  8619. /**
  8620. * When the texture is updated, this event will fire to update the scale and frame
  8621. *
  8622. * @method onTextureUpdate
  8623. * @param event
  8624. * @private
  8625. */
  8626. PIXI.TilingSprite.prototype.onTextureUpdate = function()
  8627. {
  8628. // overriding the sprite version of this!
  8629. };
  8630. /**
  8631. *
  8632. * @method generateTilingTexture
  8633. *
  8634. * @param forcePowerOfTwo {Boolean} Whether we want to force the texture to be a power of two
  8635. */
  8636. PIXI.TilingSprite.prototype.generateTilingTexture = function(forcePowerOfTwo)
  8637. {
  8638. if (!this.texture.baseTexture.hasLoaded) return;
  8639. var texture = this.texture;
  8640. var frame = texture.frame;
  8641. var targetWidth, targetHeight;
  8642. // Check that the frame is the same size as the base texture.
  8643. var isFrame = frame.width !== texture.baseTexture.width || frame.height !== texture.baseTexture.height;
  8644. var newTextureRequired = false;
  8645. if (!forcePowerOfTwo)
  8646. {
  8647. if (isFrame)
  8648. {
  8649. targetWidth = frame.width;
  8650. targetHeight = frame.height;
  8651. newTextureRequired = true;
  8652. }
  8653. }
  8654. else
  8655. {
  8656. targetWidth = PIXI.getNextPowerOfTwo(frame.width);
  8657. targetHeight = PIXI.getNextPowerOfTwo(frame.height);
  8658. if (frame.width !== targetWidth || frame.height !== targetHeight) newTextureRequired = true;
  8659. }
  8660. if (newTextureRequired)
  8661. {
  8662. var canvasBuffer;
  8663. if (this.tilingTexture && this.tilingTexture.isTiling)
  8664. {
  8665. canvasBuffer = this.tilingTexture.canvasBuffer;
  8666. canvasBuffer.resize(targetWidth, targetHeight);
  8667. this.tilingTexture.baseTexture.width = targetWidth;
  8668. this.tilingTexture.baseTexture.height = targetHeight;
  8669. this.tilingTexture.needsUpdate = true;
  8670. }
  8671. else
  8672. {
  8673. canvasBuffer = new PIXI.CanvasBuffer(targetWidth, targetHeight);
  8674. this.tilingTexture = PIXI.Texture.fromCanvas(canvasBuffer.canvas);
  8675. this.tilingTexture.canvasBuffer = canvasBuffer;
  8676. this.tilingTexture.isTiling = true;
  8677. }
  8678. canvasBuffer.context.drawImage(texture.baseTexture.source,
  8679. texture.crop.x,
  8680. texture.crop.y,
  8681. texture.crop.width,
  8682. texture.crop.height,
  8683. 0,
  8684. 0,
  8685. targetWidth,
  8686. targetHeight);
  8687. this.tileScaleOffset.x = frame.width / targetWidth;
  8688. this.tileScaleOffset.y = frame.height / targetHeight;
  8689. }
  8690. else
  8691. {
  8692. // TODO - switching?
  8693. if (this.tilingTexture && this.tilingTexture.isTiling)
  8694. {
  8695. // destroy the tiling texture!
  8696. // TODO could store this somewhere?
  8697. this.tilingTexture.destroy(true);
  8698. }
  8699. this.tileScaleOffset.x = 1;
  8700. this.tileScaleOffset.y = 1;
  8701. this.tilingTexture = texture;
  8702. }
  8703. this.refreshTexture = false;
  8704. this.tilingTexture.baseTexture._powerOf2 = true;
  8705. };
  8706. /**
  8707. * @author Mat Groves http://matgroves.com/ @Doormat23
  8708. */
  8709. PIXI.BaseTextureCache = {};
  8710. PIXI.texturesToUpdate = [];
  8711. PIXI.texturesToDestroy = [];
  8712. PIXI.BaseTextureCacheIdGenerator = 0;
  8713. /**
  8714. * A texture stores the information that represents an image. All textures have a base texture
  8715. *
  8716. * @class BaseTexture
  8717. * @uses EventTarget
  8718. * @constructor
  8719. * @param source {String} the source object (image or canvas)
  8720. * @param scaleMode {Number} Should be one of the PIXI.scaleMode consts
  8721. */
  8722. PIXI.BaseTexture = function(source, scaleMode)
  8723. {
  8724. PIXI.EventTarget.call( this );
  8725. /**
  8726. * [read-only] The width of the base texture set when the image has loaded
  8727. *
  8728. * @property width
  8729. * @type Number
  8730. * @readOnly
  8731. */
  8732. this.width = 100;
  8733. /**
  8734. * [read-only] The height of the base texture set when the image has loaded
  8735. *
  8736. * @property height
  8737. * @type Number
  8738. * @readOnly
  8739. */
  8740. this.height = 100;
  8741. /**
  8742. * The scale mode to apply when scaling this texture
  8743. * @property scaleMode
  8744. * @type PIXI.scaleModes
  8745. * @default PIXI.scaleModes.LINEAR
  8746. */
  8747. this.scaleMode = scaleMode || PIXI.scaleModes.DEFAULT;
  8748. /**
  8749. * [read-only] Describes if the base texture has loaded or not
  8750. *
  8751. * @property hasLoaded
  8752. * @type Boolean
  8753. * @readOnly
  8754. */
  8755. this.hasLoaded = false;
  8756. /**
  8757. * The source that is loaded to create the texture
  8758. *
  8759. * @property source
  8760. * @type Image
  8761. */
  8762. this.source = source;
  8763. //TODO will be used for futer pixi 1.5...
  8764. this.id = PIXI.BaseTextureCacheIdGenerator++;
  8765. /**
  8766. * Controls if RGB channels should be premultiplied by Alpha (WebGL only)
  8767. *
  8768. * @property
  8769. * @type Boolean
  8770. * @default TRUE
  8771. */
  8772. this.premultipliedAlpha = true;
  8773. // used for webGL
  8774. this._glTextures = [];
  8775. // used for webGL teture updateing...
  8776. this._dirty = [];
  8777. if(!source)return;
  8778. if((this.source.complete || this.source.getContext) && this.source.width && this.source.height)
  8779. {
  8780. this.hasLoaded = true;
  8781. this.width = this.source.width;
  8782. this.height = this.source.height;
  8783. PIXI.texturesToUpdate.push(this);
  8784. }
  8785. else
  8786. {
  8787. var scope = this;
  8788. this.source.onload = function() {
  8789. scope.hasLoaded = true;
  8790. scope.width = scope.source.width;
  8791. scope.height = scope.source.height;
  8792. for (var i = 0; i < scope._glTextures.length; i++)
  8793. {
  8794. scope._dirty[i] = true;
  8795. }
  8796. // add it to somewhere...
  8797. scope.dispatchEvent( { type: 'loaded', content: scope } );
  8798. };
  8799. this.source.onerror = function() {
  8800. scope.dispatchEvent( { type: 'error', content: scope } );
  8801. };
  8802. }
  8803. this.imageUrl = null;
  8804. this._powerOf2 = false;
  8805. };
  8806. PIXI.BaseTexture.prototype.constructor = PIXI.BaseTexture;
  8807. /**
  8808. * Destroys this base texture
  8809. *
  8810. * @method destroy
  8811. */
  8812. PIXI.BaseTexture.prototype.destroy = function()
  8813. {
  8814. if(this.imageUrl)
  8815. {
  8816. delete PIXI.BaseTextureCache[this.imageUrl];
  8817. delete PIXI.TextureCache[this.imageUrl];
  8818. this.imageUrl = null;
  8819. this.source.src = null;
  8820. }
  8821. else if (this.source && this.source._pixiId)
  8822. {
  8823. delete PIXI.BaseTextureCache[this.source._pixiId];
  8824. }
  8825. this.source = null;
  8826. PIXI.texturesToDestroy.push(this);
  8827. };
  8828. /**
  8829. * Changes the source image of the texture
  8830. *
  8831. * @method updateSourceImage
  8832. * @param newSrc {String} the path of the image
  8833. */
  8834. PIXI.BaseTexture.prototype.updateSourceImage = function(newSrc)
  8835. {
  8836. this.hasLoaded = false;
  8837. this.source.src = null;
  8838. this.source.src = newSrc;
  8839. };
  8840. /**
  8841. * Helper function that returns a base texture based on an image url
  8842. * If the image is not in the base texture cache it will be created and loaded
  8843. *
  8844. * @static
  8845. * @method fromImage
  8846. * @param imageUrl {String} The image url of the texture
  8847. * @param crossorigin {Boolean}
  8848. * @param scaleMode {Number} Should be one of the PIXI.scaleMode consts
  8849. * @return BaseTexture
  8850. */
  8851. PIXI.BaseTexture.fromImage = function(imageUrl, crossorigin, scaleMode)
  8852. {
  8853. var baseTexture = PIXI.BaseTextureCache[imageUrl];
  8854. if(crossorigin === undefined && imageUrl.indexOf('data:') === -1) crossorigin = true;
  8855. if(!baseTexture)
  8856. {
  8857. // new Image() breaks tex loading in some versions of Chrome.
  8858. // See https://code.google.com/p/chromium/issues/detail?id=238071
  8859. var image = new Image();//document.createElement('img');
  8860. if (crossorigin)
  8861. {
  8862. image.crossOrigin = '';
  8863. }
  8864. image.src = imageUrl;
  8865. baseTexture = new PIXI.BaseTexture(image, scaleMode);
  8866. baseTexture.imageUrl = imageUrl;
  8867. PIXI.BaseTextureCache[imageUrl] = baseTexture;
  8868. }
  8869. return baseTexture;
  8870. };
  8871. /**
  8872. * Helper function that returns a base texture based on a canvas element
  8873. * If the image is not in the base texture cache it will be created and loaded
  8874. *
  8875. * @static
  8876. * @method fromCanvas
  8877. * @param canvas {Canvas} The canvas element source of the texture
  8878. * @param scaleMode {Number} Should be one of the PIXI.scaleMode consts
  8879. * @return BaseTexture
  8880. */
  8881. PIXI.BaseTexture.fromCanvas = function(canvas, scaleMode)
  8882. {
  8883. if(!canvas._pixiId)
  8884. {
  8885. canvas._pixiId = 'canvas_' + PIXI.TextureCacheIdGenerator++;
  8886. }
  8887. var baseTexture = PIXI.BaseTextureCache[canvas._pixiId];
  8888. if(!baseTexture)
  8889. {
  8890. baseTexture = new PIXI.BaseTexture(canvas, scaleMode);
  8891. PIXI.BaseTextureCache[canvas._pixiId] = baseTexture;
  8892. }
  8893. return baseTexture;
  8894. };
  8895. /**
  8896. * @author Mat Groves http://matgroves.com/ @Doormat23
  8897. */
  8898. PIXI.TextureCache = {};
  8899. PIXI.FrameCache = {};
  8900. PIXI.TextureCacheIdGenerator = 0;
  8901. /**
  8902. * A texture stores the information that represents an image or part of an image. It cannot be added
  8903. * to the display list directly. To do this use PIXI.Sprite. If no frame is provided then the whole image is used
  8904. *
  8905. * @class Texture
  8906. * @uses EventTarget
  8907. * @constructor
  8908. * @param baseTexture {BaseTexture} The base texture source to create the texture from
  8909. * @param frame {Rectangle} The rectangle frame of the texture to show
  8910. */
  8911. PIXI.Texture = function(baseTexture, frame)
  8912. {
  8913. PIXI.EventTarget.call( this );
  8914. /**
  8915. * Does this Texture have any frame data assigned to it?
  8916. *
  8917. * @property noFrame
  8918. * @type Boolean
  8919. */
  8920. this.noFrame = false;
  8921. if (!frame)
  8922. {
  8923. this.noFrame = true;
  8924. frame = new PIXI.Rectangle(0,0,1,1);
  8925. }
  8926. if (baseTexture instanceof PIXI.Texture)
  8927. {
  8928. baseTexture = baseTexture.baseTexture;
  8929. }
  8930. /**
  8931. * The base texture that this texture uses.
  8932. *
  8933. * @property baseTexture
  8934. * @type BaseTexture
  8935. */
  8936. this.baseTexture = baseTexture;
  8937. /**
  8938. * The frame specifies the region of the base texture that this texture uses
  8939. *
  8940. * @property frame
  8941. * @type Rectangle
  8942. */
  8943. this.frame = frame;
  8944. /**
  8945. * The trim point
  8946. *
  8947. * @property trim
  8948. * @type Rectangle
  8949. */
  8950. this.trim = null;
  8951. /**
  8952. * This will let the renderer know if the texture is valid. If its not then it cannot be rendered.
  8953. *
  8954. * @property valid
  8955. * @type Boolean
  8956. */
  8957. this.valid = false;
  8958. /**
  8959. * The context scope under which events are run.
  8960. *
  8961. * @property scope
  8962. * @type Object
  8963. */
  8964. this.scope = this;
  8965. /**
  8966. * The WebGL UV data cache.
  8967. *
  8968. * @private
  8969. * @property _uvs
  8970. * @type Object
  8971. */
  8972. this._uvs = null;
  8973. /**
  8974. * The width of the Texture in pixels.
  8975. *
  8976. * @property width
  8977. * @type Number
  8978. */
  8979. this.width = 0;
  8980. /**
  8981. * The height of the Texture in pixels.
  8982. *
  8983. * @property height
  8984. * @type Number
  8985. */
  8986. this.height = 0;
  8987. /**
  8988. * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering,
  8989. * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases)
  8990. *
  8991. * @property crop
  8992. * @type Rectangle
  8993. */
  8994. this.crop = new PIXI.Rectangle(0, 0, 1, 1);
  8995. if (baseTexture.hasLoaded)
  8996. {
  8997. if (this.noFrame) frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height);
  8998. this.setFrame(frame);
  8999. }
  9000. else
  9001. {
  9002. var scope = this;
  9003. baseTexture.addEventListener('loaded', function(){ scope.onBaseTextureLoaded(); });
  9004. }
  9005. };
  9006. PIXI.Texture.prototype.constructor = PIXI.Texture;
  9007. /**
  9008. * Called when the base texture is loaded
  9009. *
  9010. * @method onBaseTextureLoaded
  9011. * @param event
  9012. * @private
  9013. */
  9014. PIXI.Texture.prototype.onBaseTextureLoaded = function()
  9015. {
  9016. var baseTexture = this.baseTexture;
  9017. baseTexture.removeEventListener('loaded', this.onLoaded);
  9018. if (this.noFrame) this.frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height);
  9019. this.setFrame(this.frame);
  9020. this.scope.dispatchEvent( { type: 'update', content: this } );
  9021. };
  9022. /**
  9023. * Destroys this texture
  9024. *
  9025. * @method destroy
  9026. * @param destroyBase {Boolean} Whether to destroy the base texture as well
  9027. */
  9028. PIXI.Texture.prototype.destroy = function(destroyBase)
  9029. {
  9030. if (destroyBase) this.baseTexture.destroy();
  9031. this.valid = false;
  9032. };
  9033. /**
  9034. * Specifies the region of the baseTexture that this texture will use.
  9035. *
  9036. * @method setFrame
  9037. * @param frame {Rectangle} The frame of the texture to set it to
  9038. */
  9039. PIXI.Texture.prototype.setFrame = function(frame)
  9040. {
  9041. this.noFrame = false;
  9042. this.frame = frame;
  9043. this.width = frame.width;
  9044. this.height = frame.height;
  9045. this.crop.x = frame.x;
  9046. this.crop.y = frame.y;
  9047. this.crop.width = frame.width;
  9048. this.crop.height = frame.height;
  9049. if (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height))
  9050. {
  9051. throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this);
  9052. }
  9053. this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded;
  9054. if (this.trim)
  9055. {
  9056. this.width = this.trim.width;
  9057. this.height = this.trim.height;
  9058. this.frame.width = this.trim.width;
  9059. this.frame.height = this.trim.height;
  9060. }
  9061. if (this.valid) PIXI.Texture.frameUpdates.push(this);
  9062. };
  9063. /**
  9064. * Updates the internal WebGL UV cache.
  9065. *
  9066. * @method _updateWebGLuvs
  9067. * @private
  9068. */
  9069. PIXI.Texture.prototype._updateWebGLuvs = function()
  9070. {
  9071. if(!this._uvs)this._uvs = new PIXI.TextureUvs();
  9072. var frame = this.crop;
  9073. var tw = this.baseTexture.width;
  9074. var th = this.baseTexture.height;
  9075. this._uvs.x0 = frame.x / tw;
  9076. this._uvs.y0 = frame.y / th;
  9077. this._uvs.x1 = (frame.x + frame.width) / tw;
  9078. this._uvs.y1 = frame.y / th;
  9079. this._uvs.x2 = (frame.x + frame.width) / tw;
  9080. this._uvs.y2 = (frame.y + frame.height) / th;
  9081. this._uvs.x3 = frame.x / tw;
  9082. this._uvs.y3 = (frame.y + frame.height) / th;
  9083. };
  9084. /**
  9085. * Helper function that returns a texture based on an image url
  9086. * If the image is not in the texture cache it will be created and loaded
  9087. *
  9088. * @static
  9089. * @method fromImage
  9090. * @param imageUrl {String} The image url of the texture
  9091. * @param crossorigin {Boolean} Whether requests should be treated as crossorigin
  9092. * @param scaleMode {Number} Should be one of the PIXI.scaleMode consts
  9093. * @return Texture
  9094. */
  9095. PIXI.Texture.fromImage = function(imageUrl, crossorigin, scaleMode)
  9096. {
  9097. var texture = PIXI.TextureCache[imageUrl];
  9098. if(!texture)
  9099. {
  9100. texture = new PIXI.Texture(PIXI.BaseTexture.fromImage(imageUrl, crossorigin, scaleMode));
  9101. PIXI.TextureCache[imageUrl] = texture;
  9102. }
  9103. return texture;
  9104. };
  9105. /**
  9106. * Helper function that returns a texture based on a frame id
  9107. * If the frame id is not in the texture cache an error will be thrown
  9108. *
  9109. * @static
  9110. * @method fromFrame
  9111. * @param frameId {String} The frame id of the texture
  9112. * @return Texture
  9113. */
  9114. PIXI.Texture.fromFrame = function(frameId)
  9115. {
  9116. var texture = PIXI.TextureCache[frameId];
  9117. if(!texture) throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ');
  9118. return texture;
  9119. };
  9120. /**
  9121. * Helper function that returns a texture based on a canvas element
  9122. * If the canvas is not in the texture cache it will be created and loaded
  9123. *
  9124. * @static
  9125. * @method fromCanvas
  9126. * @param canvas {Canvas} The canvas element source of the texture
  9127. * @param scaleMode {Number} Should be one of the PIXI.scaleMode consts
  9128. * @return Texture
  9129. */
  9130. PIXI.Texture.fromCanvas = function(canvas, scaleMode)
  9131. {
  9132. var baseTexture = PIXI.BaseTexture.fromCanvas(canvas, scaleMode);
  9133. return new PIXI.Texture( baseTexture );
  9134. };
  9135. /**
  9136. * Adds a texture to the textureCache.
  9137. *
  9138. * @static
  9139. * @method addTextureToCache
  9140. * @param texture {Texture}
  9141. * @param id {String} the id that the texture will be stored against.
  9142. */
  9143. PIXI.Texture.addTextureToCache = function(texture, id)
  9144. {
  9145. PIXI.TextureCache[id] = texture;
  9146. };
  9147. /**
  9148. * Remove a texture from the textureCache.
  9149. *
  9150. * @static
  9151. * @method removeTextureFromCache
  9152. * @param id {String} the id of the texture to be removed
  9153. * @return {Texture} the texture that was removed
  9154. */
  9155. PIXI.Texture.removeTextureFromCache = function(id)
  9156. {
  9157. var texture = PIXI.TextureCache[id];
  9158. delete PIXI.TextureCache[id];
  9159. delete PIXI.BaseTextureCache[id];
  9160. return texture;
  9161. };
  9162. // this is more for webGL.. it contains updated frames..
  9163. PIXI.Texture.frameUpdates = [];
  9164. PIXI.TextureUvs = function()
  9165. {
  9166. this.x0 = 0;
  9167. this.y0 = 0;
  9168. this.x1 = 0;
  9169. this.y1 = 0;
  9170. this.x2 = 0;
  9171. this.y2 = 0;
  9172. this.x3 = 0;
  9173. this.y3 = 0;
  9174. };
  9175. /**
  9176. * @author Mat Groves http://matgroves.com/ @Doormat23
  9177. */
  9178. /**
  9179. A RenderTexture is a special texture that allows any pixi displayObject to be rendered to it.
  9180. __Hint__: All DisplayObjects (exmpl. Sprites) that render on RenderTexture should be preloaded.
  9181. Otherwise black rectangles will be drawn instead.
  9182. RenderTexture takes snapshot of DisplayObject passed to render method. If DisplayObject is passed to render method, position and rotation of it will be ignored. For example:
  9183. var renderTexture = new PIXI.RenderTexture(800, 600);
  9184. var sprite = PIXI.Sprite.fromImage("spinObj_01.png");
  9185. sprite.position.x = 800/2;
  9186. sprite.position.y = 600/2;
  9187. sprite.anchor.x = 0.5;
  9188. sprite.anchor.y = 0.5;
  9189. renderTexture.render(sprite);
  9190. Sprite in this case will be rendered to 0,0 position. To render this sprite at center DisplayObjectContainer should be used:
  9191. var doc = new PIXI.DisplayObjectContainer();
  9192. doc.addChild(sprite);
  9193. renderTexture.render(doc); // Renders to center of renderTexture
  9194. * @class RenderTexture
  9195. * @extends Texture
  9196. * @constructor
  9197. * @param width {Number} The width of the render texture
  9198. * @param height {Number} The height of the render texture
  9199. * @param scaleMode {Number} Should be one of the PIXI.scaleMode consts
  9200. */
  9201. PIXI.RenderTexture = function(width, height, renderer, scaleMode)
  9202. {
  9203. PIXI.EventTarget.call( this );
  9204. /**
  9205. * The with of the render texture
  9206. *
  9207. * @property width
  9208. * @type Number
  9209. */
  9210. this.width = width || 100;
  9211. /**
  9212. * The height of the render texture
  9213. *
  9214. * @property height
  9215. * @type Number
  9216. */
  9217. this.height = height || 100;
  9218. /**
  9219. * The framing rectangle of the render texture
  9220. *
  9221. * @property frame
  9222. * @type Rectangle
  9223. */
  9224. this.frame = new PIXI.Rectangle(0, 0, this.width, this.height);
  9225. /**
  9226. * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering,
  9227. * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases)
  9228. *
  9229. * @property crop
  9230. * @type Rectangle
  9231. */
  9232. this.crop = new PIXI.Rectangle(0, 0, this.width, this.height);
  9233. /**
  9234. * The base texture object that this texture uses
  9235. *
  9236. * @property baseTexture
  9237. * @type BaseTexture
  9238. */
  9239. this.baseTexture = new PIXI.BaseTexture();
  9240. this.baseTexture.width = this.width;
  9241. this.baseTexture.height = this.height;
  9242. this.baseTexture._glTextures = [];
  9243. this.baseTexture.scaleMode = scaleMode || PIXI.scaleModes.DEFAULT;
  9244. this.baseTexture.hasLoaded = true;
  9245. // each render texture can only belong to one renderer at the moment if its webGL
  9246. this.renderer = renderer || PIXI.defaultRenderer;
  9247. if(this.renderer.type === PIXI.WEBGL_RENDERER)
  9248. {
  9249. var gl = this.renderer.gl;
  9250. this.textureBuffer = new PIXI.FilterTexture(gl, this.width, this.height, this.baseTexture.scaleMode);
  9251. this.baseTexture._glTextures[gl.id] = this.textureBuffer.texture;
  9252. this.render = this.renderWebGL;
  9253. this.projection = new PIXI.Point(this.width/2 , -this.height/2);
  9254. }
  9255. else
  9256. {
  9257. this.render = this.renderCanvas;
  9258. this.textureBuffer = new PIXI.CanvasBuffer(this.width, this.height);
  9259. this.baseTexture.source = this.textureBuffer.canvas;
  9260. }
  9261. this.valid = true;
  9262. PIXI.Texture.frameUpdates.push(this);
  9263. };
  9264. PIXI.RenderTexture.prototype = Object.create(PIXI.Texture.prototype);
  9265. PIXI.RenderTexture.prototype.constructor = PIXI.RenderTexture;
  9266. /**
  9267. * Resize the RenderTexture.
  9268. *
  9269. * @method resize
  9270. * @param width {Number} The width to resize to.
  9271. * @param height {Number} The height to resize to.
  9272. * @param updateBase {Boolean} Should the baseTexture.width and height values be resized as well?
  9273. */
  9274. PIXI.RenderTexture.prototype.resize = function(width, height, updateBase)
  9275. {
  9276. if (width === this.width && height === this.height)
  9277. {
  9278. return;
  9279. }
  9280. this.width = this.frame.width = this.crop.width = width;
  9281. this.height = this.frame.height = this.crop.height = height;
  9282. if (updateBase)
  9283. {
  9284. this.baseTexture.width = this.width;
  9285. this.baseTexture.height = this.height;
  9286. }
  9287. if (this.renderer.type === PIXI.WEBGL_RENDERER)
  9288. {
  9289. this.projection.x = this.width / 2;
  9290. this.projection.y = -this.height / 2;
  9291. }
  9292. this.textureBuffer.resize(this.width, this.height);
  9293. };
  9294. /**
  9295. * Clears the RenderTexture.
  9296. *
  9297. * @method clear
  9298. */
  9299. PIXI.RenderTexture.prototype.clear = function()
  9300. {
  9301. if (this.renderer.type === PIXI.WEBGL_RENDERER)
  9302. {
  9303. this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer);
  9304. }
  9305. this.textureBuffer.clear();
  9306. };
  9307. /**
  9308. * This function will draw the display object to the texture.
  9309. *
  9310. * @method renderWebGL
  9311. * @param displayObject {DisplayObject} The display object to render this texture on
  9312. * @param clear {Boolean} If true the texture will be cleared before the displayObject is drawn
  9313. * @private
  9314. */
  9315. PIXI.RenderTexture.prototype.renderWebGL = function(displayObject, position, clear)
  9316. {
  9317. //TOOD replace position with matrix..
  9318. var gl = this.renderer.gl;
  9319. gl.colorMask(true, true, true, true);
  9320. gl.viewport(0, 0, this.width, this.height);
  9321. gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer );
  9322. if(clear)this.textureBuffer.clear();
  9323. // THIS WILL MESS WITH HIT TESTING!
  9324. var children = displayObject.children;
  9325. //TODO -? create a new one??? dont think so!
  9326. var originalWorldTransform = displayObject.worldTransform;
  9327. displayObject.worldTransform = PIXI.RenderTexture.tempMatrix;
  9328. // modify to flip...
  9329. displayObject.worldTransform.d = -1;
  9330. displayObject.worldTransform.ty = this.projection.y * -2;
  9331. if(position)
  9332. {
  9333. displayObject.worldTransform.tx = position.x;
  9334. displayObject.worldTransform.ty -= position.y;
  9335. }
  9336. for(var i=0,j=children.length; i<j; i++)
  9337. {
  9338. children[i].updateTransform();
  9339. }
  9340. // update the textures!
  9341. PIXI.WebGLRenderer.updateTextures();
  9342. this.renderer.spriteBatch.dirty = true;
  9343. this.renderer.renderDisplayObject(displayObject, this.projection, this.textureBuffer.frameBuffer);
  9344. displayObject.worldTransform = originalWorldTransform;
  9345. this.renderer.spriteBatch.dirty = true;
  9346. };
  9347. /**
  9348. * This function will draw the display object to the texture.
  9349. *
  9350. * @method renderCanvas
  9351. * @param displayObject {DisplayObject} The display object to render this texture on
  9352. * @param clear {Boolean} If true the texture will be cleared before the displayObject is drawn
  9353. * @private
  9354. */
  9355. PIXI.RenderTexture.prototype.renderCanvas = function(displayObject, position, clear)
  9356. {
  9357. var children = displayObject.children;
  9358. var originalWorldTransform = displayObject.worldTransform;
  9359. displayObject.worldTransform = PIXI.RenderTexture.tempMatrix;
  9360. if(position)
  9361. {
  9362. displayObject.worldTransform.tx = position.x;
  9363. displayObject.worldTransform.ty = position.y;
  9364. }
  9365. else
  9366. {
  9367. displayObject.worldTransform.tx = 0;
  9368. displayObject.worldTransform.ty = 0;
  9369. }
  9370. for(var i = 0, j = children.length; i < j; i++)
  9371. {
  9372. children[i].updateTransform();
  9373. }
  9374. if(clear)this.textureBuffer.clear();
  9375. var context = this.textureBuffer.context;
  9376. this.renderer.renderDisplayObject(displayObject, context);
  9377. context.setTransform(1,0,0,1,0,0);
  9378. displayObject.worldTransform = originalWorldTransform;
  9379. };
  9380. PIXI.RenderTexture.tempMatrix = new PIXI.Matrix();
  9381. /**
  9382. * @author Mat Groves http://matgroves.com/ @Doormat23
  9383. */
  9384. if (typeof exports !== 'undefined') {
  9385. if (typeof module !== 'undefined' && module.exports) {
  9386. exports = module.exports = PIXI;
  9387. }
  9388. exports.PIXI = PIXI;
  9389. } else if (typeof define !== 'undefined' && define.amd) {
  9390. define('PIXI', (function() { return root.PIXI = PIXI; })() );
  9391. } else {
  9392. root.PIXI = PIXI;
  9393. }
  9394. }).call(this);
  9395. /**
  9396. * @author Richard Davey <rich@photonstorm.com>
  9397. * @copyright 2014 Photon Storm Ltd.
  9398. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  9399. *
  9400. * @overview
  9401. *
  9402. * Phaser - http://phaser.io
  9403. *
  9404. * v2.0.7 "Amadicia" - Built: Fri Jul 18 2014 12:35:30
  9405. *
  9406. * By Richard Davey http://www.photonstorm.com @photonstorm
  9407. *
  9408. * Phaser is a fun, free and fast 2D game framework for making HTML5 games
  9409. * for desktop and mobile web browsers, supporting Canvas and WebGL rendering.
  9410. *
  9411. * Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23
  9412. * Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe
  9413. * Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com
  9414. *
  9415. * Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser
  9416. * and my love of framework development originate.
  9417. *
  9418. * Follow development at http://phaser.io and on our forum
  9419. *
  9420. * "If you want your children to be intelligent, read them fairy tales."
  9421. * "If you want them to be more intelligent, read them more fairy tales."
  9422. * -- Albert Einstein
  9423. */
  9424. /**
  9425. * @author Richard Davey <rich@photonstorm.com>
  9426. * @copyright 2014 Photon Storm Ltd.
  9427. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  9428. */
  9429. (function(){
  9430. var root = this;
  9431. /* global Phaser:true */
  9432. /**
  9433. * @author Richard Davey <rich@photonstorm.com>
  9434. * @copyright 2014 Photon Storm Ltd.
  9435. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  9436. */
  9437. /**
  9438. * @namespace Phaser
  9439. */
  9440. var Phaser = Phaser || {
  9441. VERSION: '2.0.7',
  9442. GAMES: [],
  9443. AUTO: 0,
  9444. CANVAS: 1,
  9445. WEBGL: 2,
  9446. HEADLESS: 3,
  9447. NONE: 0,
  9448. LEFT: 1,
  9449. RIGHT: 2,
  9450. UP: 3,
  9451. DOWN: 4,
  9452. SPRITE: 0,
  9453. BUTTON: 1,
  9454. IMAGE: 2,
  9455. GRAPHICS: 3,
  9456. TEXT: 4,
  9457. TILESPRITE: 5,
  9458. BITMAPTEXT: 6,
  9459. GROUP: 7,
  9460. RENDERTEXTURE: 8,
  9461. TILEMAP: 9,
  9462. TILEMAPLAYER: 10,
  9463. EMITTER: 11,
  9464. POLYGON: 12,
  9465. BITMAPDATA: 13,
  9466. CANVAS_FILTER: 14,
  9467. WEBGL_FILTER: 15,
  9468. ELLIPSE: 16,
  9469. SPRITEBATCH: 17,
  9470. RETROFONT: 18,
  9471. POINTER: 19,
  9472. // The various blend modes supported by pixi / phaser
  9473. blendModes: {
  9474. NORMAL:0,
  9475. ADD:1,
  9476. MULTIPLY:2,
  9477. SCREEN:3,
  9478. OVERLAY:4,
  9479. DARKEN:5,
  9480. LIGHTEN:6,
  9481. COLOR_DODGE:7,
  9482. COLOR_BURN:8,
  9483. HARD_LIGHT:9,
  9484. SOFT_LIGHT:10,
  9485. DIFFERENCE:11,
  9486. EXCLUSION:12,
  9487. HUE:13,
  9488. SATURATION:14,
  9489. COLOR:15,
  9490. LUMINOSITY:16
  9491. },
  9492. // The scale modes
  9493. scaleModes: {
  9494. DEFAULT:0,
  9495. LINEAR:0,
  9496. NEAREST:1
  9497. }
  9498. };
  9499. // We don't need this in Pixi, so we've removed it to save space
  9500. // however the Stage object expects a reference to it, so here is a dummy entry.
  9501. // Ensure that an existing PIXI.InteractionManager is not overriden - in case you're using your own PIXI library.
  9502. PIXI.InteractionManager = PIXI.InteractionManager || function () {};
  9503. // Equally we're going to supress the Pixi console log, with their agreement.
  9504. PIXI.dontSayHello = true;
  9505. /* jshint supernew: true */
  9506. /**
  9507. * @author Richard Davey <rich@photonstorm.com>
  9508. * @copyright 2014 Photon Storm Ltd.
  9509. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  9510. */
  9511. /**
  9512. * @class Phaser.Utils
  9513. * @static
  9514. */
  9515. Phaser.Utils = {
  9516. /**
  9517. * Gets an objects property by string.
  9518. *
  9519. * @method Phaser.Utils.getProperty
  9520. * @param {object} obj - The object to traverse.
  9521. * @param {string} prop - The property whose value will be returned.
  9522. * @return {*} the value of the property or null if property isn't found .
  9523. */
  9524. getProperty: function(obj, prop) {
  9525. var parts = prop.split('.'),
  9526. last = parts.pop(),
  9527. l = parts.length,
  9528. i = 1,
  9529. current = parts[0];
  9530. while (i < l && (obj = obj[current]))
  9531. {
  9532. current = parts[i];
  9533. i++;
  9534. }
  9535. if (obj)
  9536. {
  9537. return obj[last];
  9538. }
  9539. else
  9540. {
  9541. return null;
  9542. }
  9543. },
  9544. /**
  9545. * Sets an objects property by string.
  9546. *
  9547. * @method Phaser.Utils.setProperty
  9548. * @param {object} obj - The object to traverse
  9549. * @param {string} prop - The property whose value will be changed
  9550. * @return {object} The object on which the property was set.
  9551. */
  9552. setProperty: function(obj, prop, value) {
  9553. var parts = prop.split('.'),
  9554. last = parts.pop(),
  9555. l = parts.length,
  9556. i = 1,
  9557. current = parts[0];
  9558. while (i < l && (obj = obj[current]))
  9559. {
  9560. current = parts[i];
  9561. i++;
  9562. }
  9563. if (obj)
  9564. {
  9565. obj[last] = value;
  9566. }
  9567. return obj;
  9568. },
  9569. /**
  9570. * Transposes the elements of the given Array.
  9571. *
  9572. * @method Phaser.Utils.transposeArray
  9573. * @param {array} array - The array to transpose.
  9574. * @return {array} The transposed array.
  9575. */
  9576. transposeArray: function (array) {
  9577. var result = new Array(array[0].length);
  9578. for (var i = 0; i < array[0].length; i++)
  9579. {
  9580. result[i] = new Array(array.length - 1);
  9581. for (var j = array.length - 1; j > -1; j--)
  9582. {
  9583. result[i][j] = array[j][i];
  9584. }
  9585. }
  9586. return result;
  9587. },
  9588. /**
  9589. * Rotates the given array.
  9590. * Based on the routine from http://jsfiddle.net/MrPolywhirl/NH42z/
  9591. *
  9592. * @method Phaser.Utils.rotateArray
  9593. * @param {array} matrix - The array to rotate.
  9594. * @param {number|string} direction - The amount to rotate. Either a number: 90, -90, 270, -270, 180 or a string: 'rotateLeft', 'rotateRight' or 'rotate180'
  9595. * @return {array} The rotated array
  9596. */
  9597. rotateArray: function (matrix, direction) {
  9598. if (typeof direction !== 'string')
  9599. {
  9600. direction = ((direction % 360) + 360) % 360;
  9601. }
  9602. if (direction === 90 || direction === -270 || direction === 'rotateLeft')
  9603. {
  9604. matrix = Phaser.Utils.transposeArray(matrix);
  9605. matrix = matrix.reverse();
  9606. }
  9607. else if (direction === -90 || direction === 270 || direction === 'rotateRight')
  9608. {
  9609. matrix = matrix.reverse();
  9610. matrix = Phaser.Utils.transposeArray(matrix);
  9611. }
  9612. else if (Math.abs(direction) === 180 || direction === 'rotate180')
  9613. {
  9614. for (var i = 0; i < matrix.length; i++)
  9615. {
  9616. matrix[i].reverse();
  9617. }
  9618. matrix = matrix.reverse();
  9619. }
  9620. return matrix;
  9621. },
  9622. /**
  9623. * Get a unit dimension from a string.
  9624. *
  9625. * @method Phaser.Utils.parseDimension
  9626. * @param {string|number} size - The size to parse.
  9627. * @param {number} dimension - The window dimension to check.
  9628. * @return {number} The parsed dimension.
  9629. */
  9630. parseDimension: function (size, dimension) {
  9631. var f = 0;
  9632. var px = 0;
  9633. if (typeof size === 'string')
  9634. {
  9635. // %?
  9636. if (size.substr(-1) === '%')
  9637. {
  9638. f = parseInt(size, 10) / 100;
  9639. if (dimension === 0)
  9640. {
  9641. px = window.innerWidth * f;
  9642. }
  9643. else
  9644. {
  9645. px = window.innerHeight * f;
  9646. }
  9647. }
  9648. else
  9649. {
  9650. px = parseInt(size, 10);
  9651. }
  9652. }
  9653. else
  9654. {
  9655. px = size;
  9656. }
  9657. return px;
  9658. },
  9659. /**
  9660. * A standard Fisher-Yates Array shuffle implementation.
  9661. * @method Phaser.Utils.shuffle
  9662. * @param {array} array - The array to shuffle.
  9663. * @return {array} The shuffled array.
  9664. */
  9665. shuffle: function (array) {
  9666. for (var i = array.length - 1; i > 0; i--)
  9667. {
  9668. var j = Math.floor(Math.random() * (i + 1));
  9669. var temp = array[i];
  9670. array[i] = array[j];
  9671. array[j] = temp;
  9672. }
  9673. return array;
  9674. },
  9675. /**
  9676. * Javascript string pad http://www.webtoolkit.info/.
  9677. * pad = the string to pad it out with (defaults to a space)
  9678. * dir = 1 (left), 2 (right), 3 (both)
  9679. * @method Phaser.Utils.pad
  9680. * @param {string} str - The target string.
  9681. * @param {number} len - The number of characters to be added.
  9682. * @param {number} pad - The string to pad it out with (defaults to a space).
  9683. * @param {number} [dir=3] The direction dir = 1 (left), 2 (right), 3 (both).
  9684. * @return {string} The padded string
  9685. */
  9686. pad: function (str, len, pad, dir) {
  9687. if (typeof(len) == "undefined") { var len = 0; }
  9688. if (typeof(pad) == "undefined") { var pad = ' '; }
  9689. if (typeof(dir) == "undefined") { var dir = 3; }
  9690. var padlen = 0;
  9691. if (len + 1 >= str.length)
  9692. {
  9693. switch (dir)
  9694. {
  9695. case 1:
  9696. str = new Array(len + 1 - str.length).join(pad) + str;
  9697. break;
  9698. case 3:
  9699. var right = Math.ceil((padlen = len - str.length) / 2);
  9700. var left = padlen - right;
  9701. str = new Array(left+1).join(pad) + str + new Array(right+1).join(pad);
  9702. break;
  9703. default:
  9704. str = str + new Array(len + 1 - str.length).join(pad);
  9705. break;
  9706. }
  9707. }
  9708. return str;
  9709. },
  9710. /**
  9711. * This is a slightly modified version of jQuery.isPlainObject. A plain object is an object whose internal class property is [object Object].
  9712. * @method Phaser.Utils.isPlainObject
  9713. * @param {object} obj - The object to inspect.
  9714. * @return {boolean} - true if the object is plain, otherwise false.
  9715. */
  9716. isPlainObject: function (obj) {
  9717. // Not plain objects:
  9718. // - Any object or value whose internal [[Class]] property is not "[object Object]"
  9719. // - DOM nodes
  9720. // - window
  9721. if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window)
  9722. {
  9723. return false;
  9724. }
  9725. // Support: Firefox <20
  9726. // The try/catch suppresses exceptions thrown when attempting to access
  9727. // the "constructor" property of certain host objects, ie. |window.location|
  9728. // https://bugzilla.mozilla.org/show_bug.cgi?id=814622
  9729. try {
  9730. if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf"))
  9731. {
  9732. return false;
  9733. }
  9734. } catch (e) {
  9735. return false;
  9736. }
  9737. // If the function hasn't returned already, we're confident that
  9738. // |obj| is a plain object, created by {} or constructed with new Object
  9739. return true;
  9740. },
  9741. /**
  9742. * This is a slightly modified version of http://api.jquery.com/jQuery.extend/
  9743. * @method Phaser.Utils.extend
  9744. * @param {boolean} deep - Perform a deep copy?
  9745. * @param {object} target - The target object to copy to.
  9746. * @return {object} The extended object.
  9747. */
  9748. extend: function () {
  9749. var options, name, src, copy, copyIsArray, clone,
  9750. target = arguments[0] || {},
  9751. i = 1,
  9752. length = arguments.length,
  9753. deep = false;
  9754. // Handle a deep copy situation
  9755. if (typeof target === "boolean")
  9756. {
  9757. deep = target;
  9758. target = arguments[1] || {};
  9759. // skip the boolean and the target
  9760. i = 2;
  9761. }
  9762. // extend Phaser if only one argument is passed
  9763. if (length === i)
  9764. {
  9765. target = this;
  9766. --i;
  9767. }
  9768. for (; i < length; i++)
  9769. {
  9770. // Only deal with non-null/undefined values
  9771. if ((options = arguments[i]) != null)
  9772. {
  9773. // Extend the base object
  9774. for (name in options)
  9775. {
  9776. src = target[name];
  9777. copy = options[name];
  9778. // Prevent never-ending loop
  9779. if (target === copy)
  9780. {
  9781. continue;
  9782. }
  9783. // Recurse if we're merging plain objects or arrays
  9784. if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy))))
  9785. {
  9786. if (copyIsArray)
  9787. {
  9788. copyIsArray = false;
  9789. clone = src && Array.isArray(src) ? src : [];
  9790. }
  9791. else
  9792. {
  9793. clone = src && Phaser.Utils.isPlainObject(src) ? src : {};
  9794. }
  9795. // Never move original objects, clone them
  9796. target[name] = Phaser.Utils.extend(deep, clone, copy);
  9797. // Don't bring in undefined values
  9798. }
  9799. else if (copy !== undefined)
  9800. {
  9801. target[name] = copy;
  9802. }
  9803. }
  9804. }
  9805. }
  9806. // Return the modified object
  9807. return target;
  9808. },
  9809. /**
  9810. * Mixes the source object into the destination object, returning the newly modified destination object.
  9811. * Based on original code by @mudcube
  9812. *
  9813. * @method Phaser.Utils.mixin
  9814. * @param {object} from - The object to copy (the source object).
  9815. * @param {object} to - The object to copy to (the destination object).
  9816. * @return {object} The modified destination object.
  9817. */
  9818. mixin: function (from, to) {
  9819. if (!from || typeof (from) !== "object")
  9820. {
  9821. return to;
  9822. }
  9823. for (var key in from)
  9824. {
  9825. var o = from[key];
  9826. if (o.childNodes || o.cloneNode)
  9827. {
  9828. continue;
  9829. }
  9830. var type = typeof (from[key]);
  9831. if (!from[key] || type !== "object")
  9832. {
  9833. to[key] = from[key];
  9834. }
  9835. else
  9836. {
  9837. // Clone sub-object
  9838. if (typeof (to[key]) === type)
  9839. {
  9840. to[key] = Phaser.Utils.mixin(from[key], to[key]);
  9841. }
  9842. else
  9843. {
  9844. to[key] = Phaser.Utils.mixin(from[key], new o.constructor());
  9845. }
  9846. }
  9847. }
  9848. return to;
  9849. }
  9850. };
  9851. /**
  9852. * A polyfill for Function.prototype.bind
  9853. */
  9854. if (typeof Function.prototype.bind != 'function') {
  9855. /* jshint freeze: false */
  9856. Function.prototype.bind = (function () {
  9857. var slice = Array.prototype.slice;
  9858. return function (thisArg) {
  9859. var target = this, boundArgs = slice.call(arguments, 1);
  9860. if (typeof target != 'function')
  9861. {
  9862. throw new TypeError();
  9863. }
  9864. function bound() {
  9865. var args = boundArgs.concat(slice.call(arguments));
  9866. target.apply(this instanceof bound ? this : thisArg, args);
  9867. }
  9868. bound.prototype = (function F(proto) {
  9869. if (proto)
  9870. {
  9871. F.prototype = proto;
  9872. }
  9873. if (!(this instanceof F))
  9874. {
  9875. return new F;
  9876. }
  9877. })(target.prototype);
  9878. return bound;
  9879. };
  9880. })();
  9881. }
  9882. /**
  9883. * A polyfill for Array.isArray
  9884. */
  9885. if (!Array.isArray)
  9886. {
  9887. Array.isArray = function (arg)
  9888. {
  9889. return Object.prototype.toString.call(arg) == '[object Array]';
  9890. };
  9891. }
  9892. /**
  9893. * A polyfill for Array.forEach
  9894. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
  9895. */
  9896. if (!Array.prototype.forEach)
  9897. {
  9898. Array.prototype.forEach = function(fun /*, thisArg */)
  9899. {
  9900. "use strict";
  9901. if (this === void 0 || this === null)
  9902. {
  9903. throw new TypeError();
  9904. }
  9905. var t = Object(this);
  9906. var len = t.length >>> 0;
  9907. if (typeof fun !== "function")
  9908. {
  9909. throw new TypeError();
  9910. }
  9911. var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
  9912. for (var i = 0; i < len; i++)
  9913. {
  9914. if (i in t)
  9915. {
  9916. fun.call(thisArg, t[i], i, t);
  9917. }
  9918. }
  9919. };
  9920. }
  9921. /**
  9922. * Low-budget Float32Array knock-off, suitable for use with P2.js in IE9
  9923. * Source: http://www.html5gamedevs.com/topic/5988-phaser-12-ie9/
  9924. * Cameron Foale (http://www.kibibu.com)
  9925. */
  9926. if (typeof window.Uint32Array !== "function")
  9927. {
  9928. var CheapArray = function(type)
  9929. {
  9930. var proto = new Array(); // jshint ignore:line
  9931. window[type] = function(arg) {
  9932. if (typeof(arg) === "number")
  9933. {
  9934. Array.call(this, arg);
  9935. this.length = arg;
  9936. for (var i = 0; i < this.length; i++)
  9937. {
  9938. this[i] = 0;
  9939. }
  9940. }
  9941. else
  9942. {
  9943. Array.call(this, arg.length);
  9944. this.length = arg.length;
  9945. for (var i = 0; i < this.length; i++)
  9946. {
  9947. this[i] = arg[i];
  9948. }
  9949. }
  9950. };
  9951. window[type].prototype = proto;
  9952. window[type].constructor = window[type];
  9953. };
  9954. CheapArray('Uint32Array'); // jshint ignore:line
  9955. CheapArray('Int16Array'); // jshint ignore:line
  9956. }
  9957. /**
  9958. * Also fix for the absent console in IE9
  9959. */
  9960. if (!window.console)
  9961. {
  9962. window.console = {};
  9963. window.console.log = window.console.assert = function(){};
  9964. window.console.warn = window.console.assert = function(){};
  9965. }
  9966. /**
  9967. * @author Richard Davey <rich@photonstorm.com>
  9968. * @copyright 2014 Photon Storm Ltd.
  9969. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  9970. */
  9971. /**
  9972. * Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created.
  9973. * @class Circle
  9974. * @classdesc Phaser - Circle
  9975. * @constructor
  9976. * @param {number} [x=0] - The x coordinate of the center of the circle.
  9977. * @param {number} [y=0] - The y coordinate of the center of the circle.
  9978. * @param {number} [diameter=0] - The diameter of the circle.
  9979. * @return {Phaser.Circle} This circle object
  9980. */
  9981. Phaser.Circle = function (x, y, diameter) {
  9982. x = x || 0;
  9983. y = y || 0;
  9984. diameter = diameter || 0;
  9985. /**
  9986. * @property {number} x - The x coordinate of the center of the circle.
  9987. */
  9988. this.x = x;
  9989. /**
  9990. * @property {number} y - The y coordinate of the center of the circle.
  9991. */
  9992. this.y = y;
  9993. /**
  9994. * @property {number} _diameter - The diameter of the circle.
  9995. * @private
  9996. */
  9997. this._diameter = diameter;
  9998. if (diameter > 0)
  9999. {
  10000. /**
  10001. * @property {number} _radius - The radius of the circle.
  10002. * @private
  10003. */
  10004. this._radius = diameter * 0.5;
  10005. }
  10006. else
  10007. {
  10008. this._radius = 0;
  10009. }
  10010. };
  10011. Phaser.Circle.prototype = {
  10012. /**
  10013. * The circumference of the circle.
  10014. * @method Phaser.Circle#circumference
  10015. * @return {number}
  10016. */
  10017. circumference: function () {
  10018. return 2 * (Math.PI * this._radius);
  10019. },
  10020. /**
  10021. * Sets the members of Circle to the specified values.
  10022. * @method Phaser.Circle#setTo
  10023. * @param {number} x - The x coordinate of the center of the circle.
  10024. * @param {number} y - The y coordinate of the center of the circle.
  10025. * @param {number} diameter - The diameter of the circle in pixels.
  10026. * @return {Circle} This circle object.
  10027. */
  10028. setTo: function (x, y, diameter) {
  10029. this.x = x;
  10030. this.y = y;
  10031. this._diameter = diameter;
  10032. this._radius = diameter * 0.5;
  10033. return this;
  10034. },
  10035. /**
  10036. * Copies the x, y and diameter properties from any given object to this Circle.
  10037. * @method Phaser.Circle#copyFrom
  10038. * @param {any} source - The object to copy from.
  10039. * @return {Circle} This Circle object.
  10040. */
  10041. copyFrom: function (source) {
  10042. return this.setTo(source.x, source.y, source.diameter);
  10043. },
  10044. /**
  10045. * Copies the x, y and diameter properties from this Circle to any given object.
  10046. * @method Phaser.Circle#copyTo
  10047. * @param {any} dest - The object to copy to.
  10048. * @return {Object} This dest object.
  10049. */
  10050. copyTo: function (dest) {
  10051. dest.x = this.x;
  10052. dest.y = this.y;
  10053. dest.diameter = this._diameter;
  10054. return dest;
  10055. },
  10056. /**
  10057. * Returns the distance from the center of the Circle object to the given object
  10058. * (can be Circle, Point or anything with x/y properties)
  10059. * @method Phaser.Circle#distance
  10060. * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object.
  10061. * @param {boolean} [round] - Round the distance to the nearest integer (default false).
  10062. * @return {number} The distance between this Point object and the destination Point object.
  10063. */
  10064. distance: function (dest, round) {
  10065. if (typeof round === "undefined") { round = false; }
  10066. if (round)
  10067. {
  10068. return Phaser.Math.distanceRounded(this.x, this.y, dest.x, dest.y);
  10069. }
  10070. else
  10071. {
  10072. return Phaser.Math.distance(this.x, this.y, dest.x, dest.y);
  10073. }
  10074. },
  10075. /**
  10076. * Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object.
  10077. * @method Phaser.Circle#clone
  10078. * @param {Phaser.Circle} out - Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned.
  10079. * @return {Phaser.Circle} The cloned Circle object.
  10080. */
  10081. clone: function (out) {
  10082. if (typeof out === "undefined")
  10083. {
  10084. out = new Phaser.Circle(this.x, this.y, this.diameter);
  10085. }
  10086. else
  10087. {
  10088. out.setTo(this.x, this.y, this.diameter);
  10089. }
  10090. return out;
  10091. },
  10092. /**
  10093. * Return true if the given x/y coordinates are within this Circle object.
  10094. * @method Phaser.Circle#contains
  10095. * @param {number} x - The X value of the coordinate to test.
  10096. * @param {number} y - The Y value of the coordinate to test.
  10097. * @return {boolean} True if the coordinates are within this circle, otherwise false.
  10098. */
  10099. contains: function (x, y) {
  10100. return Phaser.Circle.contains(this, x, y);
  10101. },
  10102. /**
  10103. * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle.
  10104. * @method Phaser.Circle#circumferencePoint
  10105. * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from.
  10106. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
  10107. * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created.
  10108. * @return {Phaser.Point} The Point object holding the result.
  10109. */
  10110. circumferencePoint: function (angle, asDegrees, out) {
  10111. return Phaser.Circle.circumferencePoint(this, angle, asDegrees, out);
  10112. },
  10113. /**
  10114. * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts.
  10115. * @method Phaser.Circle#offset
  10116. * @param {number} dx - Moves the x value of the Circle object by this amount.
  10117. * @param {number} dy - Moves the y value of the Circle object by this amount.
  10118. * @return {Circle} This Circle object.
  10119. */
  10120. offset: function (dx, dy) {
  10121. this.x += dx;
  10122. this.y += dy;
  10123. return this;
  10124. },
  10125. /**
  10126. * 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.
  10127. * @method Phaser.Circle#offsetPoint
  10128. * @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties).
  10129. * @return {Circle} This Circle object.
  10130. */
  10131. offsetPoint: function (point) {
  10132. return this.offset(point.x, point.y);
  10133. },
  10134. /**
  10135. * Returns a string representation of this object.
  10136. * @method Phaser.Circle#toString
  10137. * @return {string} a string representation of the instance.
  10138. */
  10139. toString: function () {
  10140. return "[{Phaser.Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]";
  10141. }
  10142. };
  10143. Phaser.Circle.prototype.constructor = Phaser.Circle;
  10144. /**
  10145. * The largest distance between any two points on the circle. The same as the radius * 2.
  10146. * @name Phaser.Circle#diameter
  10147. * @property {number} diameter - Gets or sets the diameter of the circle.
  10148. */
  10149. Object.defineProperty(Phaser.Circle.prototype, "diameter", {
  10150. get: function () {
  10151. return this._diameter;
  10152. },
  10153. set: function (value) {
  10154. if (value > 0)
  10155. {
  10156. this._diameter = value;
  10157. this._radius = value * 0.5;
  10158. }
  10159. }
  10160. });
  10161. /**
  10162. * 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.
  10163. * @name Phaser.Circle#radius
  10164. * @property {number} radius - Gets or sets the radius of the circle.
  10165. */
  10166. Object.defineProperty(Phaser.Circle.prototype, "radius", {
  10167. get: function () {
  10168. return this._radius;
  10169. },
  10170. set: function (value) {
  10171. if (value > 0)
  10172. {
  10173. this._radius = value;
  10174. this._diameter = value * 2;
  10175. }
  10176. }
  10177. });
  10178. /**
  10179. * 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.
  10180. * @name Phaser.Circle#left
  10181. * @propety {number} left - Gets or sets the value of the leftmost point of the circle.
  10182. */
  10183. Object.defineProperty(Phaser.Circle.prototype, "left", {
  10184. get: function () {
  10185. return this.x - this._radius;
  10186. },
  10187. set: function (value) {
  10188. if (value > this.x)
  10189. {
  10190. this._radius = 0;
  10191. this._diameter = 0;
  10192. }
  10193. else
  10194. {
  10195. this.radius = this.x - value;
  10196. }
  10197. }
  10198. });
  10199. /**
  10200. * 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.
  10201. * @name Phaser.Circle#right
  10202. * @property {number} right - Gets or sets the value of the rightmost point of the circle.
  10203. */
  10204. Object.defineProperty(Phaser.Circle.prototype, "right", {
  10205. get: function () {
  10206. return this.x + this._radius;
  10207. },
  10208. set: function (value) {
  10209. if (value < this.x)
  10210. {
  10211. this._radius = 0;
  10212. this._diameter = 0;
  10213. }
  10214. else
  10215. {
  10216. this.radius = value - this.x;
  10217. }
  10218. }
  10219. });
  10220. /**
  10221. * 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.
  10222. * @name Phaser.Circle#top
  10223. * @property {number} top - Gets or sets the top of the circle.
  10224. */
  10225. Object.defineProperty(Phaser.Circle.prototype, "top", {
  10226. get: function () {
  10227. return this.y - this._radius;
  10228. },
  10229. set: function (value) {
  10230. if (value > this.y)
  10231. {
  10232. this._radius = 0;
  10233. this._diameter = 0;
  10234. }
  10235. else
  10236. {
  10237. this.radius = this.y - value;
  10238. }
  10239. }
  10240. });
  10241. /**
  10242. * 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.
  10243. * @name Phaser.Circle#bottom
  10244. * @property {number} bottom - Gets or sets the bottom of the circle.
  10245. */
  10246. Object.defineProperty(Phaser.Circle.prototype, "bottom", {
  10247. get: function () {
  10248. return this.y + this._radius;
  10249. },
  10250. set: function (value) {
  10251. if (value < this.y)
  10252. {
  10253. this._radius = 0;
  10254. this._diameter = 0;
  10255. }
  10256. else
  10257. {
  10258. this.radius = value - this.y;
  10259. }
  10260. }
  10261. });
  10262. /**
  10263. * The area of this Circle.
  10264. * @name Phaser.Circle#area
  10265. * @property {number} area - The area of this circle.
  10266. * @readonly
  10267. */
  10268. Object.defineProperty(Phaser.Circle.prototype, "area", {
  10269. get: function () {
  10270. if (this._radius > 0)
  10271. {
  10272. return Math.PI * this._radius * this._radius;
  10273. }
  10274. else
  10275. {
  10276. return 0;
  10277. }
  10278. }
  10279. });
  10280. /**
  10281. * 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.
  10282. * 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.
  10283. * @name Phaser.Circle#empty
  10284. * @property {boolean} empty - Gets or sets the empty state of the circle.
  10285. */
  10286. Object.defineProperty(Phaser.Circle.prototype, "empty", {
  10287. get: function () {
  10288. return (this._diameter === 0);
  10289. },
  10290. set: function (value) {
  10291. if (value === true)
  10292. {
  10293. this.setTo(0, 0, 0);
  10294. }
  10295. }
  10296. });
  10297. /**
  10298. * Return true if the given x/y coordinates are within the Circle object.
  10299. * @method Phaser.Circle.contains
  10300. * @param {Phaser.Circle} a - The Circle to be checked.
  10301. * @param {number} x - The X value of the coordinate to test.
  10302. * @param {number} y - The Y value of the coordinate to test.
  10303. * @return {boolean} True if the coordinates are within this circle, otherwise false.
  10304. */
  10305. Phaser.Circle.contains = function (a, x, y) {
  10306. // Check if x/y are within the bounds first
  10307. if (a.radius > 0 && x >= a.left && x <= a.right && y >= a.top && y <= a.bottom)
  10308. {
  10309. var dx = (a.x - x) * (a.x - x);
  10310. var dy = (a.y - y) * (a.y - y);
  10311. return (dx + dy) <= (a.radius * a.radius);
  10312. }
  10313. else
  10314. {
  10315. return false;
  10316. }
  10317. };
  10318. /**
  10319. * Determines whether the two Circle objects match. This method compares the x, y and diameter properties.
  10320. * @method Phaser.Circle.equals
  10321. * @param {Phaser.Circle} a - The first Circle object.
  10322. * @param {Phaser.Circle} b - The second Circle object.
  10323. * @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.
  10324. */
  10325. Phaser.Circle.equals = function (a, b) {
  10326. return (a.x == b.x && a.y == b.y && a.diameter == b.diameter);
  10327. };
  10328. /**
  10329. * Determines whether the two Circle objects intersect.
  10330. * This method checks the radius distances between the two Circle objects to see if they intersect.
  10331. * @method Phaser.Circle.intersects
  10332. * @param {Phaser.Circle} a - The first Circle object.
  10333. * @param {Phaser.Circle} b - The second Circle object.
  10334. * @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false.
  10335. */
  10336. Phaser.Circle.intersects = function (a, b) {
  10337. return (Phaser.Math.distance(a.x, a.y, b.x, b.y) <= (a.radius + b.radius));
  10338. };
  10339. /**
  10340. * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle.
  10341. * @method Phaser.Circle.circumferencePoint
  10342. * @param {Phaser.Circle} a - The first Circle object.
  10343. * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from.
  10344. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
  10345. * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created.
  10346. * @return {Phaser.Point} The Point object holding the result.
  10347. */
  10348. Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) {
  10349. if (typeof asDegrees === "undefined") { asDegrees = false; }
  10350. if (typeof out === "undefined") { out = new Phaser.Point(); }
  10351. if (asDegrees === true)
  10352. {
  10353. angle = Phaser.Math.degToRad(angle);
  10354. }
  10355. out.x = a.x + a.radius * Math.cos(angle);
  10356. out.y = a.y + a.radius * Math.sin(angle);
  10357. return out;
  10358. };
  10359. /**
  10360. * Checks if the given Circle and Rectangle objects intersect.
  10361. * @method Phaser.Circle.intersectsRectangle
  10362. * @param {Phaser.Circle} c - The Circle object to test.
  10363. * @param {Phaser.Rectangle} r - The Rectangle object to test.
  10364. * @return {boolean} True if the two objects intersect, otherwise false.
  10365. */
  10366. Phaser.Circle.intersectsRectangle = function (c, r) {
  10367. var cx = Math.abs(c.x - r.x - r.halfWidth);
  10368. var xDist = r.halfWidth + c.radius;
  10369. if (cx > xDist)
  10370. {
  10371. return false;
  10372. }
  10373. var cy = Math.abs(c.y - r.y - r.halfHeight);
  10374. var yDist = r.halfHeight + c.radius;
  10375. if (cy > yDist)
  10376. {
  10377. return false;
  10378. }
  10379. if (cx <= r.halfWidth || cy <= r.halfHeight)
  10380. {
  10381. return true;
  10382. }
  10383. var xCornerDist = cx - r.halfWidth;
  10384. var yCornerDist = cy - r.halfHeight;
  10385. var xCornerDistSq = xCornerDist * xCornerDist;
  10386. var yCornerDistSq = yCornerDist * yCornerDist;
  10387. var maxCornerDistSq = c.radius * c.radius;
  10388. return xCornerDistSq + yCornerDistSq <= maxCornerDistSq;
  10389. };
  10390. // Because PIXI uses its own Circle, we'll replace it with ours to avoid duplicating code or confusion.
  10391. PIXI.Circle = Phaser.Circle;
  10392. /**
  10393. * @author Richard Davey <rich@photonstorm.com>
  10394. * @copyright 2014 Photon Storm Ltd.
  10395. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  10396. */
  10397. /**
  10398. * @class Phaser.Point
  10399. * @classdesc
  10400. * The Point object represents a location in a two-dimensional coordinate system,
  10401. * where x represents the horizontal axis and y represents the vertical axis.
  10402. * The following code creates a point at (0,0):
  10403. * `var myPoint = new Phaser.Point();`
  10404. * You can also use them as 2D Vectors and you'll find different vector related methods in this class.
  10405. */
  10406. /**
  10407. * Creates a new Point object. If you pass no parameters a Point is created set to (0, 0).
  10408. *
  10409. * @constructor
  10410. * @param {number} [x=0] - The horizontal position of this Point.
  10411. * @param {number} [y=0] - The vertical position of this Point.
  10412. */
  10413. Phaser.Point = function (x, y) {
  10414. x = x || 0;
  10415. y = y || 0;
  10416. /**
  10417. * @property {number} x - The x value of the point.
  10418. */
  10419. this.x = x;
  10420. /**
  10421. * @property {number} y - The y value of the point.
  10422. */
  10423. this.y = y;
  10424. };
  10425. Phaser.Point.prototype = {
  10426. /**
  10427. * Copies the x and y properties from any given object to this Point.
  10428. *
  10429. * @method Phaser.Point#copyFrom
  10430. * @param {any} source - The object to copy from.
  10431. * @return {Phaser.Point} This Point object.
  10432. */
  10433. copyFrom: function (source) {
  10434. return this.setTo(source.x, source.y);
  10435. },
  10436. /**
  10437. * Inverts the x and y values of this Point
  10438. *
  10439. * @method Phaser.Point#invert
  10440. * @return {Phaser.Point} This Point object.
  10441. */
  10442. invert: function () {
  10443. return this.setTo(this.y, this.x);
  10444. },
  10445. /**
  10446. * Sets the `x` and `y` values of this Point object to the given values.
  10447. * If you omit the `y` value then the `x` value will be applied to both, for example:
  10448. * `Point.setTo(2)` is the same as `Point.setTo(2, 2)`
  10449. *
  10450. * @method Phaser.Point#setTo
  10451. * @param {number} x - The horizontal value of this point.
  10452. * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place.
  10453. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  10454. */
  10455. setTo: function (x, y) {
  10456. this.x = x || 0;
  10457. this.y = y || ( (y !== 0) ? this.x : 0 );
  10458. return this;
  10459. },
  10460. /**
  10461. * Sets the `x` and `y` values of this Point object to the given values.
  10462. * If you omit the `y` value then the `x` value will be applied to both, for example:
  10463. * `Point.setTo(2)` is the same as `Point.setTo(2, 2)`
  10464. *
  10465. * @method Phaser.Point#set
  10466. * @param {number} x - The horizontal value of this point.
  10467. * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place.
  10468. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  10469. */
  10470. set: function (x, y) {
  10471. this.x = x || 0;
  10472. this.y = y || ( (y !== 0) ? this.x : 0 );
  10473. return this;
  10474. },
  10475. /**
  10476. * Adds the given x and y values to this Point.
  10477. *
  10478. * @method Phaser.Point#add
  10479. * @param {number} x - The value to add to Point.x.
  10480. * @param {number} y - The value to add to Point.y.
  10481. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  10482. */
  10483. add: function (x, y) {
  10484. this.x += x;
  10485. this.y += y;
  10486. return this;
  10487. },
  10488. /**
  10489. * Subtracts the given x and y values from this Point.
  10490. *
  10491. * @method Phaser.Point#subtract
  10492. * @param {number} x - The value to subtract from Point.x.
  10493. * @param {number} y - The value to subtract from Point.y.
  10494. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  10495. */
  10496. subtract: function (x, y) {
  10497. this.x -= x;
  10498. this.y -= y;
  10499. return this;
  10500. },
  10501. /**
  10502. * Multiplies Point.x and Point.y by the given x and y values. Sometimes known as `Scale`.
  10503. *
  10504. * @method Phaser.Point#multiply
  10505. * @param {number} x - The value to multiply Point.x by.
  10506. * @param {number} y - The value to multiply Point.x by.
  10507. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  10508. */
  10509. multiply: function (x, y) {
  10510. this.x *= x;
  10511. this.y *= y;
  10512. return this;
  10513. },
  10514. /**
  10515. * Divides Point.x and Point.y by the given x and y values.
  10516. *
  10517. * @method Phaser.Point#divide
  10518. * @param {number} x - The value to divide Point.x by.
  10519. * @param {number} y - The value to divide Point.x by.
  10520. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  10521. */
  10522. divide: function (x, y) {
  10523. this.x /= x;
  10524. this.y /= y;
  10525. return this;
  10526. },
  10527. /**
  10528. * Clamps the x value of this Point to be between the given min and max.
  10529. *
  10530. * @method Phaser.Point#clampX
  10531. * @param {number} min - The minimum value to clamp this Point to.
  10532. * @param {number} max - The maximum value to clamp this Point to.
  10533. * @return {Phaser.Point} This Point object.
  10534. */
  10535. clampX: function (min, max) {
  10536. this.x = Phaser.Math.clamp(this.x, min, max);
  10537. return this;
  10538. },
  10539. /**
  10540. * Clamps the y value of this Point to be between the given min and max
  10541. *
  10542. * @method Phaser.Point#clampY
  10543. * @param {number} min - The minimum value to clamp this Point to.
  10544. * @param {number} max - The maximum value to clamp this Point to.
  10545. * @return {Phaser.Point} This Point object.
  10546. */
  10547. clampY: function (min, max) {
  10548. this.y = Phaser.Math.clamp(this.y, min, max);
  10549. return this;
  10550. },
  10551. /**
  10552. * Clamps this Point object values to be between the given min and max.
  10553. *
  10554. * @method Phaser.Point#clamp
  10555. * @param {number} min - The minimum value to clamp this Point to.
  10556. * @param {number} max - The maximum value to clamp this Point to.
  10557. * @return {Phaser.Point} This Point object.
  10558. */
  10559. clamp: function (min, max) {
  10560. this.x = Phaser.Math.clamp(this.x, min, max);
  10561. this.y = Phaser.Math.clamp(this.y, min, max);
  10562. return this;
  10563. },
  10564. /**
  10565. * Creates a copy of the given Point.
  10566. *
  10567. * @method Phaser.Point#clone
  10568. * @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.
  10569. * @return {Phaser.Point} The new Point object.
  10570. */
  10571. clone: function (output) {
  10572. if (typeof output === "undefined")
  10573. {
  10574. output = new Phaser.Point(this.x, this.y);
  10575. }
  10576. else
  10577. {
  10578. output.setTo(this.x, this.y);
  10579. }
  10580. return output;
  10581. },
  10582. /**
  10583. * Copies the x and y properties from this Point to any given object.
  10584. *
  10585. * @method Phaser.Point#copyTo
  10586. * @param {any} dest - The object to copy to.
  10587. * @return {Object} The dest object.
  10588. */
  10589. copyTo: function (dest) {
  10590. dest.x = this.x;
  10591. dest.y = this.y;
  10592. return dest;
  10593. },
  10594. /**
  10595. * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties)
  10596. *
  10597. * @method Phaser.Point#distance
  10598. * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object.
  10599. * @param {boolean} [round] - Round the distance to the nearest integer (default false).
  10600. * @return {number} The distance between this Point object and the destination Point object.
  10601. */
  10602. distance: function (dest, round) {
  10603. return Phaser.Point.distance(this, dest, round);
  10604. },
  10605. /**
  10606. * Determines whether the given objects x/y values are equal to this Point object.
  10607. *
  10608. * @method Phaser.Point#equals
  10609. * @param {Phaser.Point|any} a - The object to compare with this Point.
  10610. * @return {boolean} A value of true if the x and y points are equal, otherwise false.
  10611. */
  10612. equals: function (a) {
  10613. return (a.x === this.x && a.y === this.y);
  10614. },
  10615. /**
  10616. * Returns the angle between this Point object and another object with public x and y properties.
  10617. *
  10618. * @method Phaser.Point#angle
  10619. * @param {Phaser.Point|any} a - The object to get the angle from this Point to.
  10620. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
  10621. * @return {number} The angle between the two objects.
  10622. */
  10623. angle: function (a, asDegrees) {
  10624. if (typeof asDegrees === 'undefined') { asDegrees = false; }
  10625. if (asDegrees)
  10626. {
  10627. return Phaser.Math.radToDeg(Math.atan2(a.y - this.y, a.x - this.x));
  10628. }
  10629. else
  10630. {
  10631. return Math.atan2(a.y - this.y, a.x - this.x);
  10632. }
  10633. },
  10634. /**
  10635. * Returns the angle squared between this Point object and another object with public x and y properties.
  10636. *
  10637. * @method Phaser.Point#angleSq
  10638. * @param {Phaser.Point|any} a - The object to get the angleSq from this Point to.
  10639. * @return {number} The angleSq between the two objects.
  10640. */
  10641. angleSq: function (a) {
  10642. return this.subtract(a).angle(a.subtract(this));
  10643. },
  10644. /**
  10645. * Rotates this Point around the x/y coordinates given to the desired angle.
  10646. *
  10647. * @method Phaser.Point#rotate
  10648. * @param {number} x - The x coordinate of the anchor point.
  10649. * @param {number} y - The y coordinate of the anchor point.
  10650. * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to.
  10651. * @param {boolean} asDegrees - Is the given rotation in radians (false) or degrees (true)?
  10652. * @param {number} [distance] - An optional distance constraint between the Point and the anchor.
  10653. * @return {Phaser.Point} The modified point object.
  10654. */
  10655. rotate: function (x, y, angle, asDegrees, distance) {
  10656. return Phaser.Point.rotate(this, x, y, angle, asDegrees, distance);
  10657. },
  10658. /**
  10659. * Calculates the length of the Point object.
  10660. *
  10661. * @method Phaser.Point#getMagnitude
  10662. * @return {number} The length of the Point.
  10663. */
  10664. getMagnitude: function () {
  10665. return Math.sqrt((this.x * this.x) + (this.y * this.y));
  10666. },
  10667. /**
  10668. * Calculates the length squared of the Point object.
  10669. *
  10670. * @method Phaser.Point#getMagnitudeSq
  10671. * @return {number} The length ^ 2 of the Point.
  10672. */
  10673. getMagnitudeSq: function () {
  10674. return (this.x * this.x) + (this.y * this.y);
  10675. },
  10676. /**
  10677. * Alters the length of the Point without changing the direction.
  10678. *
  10679. * @method Phaser.Point#setMagnitude
  10680. * @param {number} magnitude - The desired magnitude of the resulting Point.
  10681. * @return {Phaser.Point} This Point object.
  10682. */
  10683. setMagnitude: function (magnitude) {
  10684. return this.normalize().multiply(magnitude, magnitude);
  10685. },
  10686. /**
  10687. * Alters the Point object so that its length is 1, but it retains the same direction.
  10688. *
  10689. * @method Phaser.Point#normalize
  10690. * @return {Phaser.Point} This Point object.
  10691. */
  10692. normalize: function () {
  10693. if (!this.isZero())
  10694. {
  10695. var m = this.getMagnitude();
  10696. this.x /= m;
  10697. this.y /= m;
  10698. }
  10699. return this;
  10700. },
  10701. /**
  10702. * Determine if this point is at 0,0.
  10703. *
  10704. * @method Phaser.Point#isZero
  10705. * @return {boolean} True if this Point is 0,0, otherwise false.
  10706. */
  10707. isZero: function () {
  10708. return (this.x === 0 && this.y === 0);
  10709. },
  10710. /**
  10711. * The dot product of this and another Point object.
  10712. *
  10713. * @method Phaser.Point#dot
  10714. * @param {Phaser.Point} a - The Point object to get the dot product combined with this Point.
  10715. * @return {number} The result.
  10716. */
  10717. dot: function (a) {
  10718. return ((this.x * a.x) + (this.y * a.y));
  10719. },
  10720. /**
  10721. * The cross product of this and another Point object.
  10722. *
  10723. * @method Phaser.Point#cross
  10724. * @param {Phaser.Point} a - The Point object to get the cross product combined with this Point.
  10725. * @return {number} The result.
  10726. */
  10727. cross: function (a) {
  10728. return ((this.x * a.y) - (this.y * a.x));
  10729. },
  10730. /**
  10731. * Make this Point perpendicular (90 degrees rotation)
  10732. *
  10733. * @method Phaser.Point#perp
  10734. * @return {Phaser.Point} This Point object.
  10735. */
  10736. perp: function () {
  10737. return this.setTo(-this.y, this.x);
  10738. },
  10739. /**
  10740. * Make this Point perpendicular (-90 degrees rotation)
  10741. *
  10742. * @method Phaser.Point#rperp
  10743. * @return {Phaser.Point} This Point object.
  10744. */
  10745. rperp: function () {
  10746. return this.setTo(this.y, -this.x);
  10747. },
  10748. /**
  10749. * Right-hand normalize (make unit length) this Point.
  10750. *
  10751. * @method Phaser.Point#normalRightHand
  10752. * @return {Phaser.Point} This Point object.
  10753. */
  10754. normalRightHand: function () {
  10755. return this.setTo(this.y * -1, this.x);
  10756. },
  10757. /**
  10758. * Returns a string representation of this object.
  10759. *
  10760. * @method Phaser.Point#toString
  10761. * @return {string} A string representation of the instance.
  10762. */
  10763. toString: function () {
  10764. return '[{Point (x=' + this.x + ' y=' + this.y + ')}]';
  10765. }
  10766. };
  10767. Phaser.Point.prototype.constructor = Phaser.Point;
  10768. /**
  10769. * Adds the coordinates of two points together to create a new point.
  10770. *
  10771. * @method Phaser.Point.add
  10772. * @param {Phaser.Point} a - The first Point object.
  10773. * @param {Phaser.Point} b - The second Point object.
  10774. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  10775. * @return {Phaser.Point} The new Point object.
  10776. */
  10777. Phaser.Point.add = function (a, b, out) {
  10778. if (typeof out === "undefined") { out = new Phaser.Point(); }
  10779. out.x = a.x + b.x;
  10780. out.y = a.y + b.y;
  10781. return out;
  10782. };
  10783. /**
  10784. * Subtracts the coordinates of two points to create a new point.
  10785. *
  10786. * @method Phaser.Point.subtract
  10787. * @param {Phaser.Point} a - The first Point object.
  10788. * @param {Phaser.Point} b - The second Point object.
  10789. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  10790. * @return {Phaser.Point} The new Point object.
  10791. */
  10792. Phaser.Point.subtract = function (a, b, out) {
  10793. if (typeof out === "undefined") { out = new Phaser.Point(); }
  10794. out.x = a.x - b.x;
  10795. out.y = a.y - b.y;
  10796. return out;
  10797. };
  10798. /**
  10799. * Multiplies the coordinates of two points to create a new point.
  10800. *
  10801. * @method Phaser.Point.multiply
  10802. * @param {Phaser.Point} a - The first Point object.
  10803. * @param {Phaser.Point} b - The second Point object.
  10804. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  10805. * @return {Phaser.Point} The new Point object.
  10806. */
  10807. Phaser.Point.multiply = function (a, b, out) {
  10808. if (typeof out === "undefined") { out = new Phaser.Point(); }
  10809. out.x = a.x * b.x;
  10810. out.y = a.y * b.y;
  10811. return out;
  10812. };
  10813. /**
  10814. * Divides the coordinates of two points to create a new point.
  10815. *
  10816. * @method Phaser.Point.divide
  10817. * @param {Phaser.Point} a - The first Point object.
  10818. * @param {Phaser.Point} b - The second Point object.
  10819. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  10820. * @return {Phaser.Point} The new Point object.
  10821. */
  10822. Phaser.Point.divide = function (a, b, out) {
  10823. if (typeof out === "undefined") { out = new Phaser.Point(); }
  10824. out.x = a.x / b.x;
  10825. out.y = a.y / b.y;
  10826. return out;
  10827. };
  10828. /**
  10829. * Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values.
  10830. *
  10831. * @method Phaser.Point.equals
  10832. * @param {Phaser.Point} a - The first Point object.
  10833. * @param {Phaser.Point} b - The second Point object.
  10834. * @return {boolean} A value of true if the Points are equal, otherwise false.
  10835. */
  10836. Phaser.Point.equals = function (a, b) {
  10837. return (a.x === b.x && a.y === b.y);
  10838. };
  10839. /**
  10840. * Returns the angle between two Point objects.
  10841. *
  10842. * @method Phaser.Point.angle
  10843. * @param {Phaser.Point} a - The first Point object.
  10844. * @param {Phaser.Point} b - The second Point object.
  10845. * @return {number} The angle between the two Points.
  10846. */
  10847. Phaser.Point.angle = function (a, b) {
  10848. // return Math.atan2(a.x * b.y - a.y * b.x, a.x * b.x + a.y * b.y);
  10849. return Math.atan2(a.y - b.y, a.x - b.x);
  10850. };
  10851. /**
  10852. * Returns the angle squared between two Point objects.
  10853. *
  10854. * @method Phaser.Point.angleSq
  10855. * @param {Phaser.Point} a - The first Point object.
  10856. * @param {Phaser.Point} b - The second Point object.
  10857. * @return {number} The angle squared between the two Points.
  10858. */
  10859. Phaser.Point.angleSq = function (a, b) {
  10860. return a.subtract(b).angle(b.subtract(a));
  10861. };
  10862. /**
  10863. * Creates a negative Point.
  10864. *
  10865. * @method Phaser.Point.negative
  10866. * @param {Phaser.Point} a - The first Point object.
  10867. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  10868. * @return {Phaser.Point} The new Point object.
  10869. */
  10870. Phaser.Point.negative = function (a, out) {
  10871. if (typeof out === "undefined") { out = new Phaser.Point(); }
  10872. return out.setTo(-a.x, -a.y);
  10873. };
  10874. /**
  10875. * Adds two 2D Points together and multiplies the result by the given scalar.
  10876. *
  10877. * @method Phaser.Point.multiplyAdd
  10878. * @param {Phaser.Point} a - The first Point object.
  10879. * @param {Phaser.Point} b - The second Point object.
  10880. * @param {number} s - The scaling value.
  10881. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  10882. * @return {Phaser.Point} The new Point object.
  10883. */
  10884. Phaser.Point.multiplyAdd = function (a, b, s, out) {
  10885. if (typeof out === "undefined") { out = new Phaser.Point(); }
  10886. return out.setTo(a.x + b.x * s, a.y + b.y * s);
  10887. };
  10888. /**
  10889. * Interpolates the two given Points, based on the `f` value (between 0 and 1) and returns a new Point.
  10890. *
  10891. * @method Phaser.Point.interpolate
  10892. * @param {Phaser.Point} a - The first Point object.
  10893. * @param {Phaser.Point} b - The second Point object.
  10894. * @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.
  10895. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  10896. * @return {Phaser.Point} The new Point object.
  10897. */
  10898. Phaser.Point.interpolate = function (a, b, f, out) {
  10899. if (typeof out === "undefined") { out = new Phaser.Point(); }
  10900. return out.setTo(a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f);
  10901. };
  10902. /**
  10903. * Return a perpendicular vector (90 degrees rotation)
  10904. *
  10905. * @method Phaser.Point.perp
  10906. * @param {Phaser.Point} a - The Point object.
  10907. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  10908. * @return {Phaser.Point} The new Point object.
  10909. */
  10910. Phaser.Point.perp = function (a, out) {
  10911. if (typeof out === "undefined") { out = new Phaser.Point(); }
  10912. return out.setTo(-a.y, a.x);
  10913. };
  10914. /**
  10915. * Return a perpendicular vector (-90 degrees rotation)
  10916. *
  10917. * @method Phaser.Point.rperp
  10918. * @param {Phaser.Point} a - The Point object.
  10919. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  10920. * @return {Phaser.Point} The new Point object.
  10921. */
  10922. Phaser.Point.rperp = function (a, out) {
  10923. if (typeof out === "undefined") { out = new Phaser.Point(); }
  10924. return out.setTo(a.y, -a.x);
  10925. };
  10926. /**
  10927. * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties).
  10928. *
  10929. * @method Phaser.Point.distance
  10930. * @param {object} a - The target object. Must have visible x and y properties that represent the center of the object.
  10931. * @param {object} b - The target object. Must have visible x and y properties that represent the center of the object.
  10932. * @param {boolean} [round] - Round the distance to the nearest integer (default false).
  10933. * @return {number} The distance between this Point object and the destination Point object.
  10934. */
  10935. Phaser.Point.distance = function (a, b, round) {
  10936. if (typeof round === "undefined") { round = false; }
  10937. if (round)
  10938. {
  10939. return Phaser.Math.distanceRounded(a.x, a.y, b.x, b.y);
  10940. }
  10941. else
  10942. {
  10943. return Phaser.Math.distance(a.x, a.y, b.x, b.y);
  10944. }
  10945. };
  10946. /**
  10947. * Project two Points onto another Point.
  10948. *
  10949. * @method Phaser.Point.project
  10950. * @param {Phaser.Point} a - The first Point object.
  10951. * @param {Phaser.Point} b - The second Point object.
  10952. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  10953. * @return {Phaser.Point} The new Point object.
  10954. */
  10955. Phaser.Point.project = function (a, b, out) {
  10956. if (typeof out === "undefined") { out = new Phaser.Point(); }
  10957. var amt = a.dot(b) / b.getMagnitudeSq();
  10958. if (amt !== 0)
  10959. {
  10960. out.setTo(amt * b.x, amt * b.y);
  10961. }
  10962. return out;
  10963. };
  10964. /**
  10965. * Project two Points onto a Point of unit length.
  10966. *
  10967. * @method Phaser.Point.projectUnit
  10968. * @param {Phaser.Point} a - The first Point object.
  10969. * @param {Phaser.Point} b - The second Point object.
  10970. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  10971. * @return {Phaser.Point} The new Point object.
  10972. */
  10973. Phaser.Point.projectUnit = function (a, b, out) {
  10974. if (typeof out === "undefined") { out = new Phaser.Point(); }
  10975. var amt = a.dot(b);
  10976. if (amt !== 0)
  10977. {
  10978. out.setTo(amt * b.x, amt * b.y);
  10979. }
  10980. return out;
  10981. };
  10982. /**
  10983. * Right-hand normalize (make unit length) a Point.
  10984. *
  10985. * @method Phaser.Point.normalRightHand
  10986. * @param {Phaser.Point} a - The Point object.
  10987. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  10988. * @return {Phaser.Point} The new Point object.
  10989. */
  10990. Phaser.Point.normalRightHand = function (a, out) {
  10991. if (typeof out === "undefined") { out = new Phaser.Point(); }
  10992. return out.setTo(a.y * -1, a.x);
  10993. };
  10994. /**
  10995. * Normalize (make unit length) a Point.
  10996. *
  10997. * @method Phaser.Point.normalize
  10998. * @param {Phaser.Point} a - The Point object.
  10999. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  11000. * @return {Phaser.Point} The new Point object.
  11001. */
  11002. Phaser.Point.normalize = function (a, out) {
  11003. if (typeof out === "undefined") { out = new Phaser.Point(); }
  11004. var m = a.getMagnitude();
  11005. if (m !== 0)
  11006. {
  11007. out.setTo(a.x / m, a.y / m);
  11008. }
  11009. return out;
  11010. };
  11011. /**
  11012. * Rotates a Point around the x/y coordinates given to the desired angle.
  11013. *
  11014. * @method Phaser.Point.rotate
  11015. * @param {Phaser.Point} a - The Point object to rotate.
  11016. * @param {number} x - The x coordinate of the anchor point
  11017. * @param {number} y - The y coordinate of the anchor point
  11018. * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to.
  11019. * @param {boolean} [asDegrees=false] - Is the given rotation in radians (false) or degrees (true)?
  11020. * @param {number} [distance] - An optional distance constraint between the Point and the anchor.
  11021. * @return {Phaser.Point} The modified point object.
  11022. */
  11023. Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) {
  11024. asDegrees = asDegrees || false;
  11025. distance = distance || null;
  11026. if (asDegrees)
  11027. {
  11028. angle = Phaser.Math.degToRad(angle);
  11029. }
  11030. // Get distance from origin (cx/cy) to this point
  11031. if (distance === null)
  11032. {
  11033. distance = Math.sqrt(((x - a.x) * (x - a.x)) + ((y - a.y) * (y - a.y)));
  11034. }
  11035. return a.setTo(x + distance * Math.cos(angle), y + distance * Math.sin(angle));
  11036. };
  11037. /**
  11038. * Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned.
  11039. *
  11040. * @method Phaser.Point.centroid
  11041. * @param {Phaser.Point[]} points - The array of one or more points.
  11042. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  11043. * @return {Phaser.Point} The new Point object.
  11044. */
  11045. Phaser.Point.centroid = function (points, out) {
  11046. if (typeof out === "undefined") { out = new Phaser.Point(); }
  11047. if (Object.prototype.toString.call(points) !== '[object Array]')
  11048. {
  11049. throw new Error("Phaser.Point. Parameter 'points' must be an array");
  11050. }
  11051. var pointslength = points.length;
  11052. if (pointslength < 1)
  11053. {
  11054. throw new Error("Phaser.Point. Parameter 'points' array must not be empty");
  11055. }
  11056. if (pointslength === 1)
  11057. {
  11058. out.copyFrom(points[0]);
  11059. return out;
  11060. }
  11061. for (var i = 0; i < pointslength; i++)
  11062. {
  11063. Phaser.Point.add(out, points[i], out);
  11064. }
  11065. out.divide(pointslength, pointslength);
  11066. return out;
  11067. };
  11068. // Because PIXI uses its own Point, we'll replace it with ours to avoid duplicating code or confusion.
  11069. PIXI.Point = Phaser.Point;
  11070. /**
  11071. * @author Richard Davey <rich@photonstorm.com>
  11072. * @copyright 2014 Photon Storm Ltd.
  11073. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  11074. */
  11075. /**
  11076. * 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. If you call this function without parameters, a Rectangle with x, y, width, and height properties set to 0 is created.
  11077. *
  11078. * @class Phaser.Rectangle
  11079. * @constructor
  11080. * @param {number} x - The x coordinate of the top-left corner of the Rectangle.
  11081. * @param {number} y - The y coordinate of the top-left corner of the Rectangle.
  11082. * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value.
  11083. * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value.
  11084. * @return {Phaser.Rectangle} This Rectangle object.
  11085. */
  11086. Phaser.Rectangle = function (x, y, width, height) {
  11087. x = x || 0;
  11088. y = y || 0;
  11089. width = width || 0;
  11090. height = height || 0;
  11091. /**
  11092. * @property {number} x - The x coordinate of the top-left corner of the Rectangle.
  11093. */
  11094. this.x = x;
  11095. /**
  11096. * @property {number} y - The y coordinate of the top-left corner of the Rectangle.
  11097. */
  11098. this.y = y;
  11099. /**
  11100. * @property {number} width - The width of the Rectangle. This value should never be set to a negative.
  11101. */
  11102. this.width = width;
  11103. /**
  11104. * @property {number} height - The height of the Rectangle. This value should never be set to a negative.
  11105. */
  11106. this.height = height;
  11107. };
  11108. Phaser.Rectangle.prototype = {
  11109. /**
  11110. * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts.
  11111. * @method Phaser.Rectangle#offset
  11112. * @param {number} dx - Moves the x value of the Rectangle object by this amount.
  11113. * @param {number} dy - Moves the y value of the Rectangle object by this amount.
  11114. * @return {Phaser.Rectangle} This Rectangle object.
  11115. */
  11116. offset: function (dx, dy) {
  11117. this.x += dx;
  11118. this.y += dy;
  11119. return this;
  11120. },
  11121. /**
  11122. * 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.
  11123. * @method Phaser.Rectangle#offsetPoint
  11124. * @param {Phaser.Point} point - A Point object to use to offset this Rectangle object.
  11125. * @return {Phaser.Rectangle} This Rectangle object.
  11126. */
  11127. offsetPoint: function (point) {
  11128. return this.offset(point.x, point.y);
  11129. },
  11130. /**
  11131. * Sets the members of Rectangle to the specified values.
  11132. * @method Phaser.Rectangle#setTo
  11133. * @param {number} x - The x coordinate of the top-left corner of the Rectangle.
  11134. * @param {number} y - The y coordinate of the top-left corner of the Rectangle.
  11135. * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value.
  11136. * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value.
  11137. * @return {Phaser.Rectangle} This Rectangle object
  11138. */
  11139. setTo: function (x, y, width, height) {
  11140. this.x = x;
  11141. this.y = y;
  11142. this.width = width;
  11143. this.height = height;
  11144. return this;
  11145. },
  11146. /**
  11147. * Runs Math.floor() on both the x and y values of this Rectangle.
  11148. * @method Phaser.Rectangle#floor
  11149. */
  11150. floor: function () {
  11151. this.x = Math.floor(this.x);
  11152. this.y = Math.floor(this.y);
  11153. },
  11154. /**
  11155. * Runs Math.floor() on the x, y, width and height values of this Rectangle.
  11156. * @method Phaser.Rectangle#floorAll
  11157. */
  11158. floorAll: function () {
  11159. this.x = Math.floor(this.x);
  11160. this.y = Math.floor(this.y);
  11161. this.width = Math.floor(this.width);
  11162. this.height = Math.floor(this.height);
  11163. },
  11164. /**
  11165. * Copies the x, y, width and height properties from any given object to this Rectangle.
  11166. * @method Phaser.Rectangle#copyFrom
  11167. * @param {any} source - The object to copy from.
  11168. * @return {Phaser.Rectangle} This Rectangle object.
  11169. */
  11170. copyFrom: function (source) {
  11171. return this.setTo(source.x, source.y, source.width, source.height);
  11172. },
  11173. /**
  11174. * Copies the x, y, width and height properties from this Rectangle to any given object.
  11175. * @method Phaser.Rectangle#copyTo
  11176. * @param {any} source - The object to copy to.
  11177. * @return {object} This object.
  11178. */
  11179. copyTo: function (dest) {
  11180. dest.x = this.x;
  11181. dest.y = this.y;
  11182. dest.width = this.width;
  11183. dest.height = this.height;
  11184. return dest;
  11185. },
  11186. /**
  11187. * 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.
  11188. * @method Phaser.Rectangle#inflate
  11189. * @param {number} dx - The amount to be added to the left side of the Rectangle.
  11190. * @param {number} dy - The amount to be added to the bottom side of the Rectangle.
  11191. * @return {Phaser.Rectangle} This Rectangle object.
  11192. */
  11193. inflate: function (dx, dy) {
  11194. return Phaser.Rectangle.inflate(this, dx, dy);
  11195. },
  11196. /**
  11197. * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties.
  11198. * @method Phaser.Rectangle#size
  11199. * @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.
  11200. * @return {Phaser.Point} The size of the Rectangle object.
  11201. */
  11202. size: function (output) {
  11203. return Phaser.Rectangle.size(this, output);
  11204. },
  11205. /**
  11206. * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
  11207. * @method Phaser.Rectangle#clone
  11208. * @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.
  11209. * @return {Phaser.Rectangle}
  11210. */
  11211. clone: function (output) {
  11212. return Phaser.Rectangle.clone(this, output);
  11213. },
  11214. /**
  11215. * Determines whether the specified coordinates are contained within the region defined by this Rectangle object.
  11216. * @method Phaser.Rectangle#contains
  11217. * @param {number} x - The x coordinate of the point to test.
  11218. * @param {number} y - The y coordinate of the point to test.
  11219. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  11220. */
  11221. contains: function (x, y) {
  11222. return Phaser.Rectangle.contains(this, x, y);
  11223. },
  11224. /**
  11225. * Determines whether the first Rectangle object is fully contained within the second Rectangle object.
  11226. * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first.
  11227. * @method Phaser.Rectangle#containsRect
  11228. * @param {Phaser.Rectangle} b - The second Rectangle object.
  11229. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  11230. */
  11231. containsRect: function (b) {
  11232. return Phaser.Rectangle.containsRect(this, b);
  11233. },
  11234. /**
  11235. * Determines whether the two Rectangles are equal.
  11236. * This method compares the x, y, width and height properties of each Rectangle.
  11237. * @method Phaser.Rectangle#equals
  11238. * @param {Phaser.Rectangle} b - The second Rectangle object.
  11239. * @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.
  11240. */
  11241. equals: function (b) {
  11242. return Phaser.Rectangle.equals(this, b);
  11243. },
  11244. /**
  11245. * 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.
  11246. * @method Phaser.Rectangle#intersection
  11247. * @param {Phaser.Rectangle} b - The second Rectangle object.
  11248. * @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.
  11249. * @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.
  11250. */
  11251. intersection: function (b, out) {
  11252. return Phaser.Rectangle.intersection(this, b, out);
  11253. },
  11254. /**
  11255. * Determines whether the two Rectangles intersect with each other.
  11256. * This method checks the x, y, width, and height properties of the Rectangles.
  11257. * @method Phaser.Rectangle#intersects
  11258. * @param {Phaser.Rectangle} b - The second Rectangle object.
  11259. * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0.
  11260. * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false.
  11261. */
  11262. intersects: function (b, tolerance) {
  11263. return Phaser.Rectangle.intersects(this, b, tolerance);
  11264. },
  11265. /**
  11266. * Determines whether the coordinates given intersects (overlaps) with this Rectangle.
  11267. *
  11268. * @method Phaser.Rectangle#intersectsRaw
  11269. * @param {number} left - The x coordinate of the left of the area.
  11270. * @param {number} right - The right coordinate of the area.
  11271. * @param {number} top - The y coordinate of the area.
  11272. * @param {number} bottom - The bottom coordinate of the area.
  11273. * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0
  11274. * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false.
  11275. */
  11276. intersectsRaw: function (left, right, top, bottom, tolerance) {
  11277. return Phaser.Rectangle.intersectsRaw(this, left, right, top, bottom, tolerance);
  11278. },
  11279. /**
  11280. * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles.
  11281. * @method Phaser.Rectangle#union
  11282. * @param {Phaser.Rectangle} b - The second Rectangle object.
  11283. * @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.
  11284. * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles.
  11285. */
  11286. union: function (b, out) {
  11287. return Phaser.Rectangle.union(this, b, out);
  11288. },
  11289. /**
  11290. * Returns a string representation of this object.
  11291. * @method Phaser.Rectangle#toString
  11292. * @return {string} A string representation of the instance.
  11293. */
  11294. toString: function () {
  11295. return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]";
  11296. }
  11297. };
  11298. /**
  11299. * @name Phaser.Rectangle#halfWidth
  11300. * @property {number} halfWidth - Half of the width of the Rectangle.
  11301. * @readonly
  11302. */
  11303. Object.defineProperty(Phaser.Rectangle.prototype, "halfWidth", {
  11304. get: function () {
  11305. return Math.round(this.width / 2);
  11306. }
  11307. });
  11308. /**
  11309. * @name Phaser.Rectangle#halfHeight
  11310. * @property {number} halfHeight - Half of the height of the Rectangle.
  11311. * @readonly
  11312. */
  11313. Object.defineProperty(Phaser.Rectangle.prototype, "halfHeight", {
  11314. get: function () {
  11315. return Math.round(this.height / 2);
  11316. }
  11317. });
  11318. /**
  11319. * 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.
  11320. * @name Phaser.Rectangle#bottom
  11321. * @property {number} bottom - The sum of the y and height properties.
  11322. */
  11323. Object.defineProperty(Phaser.Rectangle.prototype, "bottom", {
  11324. get: function () {
  11325. return this.y + this.height;
  11326. },
  11327. set: function (value) {
  11328. if (value <= this.y) {
  11329. this.height = 0;
  11330. } else {
  11331. this.height = (this.y - value);
  11332. }
  11333. }
  11334. });
  11335. /**
  11336. * The location of the Rectangles bottom right corner as a Point object.
  11337. * @name Phaser.Rectangle#bottom
  11338. * @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object.
  11339. */
  11340. Object.defineProperty(Phaser.Rectangle.prototype, "bottomRight", {
  11341. get: function () {
  11342. return new Phaser.Point(this.right, this.bottom);
  11343. },
  11344. set: function (value) {
  11345. this.right = value.x;
  11346. this.bottom = value.y;
  11347. }
  11348. });
  11349. /**
  11350. * 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.
  11351. * @name Phaser.Rectangle#left
  11352. * @property {number} left - The x coordinate of the left of the Rectangle.
  11353. */
  11354. Object.defineProperty(Phaser.Rectangle.prototype, "left", {
  11355. get: function () {
  11356. return this.x;
  11357. },
  11358. set: function (value) {
  11359. if (value >= this.right) {
  11360. this.width = 0;
  11361. } else {
  11362. this.width = this.right - value;
  11363. }
  11364. this.x = value;
  11365. }
  11366. });
  11367. /**
  11368. * 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.
  11369. * @name Phaser.Rectangle#right
  11370. * @property {number} right - The sum of the x and width properties.
  11371. */
  11372. Object.defineProperty(Phaser.Rectangle.prototype, "right", {
  11373. get: function () {
  11374. return this.x + this.width;
  11375. },
  11376. set: function (value) {
  11377. if (value <= this.x) {
  11378. this.width = 0;
  11379. } else {
  11380. this.width = value - this.x;
  11381. }
  11382. }
  11383. });
  11384. /**
  11385. * The volume of the Rectangle derived from width * height.
  11386. * @name Phaser.Rectangle#volume
  11387. * @property {number} volume - The volume of the Rectangle derived from width * height.
  11388. * @readonly
  11389. */
  11390. Object.defineProperty(Phaser.Rectangle.prototype, "volume", {
  11391. get: function () {
  11392. return this.width * this.height;
  11393. }
  11394. });
  11395. /**
  11396. * The perimeter size of the Rectangle. This is the sum of all 4 sides.
  11397. * @name Phaser.Rectangle#perimeter
  11398. * @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides.
  11399. * @readonly
  11400. */
  11401. Object.defineProperty(Phaser.Rectangle.prototype, "perimeter", {
  11402. get: function () {
  11403. return (this.width * 2) + (this.height * 2);
  11404. }
  11405. });
  11406. /**
  11407. * The x coordinate of the center of the Rectangle.
  11408. * @name Phaser.Rectangle#centerX
  11409. * @property {number} centerX - The x coordinate of the center of the Rectangle.
  11410. */
  11411. Object.defineProperty(Phaser.Rectangle.prototype, "centerX", {
  11412. get: function () {
  11413. return this.x + this.halfWidth;
  11414. },
  11415. set: function (value) {
  11416. this.x = value - this.halfWidth;
  11417. }
  11418. });
  11419. /**
  11420. * The y coordinate of the center of the Rectangle.
  11421. * @name Phaser.Rectangle#centerY
  11422. * @property {number} centerY - The y coordinate of the center of the Rectangle.
  11423. */
  11424. Object.defineProperty(Phaser.Rectangle.prototype, "centerY", {
  11425. get: function () {
  11426. return this.y + this.halfHeight;
  11427. },
  11428. set: function (value) {
  11429. this.y = value - this.halfHeight;
  11430. }
  11431. });
  11432. /**
  11433. * A random value between the left and right values (inclusive) of the Rectangle.
  11434. *
  11435. * @name Phaser.Rectangle#randomX
  11436. * @property {number} randomX - A random value between the left and right values (inclusive) of the Rectangle.
  11437. */
  11438. Object.defineProperty(Phaser.Rectangle.prototype, "randomX", {
  11439. get: function () {
  11440. return this.x + (Math.random() * this.width);
  11441. }
  11442. });
  11443. /**
  11444. * A random value between the top and bottom values (inclusive) of the Rectangle.
  11445. *
  11446. * @name Phaser.Rectangle#randomY
  11447. * @property {number} randomY - A random value between the top and bottom values (inclusive) of the Rectangle.
  11448. */
  11449. Object.defineProperty(Phaser.Rectangle.prototype, "randomY", {
  11450. get: function () {
  11451. return this.y + (Math.random() * this.height);
  11452. }
  11453. });
  11454. /**
  11455. * 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.
  11456. * However it does affect the height property, whereas changing the y value does not affect the height property.
  11457. * @name Phaser.Rectangle#top
  11458. * @property {number} top - The y coordinate of the top of the Rectangle.
  11459. */
  11460. Object.defineProperty(Phaser.Rectangle.prototype, "top", {
  11461. get: function () {
  11462. return this.y;
  11463. },
  11464. set: function (value) {
  11465. if (value >= this.bottom) {
  11466. this.height = 0;
  11467. this.y = value;
  11468. } else {
  11469. this.height = (this.bottom - value);
  11470. }
  11471. }
  11472. });
  11473. /**
  11474. * The location of the Rectangles top left corner as a Point object.
  11475. * @name Phaser.Rectangle#topLeft
  11476. * @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object.
  11477. */
  11478. Object.defineProperty(Phaser.Rectangle.prototype, "topLeft", {
  11479. get: function () {
  11480. return new Phaser.Point(this.x, this.y);
  11481. },
  11482. set: function (value) {
  11483. this.x = value.x;
  11484. this.y = value.y;
  11485. }
  11486. });
  11487. /**
  11488. * 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.
  11489. * If set to true then all of the Rectangle properties are set to 0.
  11490. * @name Phaser.Rectangle#empty
  11491. * @property {boolean} empty - Gets or sets the Rectangles empty state.
  11492. */
  11493. Object.defineProperty(Phaser.Rectangle.prototype, "empty", {
  11494. get: function () {
  11495. return (!this.width || !this.height);
  11496. },
  11497. set: function (value) {
  11498. if (value === true)
  11499. {
  11500. this.setTo(0, 0, 0, 0);
  11501. }
  11502. }
  11503. });
  11504. Phaser.Rectangle.prototype.constructor = Phaser.Rectangle;
  11505. /**
  11506. * 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.
  11507. * @method Phaser.Rectangle.inflate
  11508. * @param {Phaser.Rectangle} a - The Rectangle object.
  11509. * @param {number} dx - The amount to be added to the left side of the Rectangle.
  11510. * @param {number} dy - The amount to be added to the bottom side of the Rectangle.
  11511. * @return {Phaser.Rectangle} This Rectangle object.
  11512. */
  11513. Phaser.Rectangle.inflate = function (a, dx, dy) {
  11514. a.x -= dx;
  11515. a.width += 2 * dx;
  11516. a.y -= dy;
  11517. a.height += 2 * dy;
  11518. return a;
  11519. };
  11520. /**
  11521. * 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.
  11522. * @method Phaser.Rectangle.inflatePoint
  11523. * @param {Phaser.Rectangle} a - The Rectangle object.
  11524. * @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.
  11525. * @return {Phaser.Rectangle} The Rectangle object.
  11526. */
  11527. Phaser.Rectangle.inflatePoint = function (a, point) {
  11528. return Phaser.Rectangle.inflate(a, point.x, point.y);
  11529. };
  11530. /**
  11531. * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties.
  11532. * @method Phaser.Rectangle.size
  11533. * @param {Phaser.Rectangle} a - The Rectangle object.
  11534. * @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.
  11535. * @return {Phaser.Point} The size of the Rectangle object
  11536. */
  11537. Phaser.Rectangle.size = function (a, output) {
  11538. if (typeof output === "undefined" || output === null)
  11539. {
  11540. output = new Phaser.Point(a.width, a.height);
  11541. }
  11542. else
  11543. {
  11544. output.setTo(a.width, a.height);
  11545. }
  11546. return output;
  11547. };
  11548. /**
  11549. * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
  11550. * @method Phaser.Rectangle.clone
  11551. * @param {Phaser.Rectangle} a - The Rectangle object.
  11552. * @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.
  11553. * @return {Phaser.Rectangle}
  11554. */
  11555. Phaser.Rectangle.clone = function (a, output) {
  11556. if (typeof output === "undefined" || output === null)
  11557. {
  11558. output = new Phaser.Rectangle(a.x, a.y, a.width, a.height);
  11559. }
  11560. else
  11561. {
  11562. output.setTo(a.x, a.y, a.width, a.height);
  11563. }
  11564. return output;
  11565. };
  11566. /**
  11567. * Determines whether the specified coordinates are contained within the region defined by this Rectangle object.
  11568. * @method Phaser.Rectangle.contains
  11569. * @param {Phaser.Rectangle} a - The Rectangle object.
  11570. * @param {number} x - The x coordinate of the point to test.
  11571. * @param {number} y - The y coordinate of the point to test.
  11572. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  11573. */
  11574. Phaser.Rectangle.contains = function (a, x, y) {
  11575. if (a.width <= 0 || a.height <= 0)
  11576. {
  11577. return false;
  11578. }
  11579. return (x >= a.x && x <= a.right && y >= a.y && y <= a.bottom);
  11580. };
  11581. /**
  11582. * Determines whether the specified coordinates are contained within the region defined by the given raw values.
  11583. * @method Phaser.Rectangle.containsRaw
  11584. * @param {number} rx - The x coordinate of the top left of the area.
  11585. * @param {number} ry - The y coordinate of the top left of the area.
  11586. * @param {number} rw - The width of the area.
  11587. * @param {number} rh - The height of the area.
  11588. * @param {number} x - The x coordinate of the point to test.
  11589. * @param {number} y - The y coordinate of the point to test.
  11590. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  11591. */
  11592. Phaser.Rectangle.containsRaw = function (rx, ry, rw, rh, x, y) {
  11593. return (x >= rx && x <= (rx + rw) && y >= ry && y <= (ry + rh));
  11594. };
  11595. /**
  11596. * 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.
  11597. * @method Phaser.Rectangle.containsPoint
  11598. * @param {Phaser.Rectangle} a - The Rectangle object.
  11599. * @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values.
  11600. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  11601. */
  11602. Phaser.Rectangle.containsPoint = function (a, point) {
  11603. return Phaser.Rectangle.contains(a, point.x, point.y);
  11604. };
  11605. /**
  11606. * Determines whether the first Rectangle object is fully contained within the second Rectangle object.
  11607. * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first.
  11608. * @method Phaser.Rectangle.containsRect
  11609. * @param {Phaser.Rectangle} a - The first Rectangle object.
  11610. * @param {Phaser.Rectangle} b - The second Rectangle object.
  11611. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  11612. */
  11613. Phaser.Rectangle.containsRect = function (a, b) {
  11614. // If the given rect has a larger volume than this one then it can never contain it
  11615. if (a.volume > b.volume)
  11616. {
  11617. return false;
  11618. }
  11619. return (a.x >= b.x && a.y >= b.y && a.right <= b.right && a.bottom <= b.bottom);
  11620. };
  11621. /**
  11622. * Determines whether the two Rectangles are equal.
  11623. * This method compares the x, y, width and height properties of each Rectangle.
  11624. * @method Phaser.Rectangle.equals
  11625. * @param {Phaser.Rectangle} a - The first Rectangle object.
  11626. * @param {Phaser.Rectangle} b - The second Rectangle object.
  11627. * @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.
  11628. */
  11629. Phaser.Rectangle.equals = function (a, b) {
  11630. return (a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height);
  11631. };
  11632. /**
  11633. * 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.
  11634. * @method Phaser.Rectangle.intersection
  11635. * @param {Phaser.Rectangle} a - The first Rectangle object.
  11636. * @param {Phaser.Rectangle} b - The second Rectangle object.
  11637. * @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.
  11638. * @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.
  11639. */
  11640. Phaser.Rectangle.intersection = function (a, b, output) {
  11641. if (typeof output === "undefined")
  11642. {
  11643. output = new Phaser.Rectangle();
  11644. }
  11645. if (Phaser.Rectangle.intersects(a, b))
  11646. {
  11647. output.x = Math.max(a.x, b.x);
  11648. output.y = Math.max(a.y, b.y);
  11649. output.width = Math.min(a.right, b.right) - output.x;
  11650. output.height = Math.min(a.bottom, b.bottom) - output.y;
  11651. }
  11652. return output;
  11653. };
  11654. /**
  11655. * Determines whether the two Rectangles intersect with each other.
  11656. * This method checks the x, y, width, and height properties of the Rectangles.
  11657. * @method Phaser.Rectangle.intersects
  11658. * @param {Phaser.Rectangle} a - The first Rectangle object.
  11659. * @param {Phaser.Rectangle} b - The second Rectangle object.
  11660. * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false.
  11661. */
  11662. Phaser.Rectangle.intersects = function (a, b) {
  11663. if (a.width <= 0 || a.height <= 0 || b.width <= 0 || b.height <= 0)
  11664. {
  11665. return false;
  11666. }
  11667. return !(a.right < b.x || a.bottom < b.y || a.x > b.right || a.y > b.bottom);
  11668. };
  11669. /**
  11670. * Determines whether the object specified intersects (overlaps) with the given values.
  11671. * @method Phaser.Rectangle.intersectsRaw
  11672. * @param {number} left - The x coordinate of the left of the area.
  11673. * @param {number} right - The right coordinate of the area.
  11674. * @param {number} top - The y coordinate of the area.
  11675. * @param {number} bottom - The bottom coordinate of the area.
  11676. * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0
  11677. * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false.
  11678. */
  11679. Phaser.Rectangle.intersectsRaw = function (a, left, right, top, bottom, tolerance) {
  11680. if (typeof tolerance === "undefined") { tolerance = 0; }
  11681. return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance);
  11682. };
  11683. /**
  11684. * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles.
  11685. * @method Phaser.Rectangle.union
  11686. * @param {Phaser.Rectangle} a - The first Rectangle object.
  11687. * @param {Phaser.Rectangle} b - The second Rectangle object.
  11688. * @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.
  11689. * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles.
  11690. */
  11691. Phaser.Rectangle.union = function (a, b, output) {
  11692. if (typeof output === "undefined")
  11693. {
  11694. output = new Phaser.Rectangle();
  11695. }
  11696. 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));
  11697. };
  11698. // Because PIXI uses its own Rectangle, we'll replace it with ours to avoid duplicating code or confusion.
  11699. PIXI.Rectangle = Phaser.Rectangle;
  11700. PIXI.EmptyRectangle = new Phaser.Rectangle(0, 0, 0, 0);
  11701. /**
  11702. * @author Richard Davey <rich@photonstorm.com>
  11703. * @copyright 2014 Photon Storm Ltd.
  11704. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  11705. */
  11706. /**
  11707. * Creates a new Line object with a start and an end point.
  11708. * @class Line
  11709. * @classdesc Phaser - Line
  11710. * @constructor
  11711. * @param {number} [x1=0] - The x coordinate of the start of the line.
  11712. * @param {number} [y1=0] - The y coordinate of the start of the line.
  11713. * @param {number} [x2=0] - The x coordinate of the end of the line.
  11714. * @param {number} [y2=0] - The y coordinate of the end of the line.
  11715. * @return {Phaser.Line} This line object
  11716. */
  11717. Phaser.Line = function (x1, y1, x2, y2) {
  11718. x1 = x1 || 0;
  11719. y1 = y1 || 0;
  11720. x2 = x2 || 0;
  11721. y2 = y2 || 0;
  11722. /**
  11723. * @property {Phaser.Point} start - The start point of the line.
  11724. */
  11725. this.start = new Phaser.Point(x1, y1);
  11726. /**
  11727. * @property {Phaser.Point} end - The end point of the line.
  11728. */
  11729. this.end = new Phaser.Point(x2, y2);
  11730. };
  11731. Phaser.Line.prototype = {
  11732. /**
  11733. * Sets the components of the Line to the specified values.
  11734. * @method Phaser.Line#setTo
  11735. * @param {number} [x1=0] - The x coordinate of the start of the line.
  11736. * @param {number} [y1=0] - The y coordinate of the start of the line.
  11737. * @param {number} [x2=0] - The x coordinate of the end of the line.
  11738. * @param {number} [y2=0] - The y coordinate of the end of the line.
  11739. * @return {Phaser.Line} This line object
  11740. */
  11741. setTo: function (x1, y1, x2, y2) {
  11742. this.start.setTo(x1, y1);
  11743. this.end.setTo(x2, y2);
  11744. return this;
  11745. },
  11746. /**
  11747. * Sets the line to match the x/y coordinates of the two given sprites.
  11748. * Can optionally be calculated from their center coordinates.
  11749. * @method Phaser.Line#fromSprite
  11750. * @param {Phaser.Sprite} startSprite - The coordinates of this Sprite will be set to the Line.start point.
  11751. * @param {Phaser.Sprite} endSprite - The coordinates of this Sprite will be set to the Line.start point.
  11752. * @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.
  11753. * @return {Phaser.Line} This line object
  11754. */
  11755. fromSprite: function (startSprite, endSprite, useCenter) {
  11756. if (typeof useCenter === 'undefined') { useCenter = false; }
  11757. if (useCenter)
  11758. {
  11759. return this.setTo(startSprite.center.x, startSprite.center.y, endSprite.center.x, endSprite.center.y);
  11760. }
  11761. else
  11762. {
  11763. return this.setTo(startSprite.x, startSprite.y, endSprite.x, endSprite.y);
  11764. }
  11765. },
  11766. /**
  11767. * Checks for intersection between this line and another Line.
  11768. * If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection.
  11769. * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
  11770. *
  11771. * @method Phaser.Line#intersects
  11772. * @param {Phaser.Line} line - The line to check against this one.
  11773. * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
  11774. * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created.
  11775. * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
  11776. */
  11777. intersects: function (line, asSegment, result) {
  11778. return Phaser.Line.intersectsPoints(this.start, this.end, line.start, line.end, asSegment, result);
  11779. },
  11780. /**
  11781. * Tests if the given coordinates fall on this line. See pointOnSegment to test against just the line segment.
  11782. * @method Phaser.Line#pointOnLine
  11783. * @param {number} x - The line to check against this one.
  11784. * @param {number} y - The line to check against this one.
  11785. * @return {boolean} True if the point is on the line, false if not.
  11786. */
  11787. pointOnLine: function (x, y) {
  11788. return ((x - this.start.x) * (this.end.y - this.start.y) === (this.end.x - this.start.x) * (y - this.start.y));
  11789. },
  11790. /**
  11791. * Tests if the given coordinates fall on this line and within the segment. See pointOnLine to test against just the line.
  11792. * @method Phaser.Line#pointOnSegment
  11793. * @param {number} x - The line to check against this one.
  11794. * @param {number} y - The line to check against this one.
  11795. * @return {boolean} True if the point is on the line and segment, false if not.
  11796. */
  11797. pointOnSegment: function (x, y) {
  11798. var xMin = Math.min(this.start.x, this.end.x);
  11799. var xMax = Math.max(this.start.x, this.end.x);
  11800. var yMin = Math.min(this.start.y, this.end.y);
  11801. var yMax = Math.max(this.start.y, this.end.y);
  11802. return (this.pointOnLine(x, y) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax));
  11803. },
  11804. /**
  11805. * Using Bresenham's line algorithm this will return an array of all coordinates on this line.
  11806. * The start and end points are rounded before this runs as the algorithm works on integers.
  11807. *
  11808. * @method Phaser.Line#coordinatesOnLine
  11809. * @param {number} [stepRate=1] - How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc.
  11810. * @param {array} [results] - The array to store the results in. If not provided a new one will be generated.
  11811. * @return {array} An array of coordinates.
  11812. */
  11813. coordinatesOnLine: function (stepRate, results) {
  11814. if (typeof stepRate === 'undefined') { stepRate = 1; }
  11815. if (typeof results === 'undefined') { results = []; }
  11816. var x1 = Math.round(this.start.x);
  11817. var y1 = Math.round(this.start.y);
  11818. var x2 = Math.round(this.end.x);
  11819. var y2 = Math.round(this.end.y);
  11820. var dx = Math.abs(x2 - x1);
  11821. var dy = Math.abs(y2 - y1);
  11822. var sx = (x1 < x2) ? 1 : -1;
  11823. var sy = (y1 < y2) ? 1 : -1;
  11824. var err = dx - dy;
  11825. results.push([x1, y1]);
  11826. var i = 1;
  11827. while (!((x1 == x2) && (y1 == y2)))
  11828. {
  11829. var e2 = err << 1;
  11830. if (e2 > -dy)
  11831. {
  11832. err -= dy;
  11833. x1 += sx;
  11834. }
  11835. if (e2 < dx)
  11836. {
  11837. err += dx;
  11838. y1 += sy;
  11839. }
  11840. if (i % stepRate === 0)
  11841. {
  11842. results.push([x1, y1]);
  11843. }
  11844. i++;
  11845. }
  11846. return results;
  11847. }
  11848. };
  11849. /**
  11850. * @name Phaser.Line#length
  11851. * @property {number} length - Gets the length of the line segment.
  11852. * @readonly
  11853. */
  11854. Object.defineProperty(Phaser.Line.prototype, "length", {
  11855. get: function () {
  11856. 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));
  11857. }
  11858. });
  11859. /**
  11860. * @name Phaser.Line#angle
  11861. * @property {number} angle - Gets the angle of the line.
  11862. * @readonly
  11863. */
  11864. Object.defineProperty(Phaser.Line.prototype, "angle", {
  11865. get: function () {
  11866. return Math.atan2(this.end.y - this.start.y, this.end.x - this.start.x);
  11867. }
  11868. });
  11869. /**
  11870. * @name Phaser.Line#slope
  11871. * @property {number} slope - Gets the slope of the line (y/x).
  11872. * @readonly
  11873. */
  11874. Object.defineProperty(Phaser.Line.prototype, "slope", {
  11875. get: function () {
  11876. return (this.end.y - this.start.y) / (this.end.x - this.start.x);
  11877. }
  11878. });
  11879. /**
  11880. * @name Phaser.Line#perpSlope
  11881. * @property {number} perpSlope - Gets the perpendicular slope of the line (x/y).
  11882. * @readonly
  11883. */
  11884. Object.defineProperty(Phaser.Line.prototype, "perpSlope", {
  11885. get: function () {
  11886. return -((this.end.x - this.start.x) / (this.end.y - this.start.y));
  11887. }
  11888. });
  11889. /**
  11890. * @name Phaser.Line#x
  11891. * @property {number} x - Gets the x coordinate of the top left of the bounds around this line.
  11892. * @readonly
  11893. */
  11894. Object.defineProperty(Phaser.Line.prototype, "x", {
  11895. get: function () {
  11896. return Math.min(this.start.x, this.end.x);
  11897. }
  11898. });
  11899. /**
  11900. * @name Phaser.Line#y
  11901. * @property {number} y - Gets the y coordinate of the top left of the bounds around this line.
  11902. * @readonly
  11903. */
  11904. Object.defineProperty(Phaser.Line.prototype, "y", {
  11905. get: function () {
  11906. return Math.min(this.start.y, this.end.y);
  11907. }
  11908. });
  11909. /**
  11910. * @name Phaser.Line#left
  11911. * @property {number} left - Gets the left-most point of this line.
  11912. * @readonly
  11913. */
  11914. Object.defineProperty(Phaser.Line.prototype, "left", {
  11915. get: function () {
  11916. return Math.min(this.start.x, this.end.x);
  11917. }
  11918. });
  11919. /**
  11920. * @name Phaser.Line#right
  11921. * @property {number} right - Gets the right-most point of this line.
  11922. * @readonly
  11923. */
  11924. Object.defineProperty(Phaser.Line.prototype, "right", {
  11925. get: function () {
  11926. return Math.max(this.start.x, this.end.x);
  11927. }
  11928. });
  11929. /**
  11930. * @name Phaser.Line#top
  11931. * @property {number} top - Gets the top-most point of this line.
  11932. * @readonly
  11933. */
  11934. Object.defineProperty(Phaser.Line.prototype, "top", {
  11935. get: function () {
  11936. return Math.min(this.start.y, this.end.y);
  11937. }
  11938. });
  11939. /**
  11940. * @name Phaser.Line#bottom
  11941. * @property {number} bottom - Gets the bottom-most point of this line.
  11942. * @readonly
  11943. */
  11944. Object.defineProperty(Phaser.Line.prototype, "bottom", {
  11945. get: function () {
  11946. return Math.max(this.start.y, this.end.y);
  11947. }
  11948. });
  11949. /**
  11950. * @name Phaser.Line#width
  11951. * @property {number} width - Gets the width of this bounds of this line.
  11952. * @readonly
  11953. */
  11954. Object.defineProperty(Phaser.Line.prototype, "width", {
  11955. get: function () {
  11956. return Math.abs(this.start.x - this.end.x);
  11957. }
  11958. });
  11959. /**
  11960. * @name Phaser.Line#height
  11961. * @property {number} height - Gets the height of this bounds of this line.
  11962. * @readonly
  11963. */
  11964. Object.defineProperty(Phaser.Line.prototype, "height", {
  11965. get: function () {
  11966. return Math.abs(this.start.y - this.end.y);
  11967. }
  11968. });
  11969. /**
  11970. * Checks for intersection between two lines as defined by the given start and end points.
  11971. * If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection.
  11972. * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
  11973. * Adapted from code by Keith Hair
  11974. *
  11975. * @method Phaser.Line.intersectsPoints
  11976. * @param {Phaser.Point} a - The start of the first Line to be checked.
  11977. * @param {Phaser.Point} b - The end of the first line to be checked.
  11978. * @param {Phaser.Point} e - The start of the second Line to be checked.
  11979. * @param {Phaser.Point} f - The end of the second line to be checked.
  11980. * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
  11981. * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created.
  11982. * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
  11983. */
  11984. Phaser.Line.intersectsPoints = function (a, b, e, f, asSegment, result) {
  11985. if (typeof asSegment === 'undefined') { asSegment = true; }
  11986. if (typeof result === 'undefined') { result = new Phaser.Point(); }
  11987. var a1 = b.y - a.y;
  11988. var a2 = f.y - e.y;
  11989. var b1 = a.x - b.x;
  11990. var b2 = e.x - f.x;
  11991. var c1 = (b.x * a.y) - (a.x * b.y);
  11992. var c2 = (f.x * e.y) - (e.x * f.y);
  11993. var denom = (a1 * b2) - (a2 * b1);
  11994. if (denom === 0)
  11995. {
  11996. return null;
  11997. }
  11998. result.x = ((b1 * c2) - (b2 * c1)) / denom;
  11999. result.y = ((a2 * c1) - (a1 * c2)) / denom;
  12000. if (asSegment)
  12001. {
  12002. var uc = ((f.y-e.y)*(b.x-a.x) - (f.x-e.x)*(b.y- a.y));
  12003. var ua = (((f.x-e.x)*(a.y-e.y)) - (f.y-e.y)*(a.x-e.x)) / uc;
  12004. var ub = (((b.x- a.x)*(a.y- e.y)) - ((b.y-a.y)*(a.x- e.x))) / uc;
  12005. if (ua >=0 && ua<=1 && ub >=0 && ub <=1) {
  12006. return result;
  12007. } else {
  12008. return null;
  12009. }
  12010. }
  12011. return result;
  12012. };
  12013. /**
  12014. * Checks for intersection between two lines.
  12015. * If asSegment is true it will check for segment intersection.
  12016. * If asSegment is false it will check for line intersection.
  12017. * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
  12018. * Adapted from code by Keith Hair
  12019. *
  12020. * @method Phaser.Line.intersects
  12021. * @param {Phaser.Line} a - The first Line to be checked.
  12022. * @param {Phaser.Line} b - The second Line to be checked.
  12023. * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
  12024. * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created.
  12025. * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
  12026. */
  12027. Phaser.Line.intersects = function (a, b, asSegment, result) {
  12028. return Phaser.Line.intersectsPoints(a.start, a.end, b.start, b.end, asSegment, result);
  12029. };
  12030. /**
  12031. * @author Richard Davey <rich@photonstorm.com>
  12032. * @author Chad Engler <chad@pantherdev.com>
  12033. * @copyright 2014 Photon Storm Ltd.
  12034. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  12035. */
  12036. /**
  12037. * Creates a Ellipse object. A curve on a plane surrounding two focal points.
  12038. * @class Ellipse
  12039. * @classdesc Phaser - Ellipse
  12040. * @constructor
  12041. * @param {number} [x=0] - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
  12042. * @param {number} [y=0] - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
  12043. * @param {number} [width=0] - The overall width of this ellipse.
  12044. * @param {number} [height=0] - The overall height of this ellipse.
  12045. * @return {Phaser.Ellipse} This Ellipse object
  12046. */
  12047. Phaser.Ellipse = function (x, y, width, height) {
  12048. this.type = Phaser.ELLIPSE;
  12049. x = x || 0;
  12050. y = y || 0;
  12051. width = width || 0;
  12052. height = height || 0;
  12053. /**
  12054. * @property {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
  12055. */
  12056. this.x = x;
  12057. /**
  12058. * @property {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
  12059. */
  12060. this.y = y;
  12061. /**
  12062. * @property {number} width - The overall width of this ellipse.
  12063. */
  12064. this.width = width;
  12065. /**
  12066. * @property {number} height - The overall height of this ellipse.
  12067. */
  12068. this.height = height;
  12069. };
  12070. Phaser.Ellipse.prototype = {
  12071. /**
  12072. * Sets the members of the Ellipse to the specified values.
  12073. * @method Phaser.Ellipse#setTo
  12074. * @param {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
  12075. * @param {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
  12076. * @param {number} width - The overall width of this ellipse.
  12077. * @param {number} height - The overall height of this ellipse.
  12078. * @return {Phaser.Ellipse} This Ellipse object.
  12079. */
  12080. setTo: function (x, y, width, height) {
  12081. this.x = x;
  12082. this.y = y;
  12083. this.width = width;
  12084. this.height = height;
  12085. return this;
  12086. },
  12087. /**
  12088. * Copies the x, y, width and height properties from any given object to this Ellipse.
  12089. * @method Phaser.Ellipse#copyFrom
  12090. * @param {any} source - The object to copy from.
  12091. * @return {Phaser.Ellipse} This Ellipse object.
  12092. */
  12093. copyFrom: function (source) {
  12094. return this.setTo(source.x, source.y, source.width, source.height);
  12095. },
  12096. /**
  12097. * Copies the x, y and diameter properties from this Circle to any given object.
  12098. * @method Phaser.Ellipse#copyTo
  12099. * @param {any} dest - The object to copy to.
  12100. * @return {Object} This dest object.
  12101. */
  12102. copyTo: function(dest) {
  12103. dest.x = this.x;
  12104. dest.y = this.y;
  12105. dest.width = this.width;
  12106. dest.height = this.height;
  12107. return dest;
  12108. },
  12109. /**
  12110. * Returns a new Ellipse object with the same values for the x, y, width, and height properties as this Ellipse object.
  12111. * @method Phaser.Ellipse#clone
  12112. * @param {Phaser.Ellipse} out - Optional Ellipse object. If given the values will be set into the object, otherwise a brand new Ellipse object will be created and returned.
  12113. * @return {Phaser.Ellipse} The cloned Ellipse object.
  12114. */
  12115. clone: function(out) {
  12116. if (typeof out === "undefined")
  12117. {
  12118. out = new Phaser.Ellipse(this.x, this.y, this.width, this.height);
  12119. }
  12120. else
  12121. {
  12122. out.setTo(this.x, this.y, this.width, this.height);
  12123. }
  12124. return out;
  12125. },
  12126. /**
  12127. * Return true if the given x/y coordinates are within this Ellipse object.
  12128. * @method Phaser.Ellipse#contains
  12129. * @param {number} x - The X value of the coordinate to test.
  12130. * @param {number} y - The Y value of the coordinate to test.
  12131. * @return {boolean} True if the coordinates are within this ellipse, otherwise false.
  12132. */
  12133. contains: function (x, y) {
  12134. return Phaser.Ellipse.contains(this, x, y);
  12135. },
  12136. /**
  12137. * Returns a string representation of this object.
  12138. * @method Phaser.Ellipse#toString
  12139. * @return {string} A string representation of the instance.
  12140. */
  12141. toString: function () {
  12142. return "[{Phaser.Ellipse (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + ")}]";
  12143. }
  12144. };
  12145. Phaser.Ellipse.prototype.constructor = Phaser.Ellipse;
  12146. /**
  12147. * The left coordinate of the Ellipse. The same as the X coordinate.
  12148. * @name Phaser.Ellipse#left
  12149. * @propety {number} left - Gets or sets the value of the leftmost point of the ellipse.
  12150. */
  12151. Object.defineProperty(Phaser.Ellipse.prototype, "left", {
  12152. get: function () {
  12153. return this.x;
  12154. },
  12155. set: function (value) {
  12156. this.x = value;
  12157. }
  12158. });
  12159. /**
  12160. * 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.
  12161. * @name Phaser.Ellipse#right
  12162. * @property {number} right - Gets or sets the value of the rightmost point of the ellipse.
  12163. */
  12164. Object.defineProperty(Phaser.Ellipse.prototype, "right", {
  12165. get: function () {
  12166. return this.x + this.width;
  12167. },
  12168. set: function (value) {
  12169. if (value < this.x)
  12170. {
  12171. this.width = 0;
  12172. }
  12173. else
  12174. {
  12175. this.width = this.x + value;
  12176. }
  12177. }
  12178. });
  12179. /**
  12180. * The top of the Ellipse. The same as its y property.
  12181. * @name Phaser.Ellipse#top
  12182. * @property {number} top - Gets or sets the top of the ellipse.
  12183. */
  12184. Object.defineProperty(Phaser.Ellipse.prototype, "top", {
  12185. get: function () {
  12186. return this.y;
  12187. },
  12188. set: function (value) {
  12189. this.y = value;
  12190. }
  12191. });
  12192. /**
  12193. * 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.
  12194. * @name Phaser.Ellipse#bottom
  12195. * @property {number} bottom - Gets or sets the bottom of the ellipse.
  12196. */
  12197. Object.defineProperty(Phaser.Ellipse.prototype, "bottom", {
  12198. get: function () {
  12199. return this.y + this.height;
  12200. },
  12201. set: function (value) {
  12202. if (value < this.y)
  12203. {
  12204. this.height = 0;
  12205. }
  12206. else
  12207. {
  12208. this.height = this.y + value;
  12209. }
  12210. }
  12211. });
  12212. /**
  12213. * 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.
  12214. * 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.
  12215. * @name Phaser.Ellipse#empty
  12216. * @property {boolean} empty - Gets or sets the empty state of the ellipse.
  12217. */
  12218. Object.defineProperty(Phaser.Ellipse.prototype, "empty", {
  12219. get: function () {
  12220. return (this.width === 0 || this.height === 0);
  12221. },
  12222. set: function (value) {
  12223. if (value === true)
  12224. {
  12225. this.setTo(0, 0, 0, 0);
  12226. }
  12227. }
  12228. });
  12229. /**
  12230. * Return true if the given x/y coordinates are within the Ellipse object.
  12231. * @method Phaser.Ellipse.contains
  12232. * @param {Phaser.Ellipse} a - The Ellipse to be checked.
  12233. * @param {number} x - The X value of the coordinate to test.
  12234. * @param {number} y - The Y value of the coordinate to test.
  12235. * @return {boolean} True if the coordinates are within this ellipse, otherwise false.
  12236. */
  12237. Phaser.Ellipse.contains = function (a, x, y) {
  12238. if (a.width <= 0 || a.height <= 0)
  12239. {
  12240. return false;
  12241. }
  12242. // Normalize the coords to an ellipse with center 0,0 and a radius of 0.5
  12243. var normx = ((x - a.x) / a.width) - 0.5;
  12244. var normy = ((y - a.y) / a.height) - 0.5;
  12245. normx *= normx;
  12246. normy *= normy;
  12247. return (normx + normy < 0.25);
  12248. };
  12249. /**
  12250. * Returns the framing rectangle of the ellipse as a Phaser.Rectangle object.
  12251. *
  12252. * @method Phaser.Ellipse.getBounds
  12253. * @return {Phaser.Rectangle} The framing rectangle
  12254. */
  12255. Phaser.Ellipse.prototype.getBounds = function() {
  12256. return new Phaser.Rectangle(this.x, this.y, this.width, this.height);
  12257. };
  12258. // Because PIXI uses its own Ellipse, we'll replace it with ours to avoid duplicating code or confusion.
  12259. PIXI.Ellipse = Phaser.Ellipse;
  12260. /**
  12261. * @author Richard Davey <rich@photonstorm.com>
  12262. * @author Adrien Brault <adrien.brault@gmail.com>
  12263. * @copyright 2014 Photon Storm Ltd.
  12264. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  12265. */
  12266. /**
  12267. * Creates a new Polygon. You have to provide a list of points.
  12268. * This can be an array of Points that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...],
  12269. * or the arguments passed can be all the points of the polygon e.g. `new Phaser.Polygon(new Phaser.Point(), new Phaser.Point(), ...)`, or the
  12270. * arguments passed can be flat x,y values e.g. `new Phaser.Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are numbers.
  12271. *
  12272. * @class Phaser.Polygon
  12273. * @classdesc The polygon represents a list of orderded points in space
  12274. * @constructor
  12275. * @param {Array<Phaser.Point>|Array<number>} points - The array of Points.
  12276. */
  12277. Phaser.Polygon = function (points) {
  12278. /**
  12279. * @property {number} type - The base object type.
  12280. */
  12281. this.type = Phaser.POLYGON;
  12282. //if points isn't an array, use arguments as the array
  12283. if (!(points instanceof Array))
  12284. {
  12285. points = Array.prototype.slice.call(arguments);
  12286. }
  12287. //if this is a flat array of numbers, convert it to points
  12288. if (typeof points[0] === 'number')
  12289. {
  12290. var p = [];
  12291. for (var i = 0, len = points.length; i < len; i += 2)
  12292. {
  12293. p.push(new Phaser.Point(points[i], points[i + 1]));
  12294. }
  12295. points = p;
  12296. }
  12297. /**
  12298. * @property {array<Phaser.Point>|array<number>} points - The array of vertex Points.
  12299. * @private
  12300. */
  12301. this._points = points;
  12302. };
  12303. Phaser.Polygon.prototype = {
  12304. /**
  12305. * Creates a clone of this polygon.
  12306. *
  12307. * @method Phaser.Polygon#clone
  12308. * @return {Phaser.Polygon} A copy of the polygon.
  12309. */
  12310. clone: function () {
  12311. var points = [];
  12312. for (var i=0; i < this.points.length; i++)
  12313. {
  12314. points.push(this.points[i].clone());
  12315. }
  12316. return new Phaser.Polygon(points);
  12317. },
  12318. /**
  12319. * Checks whether the x and y coordinates are contained within this polygon.
  12320. *
  12321. * @method Phaser.Polygon#contains
  12322. * @param {number} x - The X value of the coordinate to test.
  12323. * @param {number} y - The Y value of the coordinate to test.
  12324. * @return {boolean} True if the coordinates are within this polygon, otherwise false.
  12325. */
  12326. contains: function (x, y) {
  12327. var inside = false;
  12328. // use some raycasting to test hits https://github.com/substack/point-in-polygon/blob/master/index.js
  12329. for (var i = 0, j = this.points.length - 1; i < this.points.length; j = i++)
  12330. {
  12331. var xi = this.points[i].x;
  12332. var yi = this.points[i].y;
  12333. var xj = this.points[j].x;
  12334. var yj = this.points[j].y;
  12335. var intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
  12336. if (intersect)
  12337. {
  12338. inside = !inside;
  12339. }
  12340. }
  12341. return inside;
  12342. }
  12343. };
  12344. Phaser.Polygon.prototype.constructor = Phaser.Polygon;
  12345. /*
  12346. * Sets and modifies the points of this polygon.
  12347. *
  12348. * @name Phaser.Polygon#points
  12349. * @property {array<Phaser.Point>|array<number>} points - The array of vertex points
  12350. */
  12351. Object.defineProperty(Phaser.Polygon.prototype, 'points', {
  12352. get: function() {
  12353. return this._points;
  12354. },
  12355. set: function(points) {
  12356. //if points isn't an array, use arguments as the array
  12357. if (!(points instanceof Array))
  12358. {
  12359. points = Array.prototype.slice.call(arguments);
  12360. }
  12361. //if this is a flat array of numbers, convert it to points
  12362. if (typeof points[0] === 'number')
  12363. {
  12364. var p = [];
  12365. for (var i = 0, len = points.length; i < len; i += 2)
  12366. {
  12367. p.push(new Phaser.Point(points[i], points[i + 1]));
  12368. }
  12369. points = p;
  12370. }
  12371. this._points = points;
  12372. }
  12373. });
  12374. /**
  12375. * Returns the area of the polygon.
  12376. *
  12377. * @name Phaser.Circle#right
  12378. * @readonly
  12379. */
  12380. Object.defineProperty(Phaser.Polygon.prototype, 'area', {
  12381. get: function() {
  12382. var p1;
  12383. var p2;
  12384. var avgHeight;
  12385. var width;
  12386. var i;
  12387. var y0 = Number.MAX_VALUE;
  12388. var area = 0;
  12389. // Find lowest boundary
  12390. for (i = 0; i < this.points.length; i++)
  12391. {
  12392. if (this.points[i].y < y0)
  12393. {
  12394. y0 = this.points[i].y;
  12395. }
  12396. }
  12397. for (i = 0; i< this.points.length; i++)
  12398. {
  12399. p1 = this.points[i];
  12400. if (i === this.points.length - 1)
  12401. {
  12402. p2 = this.points[0];
  12403. }
  12404. else
  12405. {
  12406. p2 = this.points[i+1];
  12407. }
  12408. avgHeight = ((p1.y - y0) + (p2.y - y0)) / 2;
  12409. width = p1.x - p2.x;
  12410. area += avgHeight * width;
  12411. }
  12412. return area;
  12413. }
  12414. });
  12415. // Because PIXI uses its own Polygon, we'll replace it with ours to avoid duplicating code or confusion.
  12416. PIXI.Polygon = Phaser.Polygon;
  12417. /**
  12418. * @author Richard Davey <rich@photonstorm.com>
  12419. * @copyright 2014 Photon Storm Ltd.
  12420. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  12421. */
  12422. /**
  12423. * 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.
  12424. * The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y
  12425. *
  12426. * @class Phaser.Camera
  12427. * @constructor
  12428. * @param {Phaser.Game} game - Game reference to the currently running game.
  12429. * @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera
  12430. * @param {number} x - Position of the camera on the X axis
  12431. * @param {number} y - Position of the camera on the Y axis
  12432. * @param {number} width - The width of the view rectangle
  12433. * @param {number} height - The height of the view rectangle
  12434. */
  12435. Phaser.Camera = function (game, id, x, y, width, height) {
  12436. /**
  12437. * @property {Phaser.Game} game - A reference to the currently running Game.
  12438. */
  12439. this.game = game;
  12440. /**
  12441. * @property {Phaser.World} world - A reference to the game world.
  12442. */
  12443. this.world = game.world;
  12444. /**
  12445. * @property {number} id - Reserved for future multiple camera set-ups.
  12446. * @default
  12447. */
  12448. this.id = 0;
  12449. /**
  12450. * Camera view.
  12451. * The view into the world we wish to render (by default the game dimensions).
  12452. * The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render.
  12453. * Objects outside of this view are not rendered if set to camera cull.
  12454. * @property {Phaser.Rectangle} view
  12455. */
  12456. this.view = new Phaser.Rectangle(x, y, width, height);
  12457. /**
  12458. * @property {Phaser.Rectangle} screenView - Used by Sprites to work out Camera culling.
  12459. */
  12460. this.screenView = new Phaser.Rectangle(x, y, width, height);
  12461. /**
  12462. * 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.
  12463. * 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
  12464. * at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the center of the world.
  12465. * @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere.
  12466. */
  12467. this.bounds = new Phaser.Rectangle(x, y, width, height);
  12468. /**
  12469. * @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause the camera to move.
  12470. */
  12471. this.deadzone = null;
  12472. /**
  12473. * @property {boolean} visible - Whether this camera is visible or not.
  12474. * @default
  12475. */
  12476. this.visible = true;
  12477. /**
  12478. * @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not.
  12479. */
  12480. this.atLimit = { x: false, y: false };
  12481. /**
  12482. * @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null.
  12483. * @default
  12484. */
  12485. this.target = null;
  12486. /**
  12487. * @property {number} edge - Edge property.
  12488. * @private
  12489. * @default
  12490. */
  12491. this._edge = 0;
  12492. /**
  12493. * @property {PIXI.DisplayObject} displayObject - The display object to which all game objects are added. Set by World.boot
  12494. */
  12495. this.displayObject = null;
  12496. /**
  12497. * @property {Phaser.Point} scale - The scale of the display object to which all game objects are added. Set by World.boot
  12498. */
  12499. this.scale = null;
  12500. };
  12501. /**
  12502. * @constant
  12503. * @type {number}
  12504. */
  12505. Phaser.Camera.FOLLOW_LOCKON = 0;
  12506. /**
  12507. * @constant
  12508. * @type {number}
  12509. */
  12510. Phaser.Camera.FOLLOW_PLATFORMER = 1;
  12511. /**
  12512. * @constant
  12513. * @type {number}
  12514. */
  12515. Phaser.Camera.FOLLOW_TOPDOWN = 2;
  12516. /**
  12517. * @constant
  12518. * @type {number}
  12519. */
  12520. Phaser.Camera.FOLLOW_TOPDOWN_TIGHT = 3;
  12521. Phaser.Camera.prototype = {
  12522. /**
  12523. * Tells this camera which sprite to follow.
  12524. * @method Phaser.Camera#follow
  12525. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text} target - The object you want the camera to track. Set to null to not follow anything.
  12526. * @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().
  12527. */
  12528. follow: function (target, style) {
  12529. if (typeof style === "undefined") { style = Phaser.Camera.FOLLOW_LOCKON; }
  12530. this.target = target;
  12531. var helper;
  12532. switch (style) {
  12533. case Phaser.Camera.FOLLOW_PLATFORMER:
  12534. var w = this.width / 8;
  12535. var h = this.height / 3;
  12536. this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h);
  12537. break;
  12538. case Phaser.Camera.FOLLOW_TOPDOWN:
  12539. helper = Math.max(this.width, this.height) / 4;
  12540. this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper);
  12541. break;
  12542. case Phaser.Camera.FOLLOW_TOPDOWN_TIGHT:
  12543. helper = Math.max(this.width, this.height) / 8;
  12544. this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper);
  12545. break;
  12546. case Phaser.Camera.FOLLOW_LOCKON:
  12547. this.deadzone = null;
  12548. break;
  12549. default:
  12550. this.deadzone = null;
  12551. break;
  12552. }
  12553. },
  12554. /**
  12555. * Sets the Camera follow target to null, stopping it from following an object if it's doing so.
  12556. *
  12557. * @method Phaser.Camera#unfollow
  12558. */
  12559. unfollow: function () {
  12560. this.target = null;
  12561. },
  12562. /**
  12563. * Move the camera focus on a display object instantly.
  12564. * @method Phaser.Camera#focusOn
  12565. * @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties.
  12566. */
  12567. focusOn: function (displayObject) {
  12568. this.setPosition(Math.round(displayObject.x - this.view.halfWidth), Math.round(displayObject.y - this.view.halfHeight));
  12569. },
  12570. /**
  12571. * Move the camera focus on a location instantly.
  12572. * @method Phaser.Camera#focusOnXY
  12573. * @param {number} x - X position.
  12574. * @param {number} y - Y position.
  12575. */
  12576. focusOnXY: function (x, y) {
  12577. this.setPosition(Math.round(x - this.view.halfWidth), Math.round(y - this.view.halfHeight));
  12578. },
  12579. /**
  12580. * Update focusing and scrolling.
  12581. * @method Phaser.Camera#update
  12582. */
  12583. update: function () {
  12584. if (this.target)
  12585. {
  12586. this.updateTarget();
  12587. }
  12588. if (this.bounds)
  12589. {
  12590. this.checkBounds();
  12591. }
  12592. this.displayObject.position.x = -this.view.x;
  12593. this.displayObject.position.y = -this.view.y;
  12594. },
  12595. /**
  12596. * Internal method
  12597. * @method Phaser.Camera#updateTarget
  12598. * @private
  12599. */
  12600. updateTarget: function () {
  12601. if (this.deadzone)
  12602. {
  12603. this._edge = this.target.x - this.view.x;
  12604. if (this._edge < this.deadzone.left)
  12605. {
  12606. this.view.x = this.target.x - this.deadzone.left;
  12607. }
  12608. else if (this._edge > this.deadzone.right)
  12609. {
  12610. this.view.x = this.target.x - this.deadzone.right;
  12611. }
  12612. this._edge = this.target.y - this.view.y;
  12613. if (this._edge < this.deadzone.top)
  12614. {
  12615. this.view.y = this.target.y - this.deadzone.top;
  12616. }
  12617. else if (this._edge > this.deadzone.bottom)
  12618. {
  12619. this.view.y = this.target.y - this.deadzone.bottom;
  12620. }
  12621. }
  12622. else
  12623. {
  12624. this.view.x = this.target.x - this.view.halfWidth;
  12625. this.view.y = this.target.y - this.view.halfHeight;
  12626. }
  12627. },
  12628. /**
  12629. * Update the Camera bounds to match the game world.
  12630. * @method Phaser.Camera#setBoundsToWorld
  12631. */
  12632. setBoundsToWorld: function () {
  12633. this.bounds.setTo(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height);
  12634. },
  12635. /**
  12636. * Method called to ensure the camera doesn't venture outside of the game world.
  12637. * @method Phaser.Camera#checkWorldBounds
  12638. */
  12639. checkBounds: function () {
  12640. this.atLimit.x = false;
  12641. this.atLimit.y = false;
  12642. // Make sure we didn't go outside the cameras bounds
  12643. if (this.view.x <= this.bounds.x)
  12644. {
  12645. this.atLimit.x = true;
  12646. this.view.x = this.bounds.x;
  12647. }
  12648. if (this.view.right >= this.bounds.right)
  12649. {
  12650. this.atLimit.x = true;
  12651. this.view.x = this.bounds.right - this.width;
  12652. }
  12653. if (this.view.y <= this.bounds.top)
  12654. {
  12655. this.atLimit.y = true;
  12656. this.view.y = this.bounds.top;
  12657. }
  12658. if (this.view.bottom >= this.bounds.bottom)
  12659. {
  12660. this.atLimit.y = true;
  12661. this.view.y = this.bounds.bottom - this.height;
  12662. }
  12663. this.view.floor();
  12664. },
  12665. /**
  12666. * A helper function to set both the X and Y properties of the camera at once
  12667. * without having to use game.camera.x and game.camera.y.
  12668. *
  12669. * @method Phaser.Camera#setPosition
  12670. * @param {number} x - X position.
  12671. * @param {number} y - Y position.
  12672. */
  12673. setPosition: function (x, y) {
  12674. this.view.x = x;
  12675. this.view.y = y;
  12676. if (this.bounds)
  12677. {
  12678. this.checkBounds();
  12679. }
  12680. },
  12681. /**
  12682. * Sets the size of the view rectangle given the width and height in parameters.
  12683. *
  12684. * @method Phaser.Camera#setSize
  12685. * @param {number} width - The desired width.
  12686. * @param {number} height - The desired height.
  12687. */
  12688. setSize: function (width, height) {
  12689. this.view.width = width;
  12690. this.view.height = height;
  12691. },
  12692. /**
  12693. * Resets the camera back to 0,0 and un-follows any object it may have been tracking.
  12694. *
  12695. * @method Phaser.Camera#reset
  12696. */
  12697. reset: function () {
  12698. this.target = null;
  12699. this.view.x = 0;
  12700. this.view.y = 0;
  12701. }
  12702. };
  12703. Phaser.Camera.prototype.constructor = Phaser.Camera;
  12704. /**
  12705. * The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds.
  12706. * @name Phaser.Camera#x
  12707. * @property {number} x - Gets or sets the cameras x position.
  12708. */
  12709. Object.defineProperty(Phaser.Camera.prototype, "x", {
  12710. get: function () {
  12711. return this.view.x;
  12712. },
  12713. set: function (value) {
  12714. this.view.x = value;
  12715. if (this.bounds)
  12716. {
  12717. this.checkBounds();
  12718. }
  12719. }
  12720. });
  12721. /**
  12722. * The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds.
  12723. * @name Phaser.Camera#y
  12724. * @property {number} y - Gets or sets the cameras y position.
  12725. */
  12726. Object.defineProperty(Phaser.Camera.prototype, "y", {
  12727. get: function () {
  12728. return this.view.y;
  12729. },
  12730. set: function (value) {
  12731. this.view.y = value;
  12732. if (this.bounds)
  12733. {
  12734. this.checkBounds();
  12735. }
  12736. }
  12737. });
  12738. /**
  12739. * The Cameras width. By default this is the same as the Game size and should not be adjusted for now.
  12740. * @name Phaser.Camera#width
  12741. * @property {number} width - Gets or sets the cameras width.
  12742. */
  12743. Object.defineProperty(Phaser.Camera.prototype, "width", {
  12744. get: function () {
  12745. return this.view.width;
  12746. },
  12747. set: function (value) {
  12748. this.view.width = value;
  12749. }
  12750. });
  12751. /**
  12752. * The Cameras height. By default this is the same as the Game size and should not be adjusted for now.
  12753. * @name Phaser.Camera#height
  12754. * @property {number} height - Gets or sets the cameras height.
  12755. */
  12756. Object.defineProperty(Phaser.Camera.prototype, "height", {
  12757. get: function () {
  12758. return this.view.height;
  12759. },
  12760. set: function (value) {
  12761. this.view.height = value;
  12762. }
  12763. });
  12764. /**
  12765. * @author Richard Davey <rich@photonstorm.com>
  12766. * @copyright 2014 Photon Storm Ltd.
  12767. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  12768. */
  12769. /**
  12770. * This is a base State class which can be extended if you are creating your own game.
  12771. * It provides quick access to common functions such as the camera, cache, input, match, sound and more.
  12772. *
  12773. * @class Phaser.State
  12774. * @constructor
  12775. */
  12776. Phaser.State = function () {
  12777. /**
  12778. * @property {Phaser.Game} game - This is a reference to the currently running Game.
  12779. */
  12780. this.game = null;
  12781. /**
  12782. * @property {Phaser.GameObjectFactory} add - A reference to the GameObjectFactory which can be used to add new objects to the World.
  12783. */
  12784. this.add = null;
  12785. /**
  12786. * @property {Phaser.GameObjectCreator} make - A reference to the GameObjectCreator which can be used to make new objects.
  12787. */
  12788. this.make = null;
  12789. /**
  12790. * @property {Phaser.Camera} camera - A handy reference to World.camera.
  12791. */
  12792. this.camera = null;
  12793. /**
  12794. * @property {Phaser.Cache} cache - A reference to the game cache which contains any loaded or generated assets, such as images, sound and more.
  12795. */
  12796. this.cache = null;
  12797. /**
  12798. * @property {Phaser.Input} input - A reference to the Input Manager.
  12799. */
  12800. this.input = null;
  12801. /**
  12802. * @property {Phaser.Loader} load - A reference to the Loader, which you mostly use in the preload method of your state to load external assets.
  12803. */
  12804. this.load = null;
  12805. /**
  12806. * @property {Phaser.Math} math - A reference to Math class with lots of helpful functions.
  12807. */
  12808. this.math = null;
  12809. /**
  12810. * @property {Phaser.SoundManager} sound - A reference to the Sound Manager which can create, play and stop sounds, as well as adjust global volume.
  12811. */
  12812. this.sound = null;
  12813. /**
  12814. * @property {Phaser.ScaleManager} scale - A reference to the Scale Manager which controls the way the game scales on different displays.
  12815. */
  12816. this.scale = null;
  12817. /**
  12818. * @property {Phaser.Stage} stage - A reference to the Stage.
  12819. */
  12820. this.stage = null;
  12821. /**
  12822. * @property {Phaser.Time} time - A reference to the game clock and timed events system.
  12823. */
  12824. this.time = null;
  12825. /**
  12826. * @property {Phaser.TweenManager} tweens - A reference to the tween manager.
  12827. */
  12828. this.tweens = null;
  12829. /**
  12830. * @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.
  12831. */
  12832. this.world = null;
  12833. /**
  12834. * @property {Phaser.Particles} particles - The Particle Manager. It is called during the core gameloop and updates any Particle Emitters it has created.
  12835. */
  12836. this.particles = null;
  12837. /**
  12838. * @property {Phaser.Physics} physics - A reference to the physics manager which looks after the different physics systems available within Phaser.
  12839. */
  12840. this.physics = null;
  12841. /**
  12842. * @property {Phaser.RandomDataGenerator} rnd - A reference to the seeded and repeatable random data generator.
  12843. */
  12844. this.rnd = null;
  12845. };
  12846. Phaser.State.prototype = {
  12847. /**
  12848. * preload is called first. Normally you'd use this to load your game assets (or those needed for the current State)
  12849. * You shouldn't create any objects in this method that require assets that you're also loading in this method, as
  12850. * they won't yet be available.
  12851. *
  12852. * @method Phaser.State#preload
  12853. */
  12854. preload: function () {
  12855. },
  12856. /**
  12857. * loadUpdate is called during the Loader process. This only happens if you've set one or more assets to load in the preload method.
  12858. *
  12859. * @method Phaser.State#loadUpdate
  12860. */
  12861. loadUpdate: function () {
  12862. },
  12863. /**
  12864. * loadRender is called during the Loader process. This only happens if you've set one or more assets to load in the preload method.
  12865. * The difference between loadRender and render is that any objects you render in this method you must be sure their assets exist.
  12866. *
  12867. * @method Phaser.State#loadRender
  12868. */
  12869. loadRender: function () {
  12870. },
  12871. /**
  12872. * create is called once preload has completed, this includes the loading of any assets from the Loader.
  12873. * If you don't have a preload method then create is the first method called in your State.
  12874. *
  12875. * @method Phaser.State#create
  12876. */
  12877. create: function () {
  12878. },
  12879. /**
  12880. * The update method is left empty for your own use.
  12881. * It is called during the core game loop AFTER debug, physics, plugins and the Stage have had their preUpdate methods called.
  12882. * If is called BEFORE Stage, Tweens, Sounds, Input, Physics, Particles and Plugins have had their postUpdate methods called.
  12883. *
  12884. * @method Phaser.State#update
  12885. */
  12886. update: function () {
  12887. },
  12888. /**
  12889. * Nearly all display objects in Phaser render automatically, you don't need to tell them to render.
  12890. * However the render method is called AFTER the game renderer and plugins have rendered, so you're able to do any
  12891. * final post-processing style effects here. Note that this happens before plugins postRender takes place.
  12892. *
  12893. * @method Phaser.State#render
  12894. */
  12895. render: function () {
  12896. },
  12897. /**
  12898. * This method will be called if the core game loop is paused.
  12899. *
  12900. * @method Phaser.State#paused
  12901. */
  12902. paused: function () {
  12903. },
  12904. /**
  12905. * pauseUpdate is called while the game is paused instead of preUpdate, update and postUpdate.
  12906. *
  12907. * @method Phaser.State#pauseUpdate
  12908. */
  12909. pauseUpdate: function () {
  12910. },
  12911. /**
  12912. * This method will be called when the State is shutdown (i.e. you switch to another state from this one).
  12913. *
  12914. * @method Phaser.State#shutdown
  12915. */
  12916. shutdown: function () {
  12917. }
  12918. };
  12919. Phaser.State.prototype.constructor = Phaser.State;
  12920. /* jshint newcap: false */
  12921. /**
  12922. * @author Richard Davey <rich@photonstorm.com>
  12923. * @copyright 2014 Photon Storm Ltd.
  12924. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  12925. */
  12926. /**
  12927. * The State Manager is responsible for loading, setting up and switching game states.
  12928. *
  12929. * @class Phaser.StateManager
  12930. * @constructor
  12931. * @param {Phaser.Game} game - A reference to the currently running game.
  12932. * @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with.
  12933. */
  12934. Phaser.StateManager = function (game, pendingState) {
  12935. /**
  12936. * @property {Phaser.Game} game - A reference to the currently running game.
  12937. */
  12938. this.game = game;
  12939. /**
  12940. * @property {Object} states - The object containing Phaser.States.
  12941. */
  12942. this.states = {};
  12943. /**
  12944. * @property {Phaser.State} _pendingState - The state to be switched to in the next frame.
  12945. * @private
  12946. */
  12947. this._pendingState = null;
  12948. if (typeof pendingState !== 'undefined' && pendingState !== null)
  12949. {
  12950. this._pendingState = pendingState;
  12951. }
  12952. /**
  12953. * @property {boolean} _clearWorld - Clear the world when we switch state?
  12954. * @private
  12955. */
  12956. this._clearWorld = false;
  12957. /**
  12958. * @property {boolean} _clearCache - Clear the cache when we switch state?
  12959. * @private
  12960. */
  12961. this._clearCache = false;
  12962. /**
  12963. * @property {boolean} _created - Flag that sets if the State has been created or not.
  12964. * @private
  12965. */
  12966. this._created = false;
  12967. /**
  12968. * @property {array} _args - Temporary container when you pass vars from one State to another.
  12969. * @private
  12970. */
  12971. this._args = [];
  12972. /**
  12973. * @property {string} current - The current active State object (defaults to null).
  12974. */
  12975. this.current = '';
  12976. /**
  12977. * @property {function} onInitCallback - This will be called when the state is started (i.e. set as the current active state).
  12978. */
  12979. this.onInitCallback = null;
  12980. /**
  12981. * @property {function} onPreloadCallback - This will be called when init states (loading assets...).
  12982. */
  12983. this.onPreloadCallback = null;
  12984. /**
  12985. * @property {function} onCreateCallback - This will be called when create states (setup states...).
  12986. */
  12987. this.onCreateCallback = null;
  12988. /**
  12989. * @property {function} onUpdateCallback - This will be called when State is updated, this doesn't happen during load (@see onLoadUpdateCallback).
  12990. */
  12991. this.onUpdateCallback = null;
  12992. /**
  12993. * @property {function} onRenderCallback - This will be called when the State is rendered, this doesn't happen during load (see onLoadRenderCallback).
  12994. */
  12995. this.onRenderCallback = null;
  12996. /**
  12997. * @property {function} onPreRenderCallback - This will be called before the State is rendered and before the stage is cleared.
  12998. */
  12999. this.onPreRenderCallback = null;
  13000. /**
  13001. * @property {function} onLoadUpdateCallback - This will be called when the State is updated but only during the load process.
  13002. */
  13003. this.onLoadUpdateCallback = null;
  13004. /**
  13005. * @property {function} onLoadRenderCallback - This will be called when the State is rendered but only during the load process.
  13006. */
  13007. this.onLoadRenderCallback = null;
  13008. /**
  13009. * @property {function} onPausedCallback - This will be called once each time the game is paused.
  13010. */
  13011. this.onPausedCallback = null;
  13012. /**
  13013. * @property {function} onResumedCallback - This will be called once each time the game is resumed from a paused state.
  13014. */
  13015. this.onResumedCallback = null;
  13016. /**
  13017. * @property {function} onPauseUpdateCallback - This will be called every frame while the game is paused.
  13018. */
  13019. this.onPauseUpdateCallback = null;
  13020. /**
  13021. * @property {function} onShutDownCallback - This will be called when the state is shut down (i.e. swapped to another state).
  13022. */
  13023. this.onShutDownCallback = null;
  13024. };
  13025. Phaser.StateManager.prototype = {
  13026. /**
  13027. * The Boot handler is called by Phaser.Game when it first starts up.
  13028. * @method Phaser.StateManager#boot
  13029. * @private
  13030. */
  13031. boot: function () {
  13032. this.game.onPause.add(this.pause, this);
  13033. this.game.onResume.add(this.resume, this);
  13034. this.game.load.onLoadComplete.add(this.loadComplete, this);
  13035. if (this._pendingState !== null)
  13036. {
  13037. if (typeof this._pendingState === 'string')
  13038. {
  13039. // State was already added, so just start it
  13040. this.start(this._pendingState, false, false);
  13041. }
  13042. else
  13043. {
  13044. this.add('default', this._pendingState, true);
  13045. }
  13046. }
  13047. },
  13048. /**
  13049. * Adds a new State into the StateManager. You must give each State a unique key by which you'll identify it.
  13050. * The State can be either a Phaser.State object (or an object that extends it), a plain JavaScript object or a function.
  13051. * If a function is given a new state object will be created by calling it.
  13052. *
  13053. * @method Phaser.StateManager#add
  13054. * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1".
  13055. * @param {Phaser.State|object|function} state - The state you want to switch to.
  13056. * @param {boolean} [autoStart=false] - If true the State will be started immediately after adding it.
  13057. */
  13058. add: function (key, state, autoStart) {
  13059. if (typeof autoStart === "undefined") { autoStart = false; }
  13060. var newState;
  13061. if (state instanceof Phaser.State)
  13062. {
  13063. newState = state;
  13064. }
  13065. else if (typeof state === 'object')
  13066. {
  13067. newState = state;
  13068. newState.game = this.game;
  13069. }
  13070. else if (typeof state === 'function')
  13071. {
  13072. newState = new state(this.game);
  13073. }
  13074. this.states[key] = newState;
  13075. if (autoStart)
  13076. {
  13077. if (this.game.isBooted)
  13078. {
  13079. this.start(key);
  13080. }
  13081. else
  13082. {
  13083. this._pendingState = key;
  13084. }
  13085. }
  13086. return newState;
  13087. },
  13088. /**
  13089. * Delete the given state.
  13090. * @method Phaser.StateManager#remove
  13091. * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1".
  13092. */
  13093. remove: function (key) {
  13094. if (this.current === key)
  13095. {
  13096. this.callbackContext = null;
  13097. this.onInitCallback = null;
  13098. this.onShutDownCallback = null;
  13099. this.onPreloadCallback = null;
  13100. this.onLoadRenderCallback = null;
  13101. this.onLoadUpdateCallback = null;
  13102. this.onCreateCallback = null;
  13103. this.onUpdateCallback = null;
  13104. this.onRenderCallback = null;
  13105. this.onPausedCallback = null;
  13106. this.onResumedCallback = null;
  13107. this.onPauseUpdateCallback = null;
  13108. }
  13109. delete this.states[key];
  13110. },
  13111. /**
  13112. * 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.
  13113. *
  13114. * @method Phaser.StateManager#start
  13115. * @param {string} key - The key of the state you want to start.
  13116. * @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)
  13117. * @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.
  13118. * @param {...*} parameter - Additional parameters that will be passed to the State.init function (if it has one).
  13119. */
  13120. start: function (key, clearWorld, clearCache) {
  13121. if (typeof clearWorld === "undefined") { clearWorld = true; }
  13122. if (typeof clearCache === "undefined") { clearCache = false; }
  13123. if (this.checkState(key))
  13124. {
  13125. // Place the state in the queue. It will be started the next time the game loop starts.
  13126. this._pendingState = key;
  13127. this._clearWorld = clearWorld;
  13128. this._clearCache = clearCache;
  13129. if (arguments.length > 3)
  13130. {
  13131. this._args = Array.prototype.splice.call(arguments, 3);
  13132. }
  13133. }
  13134. },
  13135. /**
  13136. * Restarts the current State. State.shutDown will be called (if it exists) before the State is restarted.
  13137. *
  13138. * @method Phaser.StateManager#restart
  13139. * @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)
  13140. * @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.
  13141. * @param {...*} parameter - Additional parameters that will be passed to the State.init function if it has one.
  13142. */
  13143. restart: function (clearWorld, clearCache) {
  13144. if (typeof clearWorld === "undefined") { clearWorld = true; }
  13145. if (typeof clearCache === "undefined") { clearCache = false; }
  13146. // Place the state in the queue. It will be started the next time the game loop starts.
  13147. this._pendingState = this.current;
  13148. this._clearWorld = clearWorld;
  13149. this._clearCache = clearCache;
  13150. if (arguments.length > 2)
  13151. {
  13152. this._args = Array.prototype.splice.call(arguments, 2);
  13153. }
  13154. },
  13155. /**
  13156. * Used by onInit and onShutdown when those functions don't exist on the state
  13157. * @method Phaser.StateManager#dummy
  13158. * @private
  13159. */
  13160. dummy: function () {
  13161. },
  13162. /**
  13163. * preUpdate is called right at the start of the game loop. It is responsible for changing to a new state that was requested previously.
  13164. *
  13165. * @method Phaser.StateManager#preUpdate
  13166. */
  13167. preUpdate: function () {
  13168. if (this._pendingState && this.game.isBooted)
  13169. {
  13170. // Already got a state running?
  13171. if (this.current)
  13172. {
  13173. if (this.onShutDownCallback)
  13174. {
  13175. this.onShutDownCallback.call(this.callbackContext, this.game);
  13176. }
  13177. this.game.tweens.removeAll();
  13178. this.game.camera.reset();
  13179. this.game.input.reset(true);
  13180. this.game.physics.clear();
  13181. this.game.time.removeAll();
  13182. if (this._clearWorld)
  13183. {
  13184. this.game.world.shutdown();
  13185. if (this._clearCache === true)
  13186. {
  13187. this.game.cache.destroy();
  13188. }
  13189. }
  13190. }
  13191. this.setCurrentState(this._pendingState);
  13192. if (this.onPreloadCallback)
  13193. {
  13194. this.game.load.reset();
  13195. this.onPreloadCallback.call(this.callbackContext, this.game);
  13196. // Is the loader empty?
  13197. if (this.game.load.totalQueuedFiles() === 0 && this.game.load.totalQueuedPacks() === 0)
  13198. {
  13199. this.loadComplete();
  13200. }
  13201. else
  13202. {
  13203. // Start the loader going as we have something in the queue
  13204. this.game.load.start();
  13205. }
  13206. }
  13207. else
  13208. {
  13209. // No init? Then there was nothing to load either
  13210. this.loadComplete();
  13211. }
  13212. if (this.current === this._pendingState)
  13213. {
  13214. this._pendingState = null;
  13215. }
  13216. }
  13217. },
  13218. /**
  13219. * 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.
  13220. *
  13221. * @method Phaser.StateManager#checkState
  13222. * @param {string} key - The key of the state you want to check.
  13223. * @return {boolean} true if the State has the required functions, otherwise false.
  13224. */
  13225. checkState: function (key) {
  13226. if (this.states[key])
  13227. {
  13228. var valid = false;
  13229. if (this.states[key]['preload']) { valid = true; }
  13230. if (this.states[key]['create']) { valid = true; }
  13231. if (this.states[key]['update']) { valid = true; }
  13232. if (this.states[key]['render']) { valid = true; }
  13233. if (valid === false)
  13234. {
  13235. console.warn("Invalid Phaser State object given. Must contain at least a one of the required functions: preload, create, update or render");
  13236. return false;
  13237. }
  13238. return true;
  13239. }
  13240. else
  13241. {
  13242. console.warn("Phaser.StateManager - No state found with the key: " + key);
  13243. return false;
  13244. }
  13245. },
  13246. /**
  13247. * Links game properties to the State given by the key.
  13248. *
  13249. * @method Phaser.StateManager#link
  13250. * @param {string} key - State key.
  13251. * @protected
  13252. */
  13253. link: function (key) {
  13254. this.states[key].game = this.game;
  13255. this.states[key].add = this.game.add;
  13256. this.states[key].make = this.game.make;
  13257. this.states[key].camera = this.game.camera;
  13258. this.states[key].cache = this.game.cache;
  13259. this.states[key].input = this.game.input;
  13260. this.states[key].load = this.game.load;
  13261. this.states[key].math = this.game.math;
  13262. this.states[key].sound = this.game.sound;
  13263. this.states[key].scale = this.game.scale;
  13264. this.states[key].state = this;
  13265. this.states[key].stage = this.game.stage;
  13266. this.states[key].time = this.game.time;
  13267. this.states[key].tweens = this.game.tweens;
  13268. this.states[key].world = this.game.world;
  13269. this.states[key].particles = this.game.particles;
  13270. this.states[key].rnd = this.game.rnd;
  13271. this.states[key].physics = this.game.physics;
  13272. },
  13273. /**
  13274. * Sets the current State. Should not be called directly (use StateManager.start)
  13275. *
  13276. * @method Phaser.StateManager#setCurrentState
  13277. * @param {string} key - State key.
  13278. * @private
  13279. */
  13280. setCurrentState: function (key) {
  13281. this.callbackContext = this.states[key];
  13282. this.link(key);
  13283. // Used when the state is set as being the current active state
  13284. this.onInitCallback = this.states[key]['init'] || this.dummy;
  13285. this.onPreloadCallback = this.states[key]['preload'] || null;
  13286. this.onLoadRenderCallback = this.states[key]['loadRender'] || null;
  13287. this.onLoadUpdateCallback = this.states[key]['loadUpdate'] || null;
  13288. this.onCreateCallback = this.states[key]['create'] || null;
  13289. this.onUpdateCallback = this.states[key]['update'] || null;
  13290. this.onPreRenderCallback = this.states[key]['preRender'] || null;
  13291. this.onRenderCallback = this.states[key]['render'] || null;
  13292. this.onPausedCallback = this.states[key]['paused'] || null;
  13293. this.onResumedCallback = this.states[key]['resumed'] || null;
  13294. this.onPauseUpdateCallback = this.states[key]['pauseUpdate'] || null;
  13295. // Used when the state is no longer the current active state
  13296. this.onShutDownCallback = this.states[key]['shutdown'] || this.dummy;
  13297. this.current = key;
  13298. this._created = false;
  13299. this.onInitCallback.apply(this.callbackContext, this._args);
  13300. this._args = [];
  13301. },
  13302. /**
  13303. * Gets the current State.
  13304. *
  13305. * @method Phaser.StateManager#getCurrentState
  13306. * @return Phaser.State
  13307. * @public
  13308. */
  13309. getCurrentState: function() {
  13310. return this.states[this.current];
  13311. },
  13312. /**
  13313. * @method Phaser.StateManager#loadComplete
  13314. * @protected
  13315. */
  13316. loadComplete: function () {
  13317. if (this._created === false && this.onCreateCallback)
  13318. {
  13319. this._created = true;
  13320. this.onCreateCallback.call(this.callbackContext, this.game);
  13321. }
  13322. else
  13323. {
  13324. this._created = true;
  13325. }
  13326. },
  13327. /**
  13328. * @method Phaser.StateManager#pause
  13329. * @protected
  13330. */
  13331. pause: function () {
  13332. if (this._created && this.onPausedCallback)
  13333. {
  13334. this.onPausedCallback.call(this.callbackContext, this.game);
  13335. }
  13336. },
  13337. /**
  13338. * @method Phaser.StateManager#resume
  13339. * @protected
  13340. */
  13341. resume: function () {
  13342. if (this._created && this.onResumedCallback)
  13343. {
  13344. this.onResumedCallback.call(this.callbackContext, this.game);
  13345. }
  13346. },
  13347. /**
  13348. * @method Phaser.StateManager#update
  13349. * @protected
  13350. */
  13351. update: function () {
  13352. if (this._created && this.onUpdateCallback)
  13353. {
  13354. this.onUpdateCallback.call(this.callbackContext, this.game);
  13355. }
  13356. else
  13357. {
  13358. if (this.onLoadUpdateCallback)
  13359. {
  13360. this.onLoadUpdateCallback.call(this.callbackContext, this.game);
  13361. }
  13362. }
  13363. },
  13364. /**
  13365. * @method Phaser.StateManager#pauseUpdate
  13366. * @protected
  13367. */
  13368. pauseUpdate: function () {
  13369. if (this._created && this.onPauseUpdateCallback)
  13370. {
  13371. this.onPauseUpdateCallback.call(this.callbackContext, this.game);
  13372. }
  13373. else
  13374. {
  13375. if (this.onLoadUpdateCallback)
  13376. {
  13377. this.onLoadUpdateCallback.call(this.callbackContext, this.game);
  13378. }
  13379. }
  13380. },
  13381. /**
  13382. * @method Phaser.StateManager#preRender
  13383. * @protected
  13384. */
  13385. preRender: function () {
  13386. if (this.onPreRenderCallback)
  13387. {
  13388. this.onPreRenderCallback.call(this.callbackContext, this.game);
  13389. }
  13390. },
  13391. /**
  13392. * @method Phaser.StateManager#render
  13393. * @protected
  13394. */
  13395. render: function () {
  13396. if (this._created && this.onRenderCallback)
  13397. {
  13398. if (this.game.renderType === Phaser.CANVAS)
  13399. {
  13400. this.game.context.save();
  13401. this.game.context.setTransform(1, 0, 0, 1, 0, 0);
  13402. }
  13403. this.onRenderCallback.call(this.callbackContext, this.game);
  13404. if (this.game.renderType === Phaser.CANVAS)
  13405. {
  13406. this.game.context.restore();
  13407. }
  13408. }
  13409. else
  13410. {
  13411. if (this.onLoadRenderCallback)
  13412. {
  13413. this.onLoadRenderCallback.call(this.callbackContext, this.game);
  13414. }
  13415. }
  13416. },
  13417. /**
  13418. * Removes all StateManager callback references to the State object, nulls the game reference and clears the States object.
  13419. * You don't recover from this without rebuilding the Phaser instance again.
  13420. * @method Phaser.StateManager#destroy
  13421. */
  13422. destroy: function () {
  13423. this.callbackContext = null;
  13424. this.onInitCallback = null;
  13425. this.onShutDownCallback = null;
  13426. this.onPreloadCallback = null;
  13427. this.onLoadRenderCallback = null;
  13428. this.onLoadUpdateCallback = null;
  13429. this.onCreateCallback = null;
  13430. this.onUpdateCallback = null;
  13431. this.onRenderCallback = null;
  13432. this.onPausedCallback = null;
  13433. this.onResumedCallback = null;
  13434. this.onPauseUpdateCallback = null;
  13435. this.game = null;
  13436. this.states = {};
  13437. this._pendingState = null;
  13438. }
  13439. };
  13440. Phaser.StateManager.prototype.constructor = Phaser.StateManager;
  13441. /**
  13442. * @author Richard Davey <rich@photonstorm.com>
  13443. * @copyright 2014 Photon Storm Ltd.
  13444. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  13445. */
  13446. /**
  13447. * A basic linked list data structure.
  13448. *
  13449. * @class Phaser.LinkedList
  13450. * @constructor
  13451. */
  13452. Phaser.LinkedList = function () {
  13453. /**
  13454. * @property {object} next - Next element in the list.
  13455. * @default
  13456. */
  13457. this.next = null;
  13458. /**
  13459. * @property {object} prev - Previous element in the list.
  13460. * @default
  13461. */
  13462. this.prev = null;
  13463. /**
  13464. * @property {object} first - First element in the list.
  13465. * @default
  13466. */
  13467. this.first = null;
  13468. /**
  13469. * @property {object} last - Last element in the list.
  13470. * @default
  13471. */
  13472. this.last = null;
  13473. /**
  13474. * @property {number} total - Number of elements in the list.
  13475. * @default
  13476. */
  13477. this.total = 0;
  13478. };
  13479. Phaser.LinkedList.prototype = {
  13480. /**
  13481. * Adds a new element to this linked list.
  13482. *
  13483. * @method Phaser.LinkedList#add
  13484. * @param {object} child - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through.
  13485. * @return {object} The child that was added.
  13486. */
  13487. add: function (child) {
  13488. // If the list is empty
  13489. if (this.total === 0 && this.first === null && this.last === null)
  13490. {
  13491. this.first = child;
  13492. this.last = child;
  13493. this.next = child;
  13494. child.prev = this;
  13495. this.total++;
  13496. return child;
  13497. }
  13498. // Gets appended to the end of the list, regardless of anything, and it won't have any children of its own (non-nested list)
  13499. this.last.next = child;
  13500. child.prev = this.last;
  13501. this.last = child;
  13502. this.total++;
  13503. return child;
  13504. },
  13505. /**
  13506. * Resets the first, last, next and previous node pointers in this list.
  13507. *
  13508. * @method Phaser.LinkedList#reset
  13509. */
  13510. reset: function () {
  13511. this.first = null;
  13512. this.last = null;
  13513. this.next = null;
  13514. this.prev = null;
  13515. this.total = 0;
  13516. },
  13517. /**
  13518. * Removes the given element from this linked list if it exists.
  13519. *
  13520. * @method Phaser.LinkedList#remove
  13521. * @param {object} child - The child to be removed from the list.
  13522. */
  13523. remove: function (child) {
  13524. if (this.total === 1)
  13525. {
  13526. this.reset();
  13527. child.next = child.prev = null;
  13528. return;
  13529. }
  13530. if (child === this.first)
  13531. {
  13532. // It was 'first', make 'first' point to first.next
  13533. this.first = this.first.next;
  13534. }
  13535. else if (child === this.last)
  13536. {
  13537. // It was 'last', make 'last' point to last.prev
  13538. this.last = this.last.prev;
  13539. }
  13540. if (child.prev)
  13541. {
  13542. // make child.prev.next point to childs.next instead of child
  13543. child.prev.next = child.next;
  13544. }
  13545. if (child.next)
  13546. {
  13547. // make child.next.prev point to child.prev instead of child
  13548. child.next.prev = child.prev;
  13549. }
  13550. child.next = child.prev = null;
  13551. if (this.first === null )
  13552. {
  13553. this.last = null;
  13554. }
  13555. this.total--;
  13556. },
  13557. /**
  13558. * Calls a function on all members of this list, using the member as the context for the callback.
  13559. * The function must exist on the member.
  13560. *
  13561. * @method Phaser.LinkedList#callAll
  13562. * @param {function} callback - The function to call.
  13563. */
  13564. callAll: function (callback) {
  13565. if (!this.first || !this.last)
  13566. {
  13567. return;
  13568. }
  13569. var entity = this.first;
  13570. do
  13571. {
  13572. if (entity && entity[callback])
  13573. {
  13574. entity[callback].call(entity);
  13575. }
  13576. entity = entity.next;
  13577. }
  13578. while(entity != this.last.next);
  13579. }
  13580. };
  13581. Phaser.LinkedList.prototype.constructor = Phaser.LinkedList;
  13582. /**
  13583. * @author Richard Davey <rich@photonstorm.com>
  13584. * @copyright 2014 Photon Storm Ltd.
  13585. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  13586. */
  13587. /**
  13588. * A set data structure. Allows items to add themselves to and remove themselves from the set. Items can only exist once in the set.
  13589. *
  13590. * @class Phaser.ArrayList
  13591. * @constructor
  13592. */
  13593. Phaser.ArrayList = function () {
  13594. /**
  13595. * @property {number} total - Number of objects in the list.
  13596. * @default
  13597. */
  13598. this.total = 0;
  13599. /**
  13600. * @property {number} position - Current cursor position.
  13601. * @default
  13602. */
  13603. this.position = 0;
  13604. /**
  13605. * @property {array} list - The list.
  13606. */
  13607. this.list = [];
  13608. };
  13609. Phaser.ArrayList.prototype = {
  13610. /**
  13611. * Adds a new element to this list. The item can only exist in the list once.
  13612. *
  13613. * @method Phaser.ArrayList#add
  13614. * @param {object} child - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through.
  13615. * @return {object} The child that was added.
  13616. */
  13617. add: function (child) {
  13618. if (!this.exists(child))
  13619. {
  13620. this.list.push(child);
  13621. this.total++;
  13622. }
  13623. return child;
  13624. },
  13625. /**
  13626. * Gets the index of the child in the list, or -1 if it isn't in the list.
  13627. *
  13628. * @method Phaser.ArrayList#getIndex
  13629. * @param {object} child - The element to get the list index for.
  13630. * @return {number} The index of the child or -1 if not found.
  13631. */
  13632. getIndex: function (child) {
  13633. return this.list.indexOf(child);
  13634. },
  13635. /**
  13636. * Checks for the child within this list.
  13637. *
  13638. * @method Phaser.ArrayList#exists
  13639. * @param {object} child - The element to get the list index for.
  13640. * @return {boolean} True if the child is found in the list, otherwise false.
  13641. */
  13642. exists: function (child) {
  13643. return (this.list.indexOf(child) > -1);
  13644. },
  13645. /**
  13646. * Resets the list length and drops all items in the list.
  13647. *
  13648. * @method Phaser.ArrayList#reset
  13649. */
  13650. reset: function () {
  13651. this.list.length = 0;
  13652. this.total = 0;
  13653. },
  13654. /**
  13655. * Removes the given element from this list if it exists.
  13656. *
  13657. * @method Phaser.ArrayList#remove
  13658. * @param {object} child - The child to be removed from the list.
  13659. * @return {object} child - The child that was removed.
  13660. */
  13661. remove: function (child) {
  13662. var idx = this.list.indexOf(child);
  13663. if (idx > -1)
  13664. {
  13665. this.list.splice(idx, 1);
  13666. this.total--;
  13667. return child;
  13668. }
  13669. },
  13670. /**
  13671. * Sets the property `key` to the given value on all members of this list.
  13672. *
  13673. * @method Phaser.ArrayList#setAll
  13674. * @param {object} key - The object on the child to set.
  13675. * @param {*} value - The value to set the property to.
  13676. */
  13677. setAll: function (key, value) {
  13678. var i = this.list.length;
  13679. while (i--)
  13680. {
  13681. if (this.list[i] && this.list[i][key])
  13682. {
  13683. this.list[i][key] = value;
  13684. }
  13685. }
  13686. },
  13687. /**
  13688. * Calls a function on all members of this list, using the member as the context for the callback.
  13689. * The function must exist on the member.
  13690. *
  13691. * @method Phaser.ArrayList#callAll
  13692. * @param {function} callback - The function to call.
  13693. * @param {...*} parameter - Additional parameters that will be passed to the callback.
  13694. */
  13695. callAll: function (callback) {
  13696. var args = Array.prototype.splice.call(arguments, 1);
  13697. var i = this.list.length;
  13698. while (i--)
  13699. {
  13700. if (this.list[i] && this.list[i][callback])
  13701. {
  13702. this.list[i][callback].apply(this.list[i], args);
  13703. }
  13704. }
  13705. }
  13706. };
  13707. /**
  13708. * Resets the cursor to the first item in the list and returns it.
  13709. *
  13710. * @name Phaser.ArrayList#first
  13711. * @property {object} first - The first item in the list.
  13712. */
  13713. Object.defineProperty(Phaser.ArrayList.prototype, "first", {
  13714. get: function () {
  13715. this.position = 0;
  13716. if (this.total > 0)
  13717. {
  13718. return this.list[0];
  13719. }
  13720. else
  13721. {
  13722. return null;
  13723. }
  13724. }
  13725. });
  13726. /**
  13727. * Gets the next item in the list and returns it, advancing the cursor.
  13728. *
  13729. * @name Phaser.ArrayList#next
  13730. * @property {object} next - Advanced the cursor and return.
  13731. */
  13732. Object.defineProperty(Phaser.ArrayList.prototype, "next", {
  13733. get: function () {
  13734. if (this.position < this.total)
  13735. {
  13736. this.position++;
  13737. return this.list[this.position];
  13738. }
  13739. else
  13740. {
  13741. return null;
  13742. }
  13743. }
  13744. });
  13745. Phaser.ArrayList.prototype.constructor = Phaser.ArrayList;
  13746. /**
  13747. * @author Richard Davey <rich@photonstorm.com>
  13748. * @copyright 2014 Photon Storm Ltd.
  13749. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  13750. */
  13751. /**
  13752. * @class Phaser.Signal
  13753. * @classdesc A Signal is used for object communication via a custom broadcaster instead of Events.
  13754. * @author Miller Medeiros http://millermedeiros.github.com/js-signals/
  13755. * @constructor
  13756. */
  13757. Phaser.Signal = function () {
  13758. /**
  13759. * @property {Array.<Phaser.SignalBinding>} _bindings - Internal variable.
  13760. * @private
  13761. */
  13762. this._bindings = [];
  13763. /**
  13764. * @property {any} _prevParams - Internal variable.
  13765. * @private
  13766. */
  13767. this._prevParams = null;
  13768. // enforce dispatch to aways work on same context (#47)
  13769. var self = this;
  13770. /**
  13771. * @property {function} dispatch - The dispatch function is what sends the Signal out.
  13772. */
  13773. this.dispatch = function(){
  13774. Phaser.Signal.prototype.dispatch.apply(self, arguments);
  13775. };
  13776. };
  13777. Phaser.Signal.prototype = {
  13778. /**
  13779. * If Signal should keep record of previously dispatched parameters and
  13780. * automatically execute listener during `add()`/`addOnce()` if Signal was
  13781. * already dispatched before.
  13782. * @property {boolean} memorize
  13783. */
  13784. memorize: false,
  13785. /**
  13786. * @property {boolean} _shouldPropagate
  13787. * @private
  13788. */
  13789. _shouldPropagate: true,
  13790. /**
  13791. * If Signal is active and should broadcast events.
  13792. * IMPORTANT: Setting this property during a dispatch will only affect the next dispatch, if you want to stop the propagation of a signal use `halt()` instead.
  13793. * @property {boolean} active
  13794. * @default
  13795. */
  13796. active: true,
  13797. /**
  13798. * @method Phaser.Signal#validateListener
  13799. * @param {function} listener - Signal handler function.
  13800. * @param {string} fnName - Function name.
  13801. * @private
  13802. */
  13803. validateListener: function (listener, fnName) {
  13804. if (typeof listener !== 'function')
  13805. {
  13806. throw new Error('Phaser.Signal: listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName));
  13807. }
  13808. },
  13809. /**
  13810. * @method Phaser.Signal#_registerListener
  13811. * @private
  13812. * @param {function} listener - Signal handler function.
  13813. * @param {boolean} isOnce - Should the listener only be called once?
  13814. * @param {object} [listenerContext] - The context under which the listener is invoked.
  13815. * @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).
  13816. * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
  13817. */
  13818. _registerListener: function (listener, isOnce, listenerContext, priority) {
  13819. var prevIndex = this._indexOfListener(listener, listenerContext);
  13820. var binding;
  13821. if (prevIndex !== -1)
  13822. {
  13823. binding = this._bindings[prevIndex];
  13824. if (binding.isOnce() !== isOnce)
  13825. {
  13826. throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.');
  13827. }
  13828. }
  13829. else
  13830. {
  13831. binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority);
  13832. this._addBinding(binding);
  13833. }
  13834. if (this.memorize && this._prevParams)
  13835. {
  13836. binding.execute(this._prevParams);
  13837. }
  13838. return binding;
  13839. },
  13840. /**
  13841. * @method Phaser.Signal#_addBinding
  13842. * @private
  13843. * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener.
  13844. */
  13845. _addBinding: function (binding) {
  13846. // Simplified insertion sort
  13847. var n = this._bindings.length;
  13848. do {
  13849. n--;
  13850. }
  13851. while (this._bindings[n] && binding._priority <= this._bindings[n]._priority);
  13852. this._bindings.splice(n + 1, 0, binding);
  13853. },
  13854. /**
  13855. * @method Phaser.Signal#_indexOfListener
  13856. * @private
  13857. * @param {function} listener - Signal handler function.
  13858. * @return {number} The index of the listener within the private bindings array.
  13859. */
  13860. _indexOfListener: function (listener, context) {
  13861. var n = this._bindings.length;
  13862. var cur;
  13863. while (n--)
  13864. {
  13865. cur = this._bindings[n];
  13866. if (cur._listener === listener && cur.context === context)
  13867. {
  13868. return n;
  13869. }
  13870. }
  13871. return -1;
  13872. },
  13873. /**
  13874. * Check if listener was attached to Signal.
  13875. *
  13876. * @method Phaser.Signal#has
  13877. * @param {function} listener - Signal handler function.
  13878. * @param {object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  13879. * @return {boolean} If Signal has the specified listener.
  13880. */
  13881. has: function (listener, context) {
  13882. return this._indexOfListener(listener, context) !== -1;
  13883. },
  13884. /**
  13885. * Add a listener to the signal.
  13886. *
  13887. * @method Phaser.Signal#add
  13888. * @param {function} listener - The function to call when this Signal is dispatched.
  13889. * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable).
  13890. * @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)
  13891. * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
  13892. */
  13893. add: function (listener, listenerContext, priority) {
  13894. this.validateListener(listener, 'add');
  13895. return this._registerListener(listener, false, listenerContext, priority);
  13896. },
  13897. /**
  13898. * Add listener to the signal that should be removed after first execution (will be executed only once).
  13899. *
  13900. * @method Phaser.Signal#addOnce
  13901. * @param {function} listener - The function to call when this Signal is dispatched.
  13902. * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable).
  13903. * @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)
  13904. * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
  13905. */
  13906. addOnce: function (listener, listenerContext, priority) {
  13907. this.validateListener(listener, 'addOnce');
  13908. return this._registerListener(listener, true, listenerContext, priority);
  13909. },
  13910. /**
  13911. * Remove a single listener from the dispatch queue.
  13912. *
  13913. * @method Phaser.Signal#remove
  13914. * @param {function} listener - Handler function that should be removed.
  13915. * @param {object} [context] - Execution context (since you can add the same handler multiple times if executing in a different context).
  13916. * @return {function} Listener handler function.
  13917. */
  13918. remove: function (listener, context) {
  13919. this.validateListener(listener, 'remove');
  13920. var i = this._indexOfListener(listener, context);
  13921. if (i !== -1)
  13922. {
  13923. this._bindings[i]._destroy(); //no reason to a Phaser.SignalBinding exist if it isn't attached to a signal
  13924. this._bindings.splice(i, 1);
  13925. }
  13926. return listener;
  13927. },
  13928. /**
  13929. * Remove all listeners from the Signal.
  13930. *
  13931. * @method Phaser.Signal#removeAll
  13932. * @param {object} [context=null] - If specified only listeners for the given context will be removed.
  13933. */
  13934. removeAll: function (context) {
  13935. if (typeof context === 'undefined') { context = null; }
  13936. var n = this._bindings.length;
  13937. while (n--)
  13938. {
  13939. if (context)
  13940. {
  13941. if (this._bindings[n].context === context)
  13942. {
  13943. this._bindings[n]._destroy();
  13944. this._bindings.splice(n, 1);
  13945. }
  13946. }
  13947. else
  13948. {
  13949. this._bindings[n]._destroy();
  13950. }
  13951. }
  13952. this._bindings.length = 0;
  13953. },
  13954. /**
  13955. * Gets the total number of listeneres attached to ths Signal.
  13956. *
  13957. * @method Phaser.Signal#getNumListeners
  13958. * @return {number} Number of listeners attached to the Signal.
  13959. */
  13960. getNumListeners: function () {
  13961. return this._bindings.length;
  13962. },
  13963. /**
  13964. * Stop propagation of the event, blocking the dispatch to next listeners on the queue.
  13965. * IMPORTANT: should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.
  13966. * @see Signal.prototype.disable
  13967. *
  13968. * @method Phaser.Signal#halt
  13969. */
  13970. halt: function () {
  13971. this._shouldPropagate = false;
  13972. },
  13973. /**
  13974. * Dispatch/Broadcast Signal to all listeners added to the queue.
  13975. *
  13976. * @method Phaser.Signal#dispatch
  13977. * @param {any} [params] - Parameters that should be passed to each handler.
  13978. */
  13979. dispatch: function () {
  13980. if (!this.active)
  13981. {
  13982. return;
  13983. }
  13984. var paramsArr = Array.prototype.slice.call(arguments);
  13985. var n = this._bindings.length;
  13986. var bindings;
  13987. if (this.memorize)
  13988. {
  13989. this._prevParams = paramsArr;
  13990. }
  13991. if (!n)
  13992. {
  13993. // Should come after memorize
  13994. return;
  13995. }
  13996. bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch
  13997. this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch.
  13998. //execute all callbacks until end of the list or until a callback returns `false` or stops propagation
  13999. //reverse loop since listeners with higher priority will be added at the end of the list
  14000. do {
  14001. n--;
  14002. }
  14003. while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false);
  14004. },
  14005. /**
  14006. * Forget memorized arguments.
  14007. * @see Signal.memorize
  14008. *
  14009. * @method Phaser.Signal#forget
  14010. */
  14011. forget: function() {
  14012. this._prevParams = null;
  14013. },
  14014. /**
  14015. * Remove all bindings from signal and destroy any reference to external objects (destroy Signal object).
  14016. * IMPORTANT: calling any method on the signal instance after calling dispose will throw errors.
  14017. *
  14018. * @method Phaser.Signal#dispose
  14019. */
  14020. dispose: function () {
  14021. this.removeAll();
  14022. delete this._bindings;
  14023. delete this._prevParams;
  14024. },
  14025. /**
  14026. *
  14027. * @method Phaser.Signal#toString
  14028. * @return {string} String representation of the object.
  14029. */
  14030. toString: function () {
  14031. return '[Phaser.Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']';
  14032. }
  14033. };
  14034. Phaser.Signal.prototype.constructor = Phaser.Signal;
  14035. /**
  14036. * @author Richard Davey <rich@photonstorm.com>
  14037. * @copyright 2014 Photon Storm Ltd.
  14038. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  14039. */
  14040. /**
  14041. * @class Phaser.SignalBinding
  14042. * @classdesc Object that represents a binding between a Signal and a listener function.
  14043. * This is an internal constructor and shouldn't be created directly.
  14044. * Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes.
  14045. *
  14046. * @author Miller Medeiros http://millermedeiros.github.com/js-signals/
  14047. * @constructor
  14048. * @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to.
  14049. * @param {function} listener - Handler function bound to the signal.
  14050. * @param {boolean} isOnce - If binding should be executed just once.
  14051. * @param {object} [listenerContext] - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  14052. * @param {number} [priority] - The priority level of the event listener. (default = 0).
  14053. */
  14054. Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority) {
  14055. /**
  14056. * @property {Phaser.Game} _listener - Handler function bound to the signal.
  14057. * @private
  14058. */
  14059. this._listener = listener;
  14060. /**
  14061. * @property {boolean} _isOnce - If binding should be executed just once.
  14062. * @private
  14063. */
  14064. this._isOnce = isOnce;
  14065. /**
  14066. * @property {object|undefined|null} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  14067. */
  14068. this.context = listenerContext;
  14069. /**
  14070. * @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to.
  14071. * @private
  14072. */
  14073. this._signal = signal;
  14074. /**
  14075. * @property {number} _priority - Listener priority.
  14076. * @private
  14077. */
  14078. this._priority = priority || 0;
  14079. };
  14080. Phaser.SignalBinding.prototype = {
  14081. /**
  14082. * If binding is active and should be executed.
  14083. * @property {boolean} active
  14084. * @default
  14085. */
  14086. active: true,
  14087. /**
  14088. * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters).
  14089. * @property {array|null} params
  14090. * @default
  14091. */
  14092. params: null,
  14093. /**
  14094. * Call listener passing arbitrary parameters.
  14095. * 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.
  14096. * @method Phaser.SignalBinding#execute
  14097. * @param {array} [paramsArr] - Array of parameters that should be passed to the listener.
  14098. * @return {any} Value returned by the listener.
  14099. */
  14100. execute: function(paramsArr) {
  14101. var handlerReturn, params;
  14102. if (this.active && !!this._listener)
  14103. {
  14104. params = this.params ? this.params.concat(paramsArr) : paramsArr;
  14105. handlerReturn = this._listener.apply(this.context, params);
  14106. if (this._isOnce)
  14107. {
  14108. this.detach();
  14109. }
  14110. }
  14111. return handlerReturn;
  14112. },
  14113. /**
  14114. * Detach binding from signal.
  14115. * alias to: @see mySignal.remove(myBinding.getListener());
  14116. * @method Phaser.SignalBinding#detach
  14117. * @return {function|null} Handler function bound to the signal or `null` if binding was previously detached.
  14118. */
  14119. detach: function () {
  14120. return this.isBound() ? this._signal.remove(this._listener, this.context) : null;
  14121. },
  14122. /**
  14123. * @method Phaser.SignalBinding#isBound
  14124. * @return {boolean} True if binding is still bound to the signal and has a listener.
  14125. */
  14126. isBound: function () {
  14127. return (!!this._signal && !!this._listener);
  14128. },
  14129. /**
  14130. * @method Phaser.SignalBinding#isOnce
  14131. * @return {boolean} If SignalBinding will only be executed once.
  14132. */
  14133. isOnce: function () {
  14134. return this._isOnce;
  14135. },
  14136. /**
  14137. * @method Phaser.SignalBinding#getListener
  14138. * @return {Function} Handler function bound to the signal.
  14139. */
  14140. getListener: function () {
  14141. return this._listener;
  14142. },
  14143. /**
  14144. * @method Phaser.SignalBinding#getSignal
  14145. * @return {Signal} Signal that listener is currently bound to.
  14146. */
  14147. getSignal: function () {
  14148. return this._signal;
  14149. },
  14150. /**
  14151. * Delete instance properties
  14152. * @method Phaser.SignalBinding#_destroy
  14153. * @private
  14154. */
  14155. _destroy: function () {
  14156. delete this._signal;
  14157. delete this._listener;
  14158. delete this.context;
  14159. },
  14160. /**
  14161. * @method Phaser.SignalBinding#toString
  14162. * @return {string} String representation of the object.
  14163. */
  14164. toString: function () {
  14165. return '[Phaser.SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']';
  14166. }
  14167. };
  14168. Phaser.SignalBinding.prototype.constructor = Phaser.SignalBinding;
  14169. /**
  14170. * @author Richard Davey <rich@photonstorm.com>
  14171. * @copyright 2014 Photon Storm Ltd.
  14172. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  14173. */
  14174. /**
  14175. * This is a base Filter template to use for any Phaser filter development.
  14176. *
  14177. * @class Phaser.Filter
  14178. * @classdesc Phaser - Filter
  14179. * @constructor
  14180. * @param {Phaser.Game} game - A reference to the currently running game.
  14181. * @param {Object} uniforms - Uniform mappings object
  14182. * @param {Array} fragmentSrc - The fragment shader code.
  14183. */
  14184. Phaser.Filter = function (game, uniforms, fragmentSrc) {
  14185. /**
  14186. * @property {Phaser.Game} game - A reference to the currently running game.
  14187. */
  14188. this.game = game;
  14189. /**
  14190. * @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER.
  14191. * @default
  14192. */
  14193. this.type = Phaser.WEBGL_FILTER;
  14194. /**
  14195. * An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion.
  14196. * For example the blur filter has two passes blurX and blurY.
  14197. * @property {array} passes - An array of filter objects.
  14198. * @private
  14199. */
  14200. this.passes = [this];
  14201. /**
  14202. * @property {array} shaders - Array an array of shaders.
  14203. * @private
  14204. */
  14205. this.shaders = [];
  14206. /**
  14207. * @property {boolean} dirty - Internal PIXI var.
  14208. * @default
  14209. */
  14210. this.dirty = true;
  14211. /**
  14212. * @property {number} padding - Internal PIXI var.
  14213. * @default
  14214. */
  14215. this.padding = 0;
  14216. /**
  14217. * @property {object} uniforms - Default uniform mappings.
  14218. */
  14219. this.uniforms = {
  14220. time: { type: '1f', value: 0 },
  14221. resolution: { type: '2f', value: { x: 256, y: 256 }},
  14222. mouse: { type: '2f', value: { x: 0.0, y: 0.0 }}
  14223. };
  14224. /**
  14225. * @property {array} fragmentSrc - The fragment shader code.
  14226. */
  14227. this.fragmentSrc = fragmentSrc || [];
  14228. };
  14229. Phaser.Filter.prototype = {
  14230. /**
  14231. * Should be over-ridden.
  14232. * @method Phaser.Filter#init
  14233. */
  14234. init: function () {
  14235. // This should be over-ridden. Will receive a variable number of arguments.
  14236. },
  14237. /**
  14238. * Set the resolution uniforms on the filter.
  14239. * @method Phaser.Filter#setResolution
  14240. * @param {number} width - The width of the display.
  14241. * @param {number} height - The height of the display.
  14242. */
  14243. setResolution: function (width, height) {
  14244. this.uniforms.resolution.value.x = width;
  14245. this.uniforms.resolution.value.y = height;
  14246. },
  14247. /**
  14248. * Updates the filter.
  14249. * @method Phaser.Filter#update
  14250. * @param {Phaser.Pointer} [pointer] - A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform.
  14251. */
  14252. update: function (pointer) {
  14253. if (typeof pointer !== 'undefined')
  14254. {
  14255. if (pointer.x > 0)
  14256. {
  14257. this.uniforms.mouse.x = pointer.x.toFixed(2);
  14258. }
  14259. if (pointer.y > 0)
  14260. {
  14261. this.uniforms.mouse.y = pointer.y.toFixed(2);
  14262. }
  14263. }
  14264. this.uniforms.time.value = this.game.time.totalElapsedSeconds();
  14265. },
  14266. /**
  14267. * Clear down this Filter and null out references
  14268. * @method Phaser.Filter#destroy
  14269. */
  14270. destroy: function () {
  14271. this.game = null;
  14272. }
  14273. };
  14274. Phaser.Filter.prototype.constructor = Phaser.Filter;
  14275. /**
  14276. * @name Phaser.Filter#width
  14277. * @property {number} width - The width (resolution uniform)
  14278. */
  14279. Object.defineProperty(Phaser.Filter.prototype, 'width', {
  14280. get: function() {
  14281. return this.uniforms.resolution.value.x;
  14282. },
  14283. set: function(value) {
  14284. this.uniforms.resolution.value.x = value;
  14285. }
  14286. });
  14287. /**
  14288. * @name Phaser.Filter#height
  14289. * @property {number} height - The height (resolution uniform)
  14290. */
  14291. Object.defineProperty(Phaser.Filter.prototype, 'height', {
  14292. get: function() {
  14293. return this.uniforms.resolution.value.y;
  14294. },
  14295. set: function(value) {
  14296. this.uniforms.resolution.value.y = value;
  14297. }
  14298. });
  14299. /**
  14300. * @author Richard Davey <rich@photonstorm.com>
  14301. * @copyright 2014 Photon Storm Ltd.
  14302. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  14303. */
  14304. /**
  14305. * This is a base Plugin template to use for any Phaser plugin development.
  14306. *
  14307. * @class Phaser.Plugin
  14308. * @classdesc Phaser - Plugin
  14309. * @constructor
  14310. * @param {Phaser.Game} game - A reference to the currently running game.
  14311. * @param {Any} parent - The object that owns this plugin, usually Phaser.PluginManager.
  14312. */
  14313. Phaser.Plugin = function (game, parent) {
  14314. if (typeof parent === 'undefined') { parent = null; }
  14315. /**
  14316. * @property {Phaser.Game} game - A reference to the currently running game.
  14317. */
  14318. this.game = game;
  14319. /**
  14320. * @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.
  14321. */
  14322. this.parent = parent;
  14323. /**
  14324. * @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped.
  14325. * @default
  14326. */
  14327. this.active = false;
  14328. /**
  14329. * @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped.
  14330. * @default
  14331. */
  14332. this.visible = false;
  14333. /**
  14334. * @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method.
  14335. * @default
  14336. */
  14337. this.hasPreUpdate = false;
  14338. /**
  14339. * @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method.
  14340. * @default
  14341. */
  14342. this.hasUpdate = false;
  14343. /**
  14344. * @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method.
  14345. * @default
  14346. */
  14347. this.hasPostUpdate = false;
  14348. /**
  14349. * @property {boolean} hasRender - A flag to indicate if this plugin has a render method.
  14350. * @default
  14351. */
  14352. this.hasRender = false;
  14353. /**
  14354. * @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method.
  14355. * @default
  14356. */
  14357. this.hasPostRender = false;
  14358. };
  14359. Phaser.Plugin.prototype = {
  14360. /**
  14361. * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics).
  14362. * It is only called if active is set to true.
  14363. * @method Phaser.Plugin#preUpdate
  14364. */
  14365. preUpdate: function () {
  14366. },
  14367. /**
  14368. * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render.
  14369. * It is only called if active is set to true.
  14370. * @method Phaser.Plugin#update
  14371. */
  14372. update: function () {
  14373. },
  14374. /**
  14375. * Render is called right after the Game Renderer completes, but before the State.render.
  14376. * It is only called if visible is set to true.
  14377. * @method Phaser.Plugin#render
  14378. */
  14379. render: function () {
  14380. },
  14381. /**
  14382. * Post-render is called after the Game Renderer and State.render have run.
  14383. * It is only called if visible is set to true.
  14384. * @method Phaser.Plugin#postRender
  14385. */
  14386. postRender: function () {
  14387. },
  14388. /**
  14389. * Clear down this Plugin and null out references
  14390. * @method Phaser.Plugin#destroy
  14391. */
  14392. destroy: function () {
  14393. this.game = null;
  14394. this.parent = null;
  14395. this.active = false;
  14396. this.visible = false;
  14397. }
  14398. };
  14399. Phaser.Plugin.prototype.constructor = Phaser.Plugin;
  14400. /* jshint newcap: false */
  14401. /**
  14402. * @author Richard Davey <rich@photonstorm.com>
  14403. * @copyright 2014 Photon Storm Ltd.
  14404. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  14405. */
  14406. /**
  14407. * The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins.
  14408. *
  14409. * @class Phaser.PluginManager
  14410. * @classdesc Phaser - PluginManager
  14411. * @constructor
  14412. * @param {Phaser.Game} game - A reference to the currently running game.
  14413. */
  14414. Phaser.PluginManager = function(game) {
  14415. /**
  14416. * @property {Phaser.Game} game - A reference to the currently running game.
  14417. */
  14418. this.game = game;
  14419. /**
  14420. * @property {array} plugins - An array of all the plugins being managed by this PluginManager.
  14421. */
  14422. this.plugins = [];
  14423. /**
  14424. * @property {number} _len - Internal cache var.
  14425. * @private
  14426. */
  14427. this._len = 0;
  14428. /**
  14429. * @property {number} _i - Internal cache var.
  14430. * @private
  14431. */
  14432. this._i = 0;
  14433. };
  14434. Phaser.PluginManager.prototype = {
  14435. /**
  14436. * Add a new Plugin into the PluginManager.
  14437. * 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.
  14438. *
  14439. * @method Phaser.PluginManager#add
  14440. * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object.
  14441. * @param {...*} parameter - Additional parameters that will be passed to the Plugin.init method.
  14442. * @return {Phaser.Plugin} The Plugin that was added to the manager.
  14443. */
  14444. add: function (plugin) {
  14445. var args = Array.prototype.splice.call(arguments, 1);
  14446. var result = false;
  14447. // Prototype?
  14448. if (typeof plugin === 'function')
  14449. {
  14450. plugin = new plugin(this.game, this);
  14451. }
  14452. else
  14453. {
  14454. plugin.game = this.game;
  14455. plugin.parent = this;
  14456. }
  14457. // Check for methods now to avoid having to do this every loop
  14458. if (typeof plugin['preUpdate'] === 'function')
  14459. {
  14460. plugin.hasPreUpdate = true;
  14461. result = true;
  14462. }
  14463. if (typeof plugin['update'] === 'function')
  14464. {
  14465. plugin.hasUpdate = true;
  14466. result = true;
  14467. }
  14468. if (typeof plugin['postUpdate'] === 'function')
  14469. {
  14470. plugin.hasPostUpdate = true;
  14471. result = true;
  14472. }
  14473. if (typeof plugin['render'] === 'function')
  14474. {
  14475. plugin.hasRender = true;
  14476. result = true;
  14477. }
  14478. if (typeof plugin['postRender'] === 'function')
  14479. {
  14480. plugin.hasPostRender = true;
  14481. result = true;
  14482. }
  14483. // The plugin must have at least one of the above functions to be added to the PluginManager.
  14484. if (result)
  14485. {
  14486. if (plugin.hasPreUpdate || plugin.hasUpdate || plugin.hasPostUpdate)
  14487. {
  14488. plugin.active = true;
  14489. }
  14490. if (plugin.hasRender || plugin.hasPostRender)
  14491. {
  14492. plugin.visible = true;
  14493. }
  14494. this._len = this.plugins.push(plugin);
  14495. // Allows plugins to run potentially destructive code outside of the constructor, and only if being added to the PluginManager
  14496. if (typeof plugin['init'] === 'function')
  14497. {
  14498. plugin.init.apply(plugin, args);
  14499. }
  14500. return plugin;
  14501. }
  14502. else
  14503. {
  14504. return null;
  14505. }
  14506. },
  14507. /**
  14508. * Remove a Plugin from the PluginManager. It calls Plugin.destroy on the plugin before removing it from the manager.
  14509. *
  14510. * @method Phaser.PluginManager#remove
  14511. * @param {Phaser.Plugin} plugin - The plugin to be removed.
  14512. */
  14513. remove: function (plugin) {
  14514. this._i = this._len;
  14515. while (this._i--)
  14516. {
  14517. if (this.plugins[this._i] === plugin)
  14518. {
  14519. plugin.destroy();
  14520. this.plugins.splice(this._i, 1);
  14521. this._len--;
  14522. return;
  14523. }
  14524. }
  14525. },
  14526. /**
  14527. * Remove all Plugins from the PluginManager. It calls Plugin.destroy on every plugin before removing it from the manager.
  14528. *
  14529. * @method Phaser.PluginManager#removeAll
  14530. */
  14531. removeAll: function() {
  14532. this._i = this._len;
  14533. while (this._i--)
  14534. {
  14535. this.plugins[this._i].destroy();
  14536. }
  14537. this.plugins.length = 0;
  14538. this._len = 0;
  14539. },
  14540. /**
  14541. * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics).
  14542. * It only calls plugins who have active=true.
  14543. *
  14544. * @method Phaser.PluginManager#preUpdate
  14545. */
  14546. preUpdate: function () {
  14547. this._i = this._len;
  14548. while (this._i--)
  14549. {
  14550. if (this.plugins[this._i].active && this.plugins[this._i].hasPreUpdate)
  14551. {
  14552. this.plugins[this._i].preUpdate();
  14553. }
  14554. }
  14555. },
  14556. /**
  14557. * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render.
  14558. * It only calls plugins who have active=true.
  14559. *
  14560. * @method Phaser.PluginManager#update
  14561. */
  14562. update: function () {
  14563. this._i = this._len;
  14564. while (this._i--)
  14565. {
  14566. if (this.plugins[this._i].active && this.plugins[this._i].hasUpdate)
  14567. {
  14568. this.plugins[this._i].update();
  14569. }
  14570. }
  14571. },
  14572. /**
  14573. * PostUpdate is the last thing to be called before the world render.
  14574. * In particular, it is called after the world postUpdate, which means the camera has been adjusted.
  14575. * It only calls plugins who have active=true.
  14576. *
  14577. * @method Phaser.PluginManager#postUpdate
  14578. */
  14579. postUpdate: function () {
  14580. this._i = this._len;
  14581. while (this._i--)
  14582. {
  14583. if (this.plugins[this._i].active && this.plugins[this._i].hasPostUpdate)
  14584. {
  14585. this.plugins[this._i].postUpdate();
  14586. }
  14587. }
  14588. },
  14589. /**
  14590. * Render is called right after the Game Renderer completes, but before the State.render.
  14591. * It only calls plugins who have visible=true.
  14592. *
  14593. * @method Phaser.PluginManager#render
  14594. */
  14595. render: function () {
  14596. this._i = this._len;
  14597. while (this._i--)
  14598. {
  14599. if (this.plugins[this._i].visible && this.plugins[this._i].hasRender)
  14600. {
  14601. this.plugins[this._i].render();
  14602. }
  14603. }
  14604. },
  14605. /**
  14606. * Post-render is called after the Game Renderer and State.render have run.
  14607. * It only calls plugins who have visible=true.
  14608. *
  14609. * @method Phaser.PluginManager#postRender
  14610. */
  14611. postRender: function () {
  14612. this._i = this._len;
  14613. while (this._i--)
  14614. {
  14615. if (this.plugins[this._i].visible && this.plugins[this._i].hasPostRender)
  14616. {
  14617. this.plugins[this._i].postRender();
  14618. }
  14619. }
  14620. },
  14621. /**
  14622. * Clear down this PluginManager, calls destroy on every plugin and nulls out references.
  14623. *
  14624. * @method Phaser.PluginManager#destroy
  14625. */
  14626. destroy: function () {
  14627. this.removeAll();
  14628. this.game = null;
  14629. }
  14630. };
  14631. Phaser.PluginManager.prototype.constructor = Phaser.PluginManager;
  14632. /**
  14633. * @author Richard Davey <rich@photonstorm.com>
  14634. * @copyright 2014 Photon Storm Ltd.
  14635. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  14636. */
  14637. /**
  14638. * The Stage controls the canvas on which everything is displayed. It handles display within the browser,
  14639. * focus handling, game resizing, scaling and the pause, boot and orientation screens.
  14640. *
  14641. * @class Phaser.Stage
  14642. * @extends PIXI.Stage
  14643. * @constructor
  14644. * @param {Phaser.Game} game - Game reference to the currently running game.
  14645. * @param {number} width - Width of the canvas element.
  14646. * @param {number} height - Height of the canvas element.
  14647. */
  14648. Phaser.Stage = function (game, width, height) {
  14649. /**
  14650. * @property {Phaser.Game} game - A reference to the currently running Game.
  14651. */
  14652. this.game = game;
  14653. /**
  14654. * @property {Phaser.Point} offset - Holds the offset coordinates of the Game.canvas from the top-left of the browser window (used by Input and other classes)
  14655. */
  14656. this.offset = new Phaser.Point();
  14657. /**
  14658. * @property {Phaser.Rectangle} bounds - The bounds of the Stage. Typically x/y = Stage.offset.x/y and the width/height match the game width and height.
  14659. */
  14660. this.bounds = new Phaser.Rectangle(0, 0, width, height);
  14661. PIXI.Stage.call(this, 0x000000);
  14662. /**
  14663. * @property {string} name - The name of this object.
  14664. * @default
  14665. */
  14666. this.name = '_stage_root';
  14667. /**
  14668. * @property {boolean} interactive - Pixi level var, ignored by Phaser.
  14669. * @default
  14670. * @private
  14671. */
  14672. this.interactive = false;
  14673. /**
  14674. * @property {boolean} disableVisibilityChange - By default if the browser tab loses focus the game will pause. You can stop that behaviour by setting this property to true.
  14675. * @default
  14676. */
  14677. this.disableVisibilityChange = false;
  14678. /**
  14679. * @property {number|false} checkOffsetInterval - The time (in ms) between which the stage should check to see if it has moved.
  14680. * @default
  14681. */
  14682. this.checkOffsetInterval = 2500;
  14683. /**
  14684. * @property {boolean} exists - If exists is true the Stage and all children are updated, otherwise it is skipped.
  14685. * @default
  14686. */
  14687. this.exists = true;
  14688. /**
  14689. * @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated.
  14690. */
  14691. this.currentRenderOrderID = 0;
  14692. /**
  14693. * @property {string} hiddenVar - The page visibility API event name.
  14694. * @private
  14695. */
  14696. this._hiddenVar = 'hidden';
  14697. /**
  14698. * @property {number} _nextOffsetCheck - The time to run the next offset check.
  14699. * @private
  14700. */
  14701. this._nextOffsetCheck = 0;
  14702. /**
  14703. * @property {number} _backgroundColor - Stage background color.
  14704. * @private
  14705. */
  14706. this._backgroundColor = 0x000000;
  14707. if (game.config)
  14708. {
  14709. this.parseConfig(game.config);
  14710. }
  14711. };
  14712. Phaser.Stage.prototype = Object.create(PIXI.Stage.prototype);
  14713. Phaser.Stage.prototype.constructor = Phaser.Stage;
  14714. /**
  14715. * This is called automatically after the plugins preUpdate and before the State.update.
  14716. * Most objects have preUpdate methods and it's where initial movement and positioning is done.
  14717. *
  14718. * @method Phaser.Stage#preUpdate
  14719. */
  14720. Phaser.Stage.prototype.preUpdate = function () {
  14721. this.currentRenderOrderID = 0;
  14722. // This can't loop in reverse, we need the orderID to be in sequence
  14723. var len = this.children.length;
  14724. for (var i = 0; i < len; i++)
  14725. {
  14726. this.children[i].preUpdate();
  14727. }
  14728. };
  14729. /**
  14730. * This is called automatically after the State.update, but before particles or plugins update.
  14731. *
  14732. * @method Phaser.Stage#update
  14733. */
  14734. Phaser.Stage.prototype.update = function () {
  14735. var i = this.children.length;
  14736. while (i--)
  14737. {
  14738. this.children[i].update();
  14739. }
  14740. };
  14741. /**
  14742. * This is called automatically before the renderer runs and after the plugins have updated.
  14743. * In postUpdate this is where all the final physics calculatations and object positioning happens.
  14744. * The objects are processed in the order of the display list.
  14745. * The only exception to this is if the camera is following an object, in which case that is updated first.
  14746. *
  14747. * @method Phaser.Stage#postUpdate
  14748. */
  14749. Phaser.Stage.prototype.postUpdate = function () {
  14750. if (this.game.world.camera.target)
  14751. {
  14752. this.game.world.camera.target.postUpdate();
  14753. this.game.world.camera.update();
  14754. var i = this.children.length;
  14755. while (i--)
  14756. {
  14757. if (this.children[i] !== this.game.world.camera.target)
  14758. {
  14759. this.children[i].postUpdate();
  14760. }
  14761. }
  14762. }
  14763. else
  14764. {
  14765. this.game.world.camera.update();
  14766. var i = this.children.length;
  14767. while (i--)
  14768. {
  14769. this.children[i].postUpdate();
  14770. }
  14771. }
  14772. if (this.checkOffsetInterval !== false)
  14773. {
  14774. if (this.game.time.now > this._nextOffsetCheck)
  14775. {
  14776. Phaser.Canvas.getOffset(this.game.canvas, this.offset);
  14777. this.bounds.x = this.offset.x;
  14778. this.bounds.y = this.offset.y;
  14779. this._nextOffsetCheck = this.game.time.now + this.checkOffsetInterval;
  14780. }
  14781. }
  14782. };
  14783. /**
  14784. * Parses a Game configuration object.
  14785. *
  14786. * @method Phaser.Stage#parseConfig
  14787. * @protected
  14788. * @param {object} config -The configuration object to parse.
  14789. */
  14790. Phaser.Stage.prototype.parseConfig = function (config) {
  14791. if (config['checkOffsetInterval'])
  14792. {
  14793. this.checkOffsetInterval = config['checkOffsetInterval'];
  14794. }
  14795. if (config['disableVisibilityChange'])
  14796. {
  14797. this.disableVisibilityChange = config['disableVisibilityChange'];
  14798. }
  14799. if (config['fullScreenScaleMode'])
  14800. {
  14801. this.fullScreenScaleMode = config['fullScreenScaleMode'];
  14802. }
  14803. if (config['scaleMode'])
  14804. {
  14805. this.scaleMode = config['scaleMode'];
  14806. }
  14807. if (config['backgroundColor'])
  14808. {
  14809. this.backgroundColor = config['backgroundColor'];
  14810. }
  14811. };
  14812. /**
  14813. * Initialises the stage and adds the event listeners.
  14814. * @method Phaser.Stage#boot
  14815. * @private
  14816. */
  14817. Phaser.Stage.prototype.boot = function () {
  14818. Phaser.Canvas.getOffset(this.game.canvas, this.offset);
  14819. this.bounds.setTo(this.offset.x, this.offset.y, this.game.width, this.game.height);
  14820. var _this = this;
  14821. this._onChange = function (event) {
  14822. return _this.visibilityChange(event);
  14823. };
  14824. Phaser.Canvas.setUserSelect(this.game.canvas, 'none');
  14825. Phaser.Canvas.setTouchAction(this.game.canvas, 'none');
  14826. this.checkVisibility();
  14827. };
  14828. /**
  14829. * Starts a page visibility event listener running, or window.blur/focus if not supported by the browser.
  14830. * @method Phaser.Stage#checkVisibility
  14831. */
  14832. Phaser.Stage.prototype.checkVisibility = function () {
  14833. if (document.webkitHidden !== undefined)
  14834. {
  14835. this._hiddenVar = 'webkitvisibilitychange';
  14836. }
  14837. else if (document.mozHidden !== undefined)
  14838. {
  14839. this._hiddenVar = 'mozvisibilitychange';
  14840. }
  14841. else if (document.msHidden !== undefined)
  14842. {
  14843. this._hiddenVar = 'msvisibilitychange';
  14844. }
  14845. else if (document.hidden !== undefined)
  14846. {
  14847. this._hiddenVar = 'visibilitychange';
  14848. }
  14849. else
  14850. {
  14851. this._hiddenVar = null;
  14852. }
  14853. // Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus
  14854. if (this._hiddenVar)
  14855. {
  14856. document.addEventListener(this._hiddenVar, this._onChange, false);
  14857. }
  14858. window.onpagehide = this._onChange;
  14859. window.onpageshow = this._onChange;
  14860. window.onblur = this._onChange;
  14861. window.onfocus = this._onChange;
  14862. };
  14863. /**
  14864. * This method is called when the document visibility is changed.
  14865. *
  14866. * @method Phaser.Stage#visibilityChange
  14867. * @param {Event} event - Its type will be used to decide whether the game should be paused or not.
  14868. */
  14869. Phaser.Stage.prototype.visibilityChange = function (event) {
  14870. if (event.type === 'pagehide' || event.type === 'blur' || event.type === 'pageshow' || event.type === 'focus')
  14871. {
  14872. if (event.type === 'pagehide' || event.type === 'blur')
  14873. {
  14874. this.game.focusLoss(event);
  14875. }
  14876. else if (event.type === 'pageshow' || event.type === 'focus')
  14877. {
  14878. this.game.focusGain(event);
  14879. }
  14880. return;
  14881. }
  14882. if (this.disableVisibilityChange)
  14883. {
  14884. return;
  14885. }
  14886. if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden)
  14887. {
  14888. this.game.gamePaused(event);
  14889. }
  14890. else
  14891. {
  14892. this.game.gameResumed(event);
  14893. }
  14894. };
  14895. /**
  14896. * Sets the background color for the Stage. The color can be given as a hex value (#RRGGBB) or a numeric value (0xRRGGBB)
  14897. *
  14898. * @name Phaser.Stage#setBackgroundColor
  14899. * @param {number|string} backgroundColor - The color of the background.
  14900. */
  14901. Phaser.Stage.prototype.setBackgroundColor = function(backgroundColor)
  14902. {
  14903. if (typeof backgroundColor === 'string')
  14904. {
  14905. var rgb = Phaser.Color.hexToColor(backgroundColor);
  14906. this._backgroundColor = Phaser.Color.getColor(rgb.r, rgb.g, rgb.b);
  14907. }
  14908. else
  14909. {
  14910. var rgb = Phaser.Color.getRGB(backgroundColor);
  14911. this._backgroundColor = backgroundColor;
  14912. }
  14913. this.backgroundColorSplit = [ rgb.r / 255, rgb.g / 255, rgb.b / 255 ];
  14914. this.backgroundColorString = Phaser.Color.RGBtoString(rgb.r, rgb.g, rgb.b, 255, '#');
  14915. };
  14916. /**
  14917. * @name Phaser.Stage#backgroundColor
  14918. * @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'
  14919. */
  14920. Object.defineProperty(Phaser.Stage.prototype, "backgroundColor", {
  14921. get: function () {
  14922. return this._backgroundColor;
  14923. },
  14924. set: function (color) {
  14925. if (!this.game.transparent)
  14926. {
  14927. this.setBackgroundColor(color);
  14928. }
  14929. }
  14930. });
  14931. /**
  14932. * Enable or disable texture smoothing for all objects on this Stage. Only works for bitmap/image textures. Smoothing is enabled by default.
  14933. *
  14934. * @name Phaser.Stage#smoothed
  14935. * @property {boolean} smoothed - Set to true to smooth all sprites rendered on this Stage, or false to disable smoothing (great for pixel art)
  14936. */
  14937. Object.defineProperty(Phaser.Stage.prototype, "smoothed", {
  14938. get: function () {
  14939. return !PIXI.scaleModes.LINEAR;
  14940. },
  14941. set: function (value) {
  14942. if (value)
  14943. {
  14944. PIXI.scaleModes.LINEAR = 0;
  14945. }
  14946. else
  14947. {
  14948. PIXI.scaleModes.LINEAR = 1;
  14949. }
  14950. }
  14951. });
  14952. /**
  14953. * @author Richard Davey <rich@photonstorm.com>
  14954. * @copyright 2014 Photon Storm Ltd.
  14955. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  14956. */
  14957. /**
  14958. * Phaser Group constructor.
  14959. * @class Phaser.Group
  14960. * @classdesc A Group is a container for display objects that allows for fast pooling and object recycling. Groups can be nested within other Groups and have their own local transforms.
  14961. * @constructor
  14962. * @param {Phaser.Game} game - A reference to the currently running game.
  14963. * @param {Phaser.Group|Phaser.Sprite|null} parent - The parent Group, DisplayObject or DisplayObjectContainer that this Group will be added to. If `undefined` it will use game.world. If null it won't be added to anything.
  14964. * @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging.
  14965. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  14966. * @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.
  14967. * @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.
  14968. */
  14969. Phaser.Group = function (game, parent, name, addToStage, enableBody, physicsBodyType) {
  14970. if (typeof addToStage === 'undefined') { addToStage = false; }
  14971. if (typeof enableBody === 'undefined') { enableBody = false; }
  14972. if (typeof physicsBodyType === 'undefined') { physicsBodyType = Phaser.Physics.ARCADE; }
  14973. /**
  14974. * @property {Phaser.Game} game - A reference to the currently running Game.
  14975. */
  14976. this.game = game;
  14977. if (typeof parent === 'undefined')
  14978. {
  14979. parent = game.world;
  14980. }
  14981. /**
  14982. * @property {string} name - A name for this Group. Not used internally but useful for debugging.
  14983. */
  14984. this.name = name || 'group';
  14985. PIXI.DisplayObjectContainer.call(this);
  14986. if (addToStage)
  14987. {
  14988. this.game.stage.addChild(this);
  14989. }
  14990. else
  14991. {
  14992. if (parent)
  14993. {
  14994. parent.addChild(this);
  14995. }
  14996. }
  14997. /**
  14998. * @property {number} z - The z-depth value of this object within its Group (remember the World is a Group as well). No two objects in a Group can have the same z value.
  14999. */
  15000. this.z = 0;
  15001. /**
  15002. * @property {number} type - Internal Phaser Type value.
  15003. * @protected
  15004. */
  15005. this.type = Phaser.GROUP;
  15006. /**
  15007. * @property {boolean} alive - The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive.
  15008. * @default
  15009. */
  15010. this.alive = true;
  15011. /**
  15012. * @property {boolean} exists - If exists is true the Group is updated, otherwise it is skipped.
  15013. * @default
  15014. */
  15015. this.exists = true;
  15016. /**
  15017. * The type of objects that will be created when you use Group.create or Group.createMultiple. Defaults to Phaser.Sprite.
  15018. * When a new object is created it is passed the following parameters to its constructor: game, x, y, key, frame.
  15019. * @property {object} classType
  15020. * @default
  15021. */
  15022. this.classType = Phaser.Sprite;
  15023. /**
  15024. * @property {Phaser.Group|Phaser.Sprite} parent - The parent of this Group.
  15025. */
  15026. /**
  15027. * @property {Phaser.Point} scale - The scale of the Group container.
  15028. */
  15029. this.scale = new Phaser.Point(1, 1);
  15030. /**
  15031. * @property {Phaser.Point} pivot - The pivot point of the Group container.
  15032. */
  15033. /**
  15034. * The cursor is a simple way to iterate through the objects in a Group using the Group.next and Group.previous functions.
  15035. * The cursor is set to the first child added to the Group and doesn't change unless you call next, previous or set it directly with Group.cursor.
  15036. * @property {any} cursor - The current display object that the Group cursor is pointing to.
  15037. */
  15038. this.cursor = null;
  15039. /**
  15040. * @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
  15041. */
  15042. this.cameraOffset = new Phaser.Point();
  15043. /**
  15044. * @property {boolean} enableBody - If true all Sprites created by, or added to this Group, will have a physics body enabled on them. Change the body type with `Group.physicsBodyType`.
  15045. * @default
  15046. */
  15047. this.enableBody = enableBody;
  15048. /**
  15049. * @property {boolean} enableBodyDebug - If true when a physics body is created (via Group.enableBody) it will create a physics debug object as well. Only works for P2 bodies.
  15050. */
  15051. this.enableBodyDebug = false;
  15052. /**
  15053. * @property {number} physicsBodyType - If Group.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.
  15054. */
  15055. this.physicsBodyType = physicsBodyType;
  15056. /**
  15057. * @property {string} _sortProperty - The property on which children are sorted.
  15058. * @private
  15059. */
  15060. this._sortProperty = 'z';
  15061. /**
  15062. * A small internal cache:
  15063. * 0 = previous position.x
  15064. * 1 = previous position.y
  15065. * 2 = previous rotation
  15066. * 3 = renderID
  15067. * 4 = fresh? (0 = no, 1 = yes)
  15068. * 5 = outOfBoundsFired (0 = no, 1 = yes)
  15069. * 6 = exists (0 = no, 1 = yes)
  15070. * 7 = fixed to camera (0 = no, 1 = yes)
  15071. * 8 = cursor index
  15072. * 9 = sort order
  15073. * @property {Array} _cache
  15074. * @private
  15075. */
  15076. this._cache = [ 0, 0, 0, 0, 1, 0, 1, 0, 0, 0 ];
  15077. };
  15078. Phaser.Group.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  15079. Phaser.Group.prototype.constructor = Phaser.Group;
  15080. /**
  15081. * @constant
  15082. * @type {number}
  15083. */
  15084. Phaser.Group.RETURN_NONE = 0;
  15085. /**
  15086. * @constant
  15087. * @type {number}
  15088. */
  15089. Phaser.Group.RETURN_TOTAL = 1;
  15090. /**
  15091. * @constant
  15092. * @type {number}
  15093. */
  15094. Phaser.Group.RETURN_CHILD = 2;
  15095. /**
  15096. * @constant
  15097. * @type {number}
  15098. */
  15099. Phaser.Group.SORT_ASCENDING = -1;
  15100. /**
  15101. * @constant
  15102. * @type {number}
  15103. */
  15104. Phaser.Group.SORT_DESCENDING = 1;
  15105. /**
  15106. * Adds an existing object to this Group. The object can be an instance of Phaser.Sprite, Phaser.Button or any other display object.
  15107. * The child is automatically added to the top of the Group, so renders on-top of everything else within the Group. If you need to control
  15108. * that then see the addAt method.
  15109. *
  15110. * @see Phaser.Group#create
  15111. * @see Phaser.Group#addAt
  15112. * @method Phaser.Group#add
  15113. * @param {*} child - An instance of Phaser.Sprite, Phaser.Button or any other display object..
  15114. * @param {boolean} [silent=false] - If the silent parameter is `true` the child will not dispatch the onAddedToGroup event.
  15115. * @return {*} The child that was added to the Group.
  15116. */
  15117. Phaser.Group.prototype.add = function (child, silent) {
  15118. if (typeof silent === 'undefined') { silent = false; }
  15119. if (child.parent !== this)
  15120. {
  15121. if (this.enableBody)
  15122. {
  15123. this.game.physics.enable(child, this.physicsBodyType);
  15124. }
  15125. this.addChild(child);
  15126. child.z = this.children.length;
  15127. if (!silent && child.events)
  15128. {
  15129. child.events.onAddedToGroup.dispatch(child, this);
  15130. }
  15131. if (this.cursor === null)
  15132. {
  15133. this.cursor = child;
  15134. }
  15135. }
  15136. return child;
  15137. };
  15138. /**
  15139. * Adds an existing object to this Group. The object can be an instance of Phaser.Sprite, Phaser.Button or any other display object.
  15140. * The child is added to the Group at the location specified by the index value, this allows you to control child ordering.
  15141. *
  15142. * @method Phaser.Group#addAt
  15143. * @param {*} child - An instance of Phaser.Sprite, Phaser.Button or any other display object..
  15144. * @param {number} index - The index within the Group to insert the child to.
  15145. * @param {boolean} [silent=false] - If the silent parameter is `true` the child will not dispatch the onAddedToGroup event.
  15146. * @return {*} The child that was added to the Group.
  15147. */
  15148. Phaser.Group.prototype.addAt = function (child, index, silent) {
  15149. if (typeof silent === 'undefined') { silent = false; }
  15150. if (child.parent !== this)
  15151. {
  15152. if (this.enableBody)
  15153. {
  15154. this.game.physics.enable(child, this.physicsBodyType);
  15155. }
  15156. this.addChildAt(child, index);
  15157. this.updateZ();
  15158. if (!silent && child.events)
  15159. {
  15160. child.events.onAddedToGroup.dispatch(child, this);
  15161. }
  15162. if (this.cursor === null)
  15163. {
  15164. this.cursor = child;
  15165. }
  15166. }
  15167. return child;
  15168. };
  15169. /**
  15170. * Returns the child found at the given index within this Group.
  15171. *
  15172. * @method Phaser.Group#getAt
  15173. * @param {number} index - The index to return the child from.
  15174. * @return {*} The child that was found at the given index. If the index was out of bounds then this will return -1.
  15175. */
  15176. Phaser.Group.prototype.getAt = function (index) {
  15177. if (index < 0 || index >= this.children.length)
  15178. {
  15179. return -1;
  15180. }
  15181. else
  15182. {
  15183. return this.getChildAt(index);
  15184. }
  15185. };
  15186. /**
  15187. * Automatically creates a new Phaser.Sprite object and adds it to the top of this Group.
  15188. * You can change Group.classType to any object and this call will create an object of that type instead, but it should extend either Sprite or Image.
  15189. *
  15190. * @method Phaser.Group#create
  15191. * @param {number} x - The x coordinate to display the newly created Sprite at. The value is in relation to the Group.x point.
  15192. * @param {number} y - The y coordinate to display the newly created Sprite at. The value is in relation to the Group.y point.
  15193. * @param {string} key - The Game.cache key of the image that this Sprite will use.
  15194. * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here.
  15195. * @param {boolean} [exists=true] - The default exists state of the Sprite.
  15196. * @return {Phaser.Sprite|object} The child that was created. Will be a Phaser.Sprite unless Group.classType has been changed.
  15197. */
  15198. Phaser.Group.prototype.create = function (x, y, key, frame, exists) {
  15199. if (typeof exists === 'undefined') { exists = true; }
  15200. var child = new this.classType(this.game, x, y, key, frame);
  15201. if (this.enableBody)
  15202. {
  15203. this.game.physics.enable(child, this.physicsBodyType, this.enableBodyDebug);
  15204. }
  15205. child.exists = exists;
  15206. child.visible = exists;
  15207. child.alive = exists;
  15208. this.addChild(child);
  15209. child.z = this.children.length;
  15210. if (child.events)
  15211. {
  15212. child.events.onAddedToGroup.dispatch(child, this);
  15213. }
  15214. if (this.cursor === null)
  15215. {
  15216. this.cursor = child;
  15217. }
  15218. return child;
  15219. };
  15220. /**
  15221. * Automatically creates multiple Phaser.Sprite objects and adds them to the top of this Group.
  15222. * Useful if you need to quickly generate a pool of identical sprites, such as bullets. By default the sprites will be set to not exist
  15223. * and will be positioned at 0, 0 (relative to the Group.x/y)
  15224. * You can change Group.classType to any object and this call will create an object of that type instead, but it should extend either Sprite or Image.
  15225. *
  15226. * @method Phaser.Group#createMultiple
  15227. * @param {number} quantity - The number of Sprites to create.
  15228. * @param {string} key - The Game.cache key of the image that this Sprite will use.
  15229. * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here.
  15230. * @param {boolean} [exists=false] - The default exists state of the Sprite.
  15231. */
  15232. Phaser.Group.prototype.createMultiple = function (quantity, key, frame, exists) {
  15233. if (typeof exists === 'undefined') { exists = false; }
  15234. for (var i = 0; i < quantity; i++)
  15235. {
  15236. this.create(0, 0, key, frame, exists);
  15237. }
  15238. };
  15239. /**
  15240. * Internal method that re-applies all of the childrens Z values.
  15241. *
  15242. * @method Phaser.Group#updateZ
  15243. * @protected
  15244. */
  15245. Phaser.Group.prototype.updateZ = function () {
  15246. var i = this.children.length;
  15247. while (i--)
  15248. {
  15249. this.children[i].z = i;
  15250. }
  15251. };
  15252. /**
  15253. * Sets the Group cursor to the first object in the Group. If the optional index parameter is given it sets the cursor to the object at that index instead.
  15254. *
  15255. * @method Phaser.Group#resetCursor
  15256. * @param {number} [index=0] - Set the cursor to point to a specific index.
  15257. * @return {*} The child the cursor now points to.
  15258. */
  15259. Phaser.Group.prototype.resetCursor = function (index) {
  15260. if (typeof index === 'undefined') { index = 0; }
  15261. if (index > this.children.length - 1)
  15262. {
  15263. index = 0;
  15264. }
  15265. if (this.cursor)
  15266. {
  15267. this._cache[8] = index;
  15268. this.cursor = this.children[this._cache[8]];
  15269. return this.cursor;
  15270. }
  15271. };
  15272. /**
  15273. * Advances the Group cursor to the next object in the Group. If it's at the end of the Group it wraps around to the first object.
  15274. *
  15275. * @method Phaser.Group#next
  15276. * @return {*} The child the cursor now points to.
  15277. */
  15278. Phaser.Group.prototype.next = function () {
  15279. if (this.cursor)
  15280. {
  15281. // Wrap the cursor?
  15282. if (this._cache[8] >= this.children.length - 1)
  15283. {
  15284. this._cache[8] = 0;
  15285. }
  15286. else
  15287. {
  15288. this._cache[8]++;
  15289. }
  15290. this.cursor = this.children[this._cache[8]];
  15291. return this.cursor;
  15292. }
  15293. };
  15294. /**
  15295. * Moves the Group cursor to the previous object in the Group. If it's at the start of the Group it wraps around to the last object.
  15296. *
  15297. * @method Phaser.Group#previous
  15298. * @return {*} The child the cursor now points to.
  15299. */
  15300. Phaser.Group.prototype.previous = function () {
  15301. if (this.cursor)
  15302. {
  15303. // Wrap the cursor?
  15304. if (this._cache[8] === 0)
  15305. {
  15306. this._cache[8] = this.children.length - 1;
  15307. }
  15308. else
  15309. {
  15310. this._cache[8]--;
  15311. }
  15312. this.cursor = this.children[this._cache[8]];
  15313. return this.cursor;
  15314. }
  15315. };
  15316. /**
  15317. * Swaps the position of two children in this Group. Both children must be in this Group.
  15318. * You cannot swap a child with itself, or swap un-parented children, doing so will return false.
  15319. *
  15320. * @method Phaser.Group#swap
  15321. * @param {*} child1 - The first child to swap.
  15322. * @param {*} child2 - The second child to swap.
  15323. */
  15324. Phaser.Group.prototype.swap = function (child1, child2) {
  15325. var result = this.swapChildren(child1, child2);
  15326. if (result)
  15327. {
  15328. this.updateZ();
  15329. }
  15330. return result;
  15331. };
  15332. /**
  15333. * Brings the given child to the top of this Group so it renders above all other children.
  15334. *
  15335. * @method Phaser.Group#bringToTop
  15336. * @param {*} child - The child to bring to the top of this Group.
  15337. * @return {*} The child that was moved.
  15338. */
  15339. Phaser.Group.prototype.bringToTop = function (child) {
  15340. if (child.parent === this && this.getIndex(child) < this.children.length)
  15341. {
  15342. this.remove(child, false, true);
  15343. this.add(child, true);
  15344. }
  15345. return child;
  15346. };
  15347. /**
  15348. * Sends the given child to the bottom of this Group so it renders below all other children.
  15349. *
  15350. * @method Phaser.Group#sendToBack
  15351. * @param {*} child - The child to send to the bottom of this Group.
  15352. * @return {*} The child that was moved.
  15353. */
  15354. Phaser.Group.prototype.sendToBack = function (child) {
  15355. if (child.parent === this && this.getIndex(child) > 0)
  15356. {
  15357. this.remove(child, false, true);
  15358. this.addAt(child, 0, true);
  15359. }
  15360. return child;
  15361. };
  15362. /**
  15363. * Moves the given child up one place in this Group unless it's already at the top.
  15364. *
  15365. * @method Phaser.Group#moveUp
  15366. * @param {*} child - The child to move up in the Group.
  15367. * @return {*} The child that was moved.
  15368. */
  15369. Phaser.Group.prototype.moveUp = function (child) {
  15370. if (child.parent === this && this.getIndex(child) < this.children.length - 1)
  15371. {
  15372. var a = this.getIndex(child);
  15373. var b = this.getAt(a + 1);
  15374. if (b)
  15375. {
  15376. this.swap(child, b);
  15377. }
  15378. }
  15379. return child;
  15380. };
  15381. /**
  15382. * Moves the given child down one place in this Group unless it's already at the top.
  15383. *
  15384. * @method Phaser.Group#moveDown
  15385. * @param {*} child - The child to move down in the Group.
  15386. * @return {*} The child that was moved.
  15387. */
  15388. Phaser.Group.prototype.moveDown = function (child) {
  15389. if (child.parent === this && this.getIndex(child) > 0)
  15390. {
  15391. var a = this.getIndex(child);
  15392. var b = this.getAt(a - 1);
  15393. if (b)
  15394. {
  15395. this.swap(child, b);
  15396. }
  15397. }
  15398. return child;
  15399. };
  15400. /**
  15401. * Positions the child found at the given index within this Group to the given x and y coordinates.
  15402. *
  15403. * @method Phaser.Group#xy
  15404. * @param {number} index - The index of the child in the Group to set the position of.
  15405. * @param {number} x - The new x position of the child.
  15406. * @param {number} y - The new y position of the child.
  15407. */
  15408. Phaser.Group.prototype.xy = function (index, x, y) {
  15409. if (index < 0 || index > this.children.length)
  15410. {
  15411. return -1;
  15412. }
  15413. else
  15414. {
  15415. this.getChildAt(index).x = x;
  15416. this.getChildAt(index).y = y;
  15417. }
  15418. };
  15419. /**
  15420. * Reverses all children in this Group. Note that this does not propagate, only direct children are re-ordered.
  15421. *
  15422. * @method Phaser.Group#reverse
  15423. */
  15424. Phaser.Group.prototype.reverse = function () {
  15425. this.children.reverse();
  15426. this.updateZ();
  15427. };
  15428. /**
  15429. * Get the index position of the given child in this Group. This should always match the childs z property.
  15430. *
  15431. * @method Phaser.Group#getIndex
  15432. * @param {*} child - The child to get the index for.
  15433. * @return {number} The index of the child or -1 if it's not a member of this Group.
  15434. */
  15435. Phaser.Group.prototype.getIndex = function (child) {
  15436. return this.children.indexOf(child);
  15437. };
  15438. /**
  15439. * Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group.
  15440. *
  15441. * @method Phaser.Group#replace
  15442. * @param {*} oldChild - The child in this Group that will be replaced.
  15443. * @param {*} newChild - The child to be inserted into this Group.
  15444. * @return {*} Returns the oldChild that was replaced within this Group.
  15445. */
  15446. Phaser.Group.prototype.replace = function (oldChild, newChild) {
  15447. var index = this.getIndex(oldChild);
  15448. if (index !== -1)
  15449. {
  15450. if (newChild.parent !== undefined)
  15451. {
  15452. newChild.events.onRemovedFromGroup.dispatch(newChild, this);
  15453. newChild.parent.removeChild(newChild);
  15454. if (newChild.parent instanceof Phaser.Group)
  15455. {
  15456. newChild.parent.updateZ();
  15457. }
  15458. }
  15459. var temp = oldChild;
  15460. this.remove(temp);
  15461. this.addAt(newChild, index);
  15462. return temp;
  15463. }
  15464. };
  15465. /**
  15466. * Checks if the child has the given property. Will scan up to 4 levels deep only.
  15467. *
  15468. * @method Phaser.Group#hasProperty
  15469. * @param {*} child - The child to check for the existance of the property on.
  15470. * @param {array} key - An array of strings that make up the property.
  15471. * @return {boolean} True if the child has the property, otherwise false.
  15472. */
  15473. Phaser.Group.prototype.hasProperty = function (child, key) {
  15474. var len = key.length;
  15475. if (len === 1 && key[0] in child)
  15476. {
  15477. return true;
  15478. }
  15479. else if (len === 2 && key[0] in child && key[1] in child[key[0]])
  15480. {
  15481. return true;
  15482. }
  15483. else if (len === 3 && key[0] in child && key[1] in child[key[0]] && key[2] in child[key[0]][key[1]])
  15484. {
  15485. return true;
  15486. }
  15487. 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]])
  15488. {
  15489. return true;
  15490. }
  15491. return false;
  15492. };
  15493. /**
  15494. * Sets a property to the given value on the child. The operation parameter controls how the value is set.
  15495. * Operation 0 means set the existing value to the given value, or if force is `false` create a new property with the given value.
  15496. * 1 will add the given value to the value already present.
  15497. * 2 will subtract the given value from the value already present.
  15498. * 3 will multiply the value already present by the given value.
  15499. * 4 will divide the value already present by the given value.
  15500. *
  15501. * @method Phaser.Group#setProperty
  15502. * @param {*} child - The child to set the property value on.
  15503. * @param {array} key - An array of strings that make up the property that will be set.
  15504. * @param {*} value - The value that will be set.
  15505. * @param {number} [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.
  15506. * @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.
  15507. * @return {boolean} True if the property was set, false if not.
  15508. */
  15509. Phaser.Group.prototype.setProperty = function (child, key, value, operation, force) {
  15510. if (typeof force === 'undefined') { force = false; }
  15511. operation = operation || 0;
  15512. // 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.
  15513. // 0 = Equals
  15514. // 1 = Add
  15515. // 2 = Subtract
  15516. // 3 = Multiply
  15517. // 4 = Divide
  15518. // We can't force a property in and the child doesn't have it, so abort.
  15519. // Equally we can't add, subtract, multiply or divide a property value if it doesn't exist, so abort in those cases too.
  15520. if (!this.hasProperty(child, key) && (!force || operation > 0))
  15521. {
  15522. return false;
  15523. }
  15524. var len = key.length;
  15525. if (len === 1)
  15526. {
  15527. if (operation === 0) { child[key[0]] = value; }
  15528. else if (operation == 1) { child[key[0]] += value; }
  15529. else if (operation == 2) { child[key[0]] -= value; }
  15530. else if (operation == 3) { child[key[0]] *= value; }
  15531. else if (operation == 4) { child[key[0]] /= value; }
  15532. }
  15533. else if (len === 2)
  15534. {
  15535. if (operation === 0) { child[key[0]][key[1]] = value; }
  15536. else if (operation == 1) { child[key[0]][key[1]] += value; }
  15537. else if (operation == 2) { child[key[0]][key[1]] -= value; }
  15538. else if (operation == 3) { child[key[0]][key[1]] *= value; }
  15539. else if (operation == 4) { child[key[0]][key[1]] /= value; }
  15540. }
  15541. else if (len === 3)
  15542. {
  15543. if (operation === 0) { child[key[0]][key[1]][key[2]] = value; }
  15544. else if (operation == 1) { child[key[0]][key[1]][key[2]] += value; }
  15545. else if (operation == 2) { child[key[0]][key[1]][key[2]] -= value; }
  15546. else if (operation == 3) { child[key[0]][key[1]][key[2]] *= value; }
  15547. else if (operation == 4) { child[key[0]][key[1]][key[2]] /= value; }
  15548. }
  15549. else if (len === 4)
  15550. {
  15551. if (operation === 0) { child[key[0]][key[1]][key[2]][key[3]] = value; }
  15552. else if (operation == 1) { child[key[0]][key[1]][key[2]][key[3]] += value; }
  15553. else if (operation == 2) { child[key[0]][key[1]][key[2]][key[3]] -= value; }
  15554. else if (operation == 3) { child[key[0]][key[1]][key[2]][key[3]] *= value; }
  15555. else if (operation == 4) { child[key[0]][key[1]][key[2]][key[3]] /= value; }
  15556. }
  15557. return true;
  15558. };
  15559. /**
  15560. * Checks a property for the given value on the child.
  15561. *
  15562. * @method Phaser.Group#checkProperty
  15563. * @param {*} child - The child to check the property value on.
  15564. * @param {array} key - An array of strings that make up the property that will be set.
  15565. * @param {*} value - The value that will be checked.
  15566. * @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.
  15567. * @return {boolean} True if the property was was equal to value, false if not.
  15568. */
  15569. Phaser.Group.prototype.checkProperty = function (child, key, value, force) {
  15570. if (typeof force === 'undefined') { force = false; }
  15571. // We can't force a property in and the child doesn't have it, so abort.
  15572. if (!Phaser.Utils.getProperty(child, key) && force)
  15573. {
  15574. return false;
  15575. }
  15576. if (Phaser.Utils.getProperty(child, key) !== value)
  15577. {
  15578. return false;
  15579. }
  15580. return true;
  15581. };
  15582. /**
  15583. * This function allows you to quickly set a property on a single child of this Group to a new value.
  15584. * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
  15585. *
  15586. * @method Phaser.Group#set
  15587. * @param {Phaser.Sprite} child - The child to set the property on.
  15588. * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
  15589. * @param {*} value - The value that will be set.
  15590. * @param {boolean} [checkAlive=false] - If set then the child will only be updated if alive=true.
  15591. * @param {boolean} [checkVisible=false] - If set then the child will only be updated if visible=true.
  15592. * @param {number} [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.
  15593. * @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.
  15594. * @return {boolean} True if the property was set, false if not.
  15595. */
  15596. Phaser.Group.prototype.set = function (child, key, value, checkAlive, checkVisible, operation, force) {
  15597. if (typeof force === 'undefined') { force = false; }
  15598. key = key.split('.');
  15599. if (typeof checkAlive === 'undefined') { checkAlive = false; }
  15600. if (typeof checkVisible === 'undefined') { checkVisible = false; }
  15601. if ((checkAlive === false || (checkAlive && child.alive)) && (checkVisible === false || (checkVisible && child.visible)))
  15602. {
  15603. return this.setProperty(child, key, value, operation, force);
  15604. }
  15605. };
  15606. /**
  15607. * This function allows you to quickly set the same property across all children of this Group to a new value.
  15608. * 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.
  15609. * If you need that ability please see `Group.setAllChildren`.
  15610. *
  15611. * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
  15612. *
  15613. * @method Phaser.Group#setAll
  15614. * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
  15615. * @param {*} value - The value that will be set.
  15616. * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children.
  15617. * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children.
  15618. * @param {number} [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.
  15619. * @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.
  15620. */
  15621. Phaser.Group.prototype.setAll = function (key, value, checkAlive, checkVisible, operation, force) {
  15622. if (typeof checkAlive === 'undefined') { checkAlive = false; }
  15623. if (typeof checkVisible === 'undefined') { checkVisible = false; }
  15624. if (typeof force === 'undefined') { force = false; }
  15625. key = key.split('.');
  15626. operation = operation || 0;
  15627. for (var i = 0, len = this.children.length; i < len; i++)
  15628. {
  15629. if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible)))
  15630. {
  15631. this.setProperty(this.children[i], key, value, operation, force);
  15632. }
  15633. }
  15634. };
  15635. /**
  15636. * This function allows you to quickly set the same property across all children of this Group, and any child Groups, to a new value.
  15637. *
  15638. * If this Group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom.
  15639. * Unlike with Group.setAll the property is NOT set on child Groups itself.
  15640. *
  15641. * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
  15642. *
  15643. * @method Phaser.Group#setAllChildren
  15644. * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
  15645. * @param {*} value - The value that will be set.
  15646. * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children.
  15647. * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children.
  15648. * @param {number} [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.
  15649. * @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.
  15650. */
  15651. Phaser.Group.prototype.setAllChildren = function (key, value, checkAlive, checkVisible, operation, force) {
  15652. if (typeof checkAlive === 'undefined') { checkAlive = false; }
  15653. if (typeof checkVisible === 'undefined') { checkVisible = false; }
  15654. if (typeof force === 'undefined') { force = false; }
  15655. operation = operation || 0;
  15656. for (var i = 0, len = this.children.length; i < len; i++)
  15657. {
  15658. if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible)))
  15659. {
  15660. if (this.children[i] instanceof Phaser.Group)
  15661. {
  15662. this.children[i].setAllChildren(key, value, checkAlive, checkVisible, operation, force);
  15663. }
  15664. else
  15665. {
  15666. this.setProperty(this.children[i], key.split('.'), value, operation, force);
  15667. }
  15668. }
  15669. }
  15670. };
  15671. /**
  15672. * This function allows you to quickly check that the same property across all children of this Group is equal to the given value.
  15673. * 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.
  15674. *
  15675. * @method Phaser.Group#checkAll
  15676. * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
  15677. * @param {*} value - The value that will be checked.
  15678. * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children.
  15679. * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children.
  15680. * @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.
  15681. */
  15682. Phaser.Group.prototype.checkAll = function (key, value, checkAlive, checkVisible, force) {
  15683. if (typeof checkAlive === 'undefined') { checkAlive = false; }
  15684. if (typeof checkVisible === 'undefined') { checkVisible = false; }
  15685. if (typeof force === 'undefined') { force = false; }
  15686. for (var i = 0, len = this.children.length; i < len; i++)
  15687. {
  15688. if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible)))
  15689. {
  15690. if (!this.checkProperty(this.children[i], key, value, force))
  15691. {
  15692. return false;
  15693. }
  15694. }
  15695. }
  15696. return true;
  15697. };
  15698. /**
  15699. * Adds the amount to the given property on all children in this Group.
  15700. * Group.addAll('x', 10) will add 10 to the child.x value.
  15701. *
  15702. * @method Phaser.Group#addAll
  15703. * @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'.
  15704. * @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50.
  15705. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  15706. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  15707. */
  15708. Phaser.Group.prototype.addAll = function (property, amount, checkAlive, checkVisible) {
  15709. this.setAll(property, amount, checkAlive, checkVisible, 1);
  15710. };
  15711. /**
  15712. * Subtracts the amount from the given property on all children in this Group.
  15713. * Group.subAll('x', 10) will minus 10 from the child.x value.
  15714. *
  15715. * @method Phaser.Group#subAll
  15716. * @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'.
  15717. * @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10.
  15718. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  15719. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  15720. */
  15721. Phaser.Group.prototype.subAll = function (property, amount, checkAlive, checkVisible) {
  15722. this.setAll(property, amount, checkAlive, checkVisible, 2);
  15723. };
  15724. /**
  15725. * Multiplies the given property by the amount on all children in this Group.
  15726. * Group.multiplyAll('x', 2) will x2 the child.x value.
  15727. *
  15728. * @method Phaser.Group#multiplyAll
  15729. * @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'.
  15730. * @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20.
  15731. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  15732. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  15733. */
  15734. Phaser.Group.prototype.multiplyAll = function (property, amount, checkAlive, checkVisible) {
  15735. this.setAll(property, amount, checkAlive, checkVisible, 3);
  15736. };
  15737. /**
  15738. * Divides the given property by the amount on all children in this Group.
  15739. * Group.divideAll('x', 2) will half the child.x value.
  15740. *
  15741. * @method Phaser.Group#divideAll
  15742. * @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'.
  15743. * @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50.
  15744. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  15745. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  15746. */
  15747. Phaser.Group.prototype.divideAll = function (property, amount, checkAlive, checkVisible) {
  15748. this.setAll(property, amount, checkAlive, checkVisible, 4);
  15749. };
  15750. /**
  15751. * Calls a function on all of the children that have exists=true in this Group.
  15752. * After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback.
  15753. *
  15754. * @method Phaser.Group#callAllExists
  15755. * @param {function} callback - The function that exists on the children that will be called.
  15756. * @param {boolean} existsValue - Only children with exists=existsValue will be called.
  15757. * @param {...*} parameter - Additional parameters that will be passed to the callback.
  15758. */
  15759. Phaser.Group.prototype.callAllExists = function (callback, existsValue) {
  15760. var args = Array.prototype.splice.call(arguments, 2);
  15761. for (var i = 0, len = this.children.length; i < len; i++)
  15762. {
  15763. if (this.children[i].exists === existsValue && this.children[i][callback])
  15764. {
  15765. this.children[i][callback].apply(this.children[i], args);
  15766. }
  15767. }
  15768. };
  15769. /**
  15770. * Returns a reference to a function that exists on a child of the Group based on the given callback array.
  15771. *
  15772. * @method Phaser.Group#callbackFromArray
  15773. * @param {object} child - The object to inspect.
  15774. * @param {array} callback - The array of function names.
  15775. * @param {number} length - The size of the array (pre-calculated in callAll).
  15776. * @protected
  15777. */
  15778. Phaser.Group.prototype.callbackFromArray = function (child, callback, length) {
  15779. // Kinda looks like a Christmas tree
  15780. if (length == 1)
  15781. {
  15782. if (child[callback[0]])
  15783. {
  15784. return child[callback[0]];
  15785. }
  15786. }
  15787. else if (length == 2)
  15788. {
  15789. if (child[callback[0]][callback[1]])
  15790. {
  15791. return child[callback[0]][callback[1]];
  15792. }
  15793. }
  15794. else if (length == 3)
  15795. {
  15796. if (child[callback[0]][callback[1]][callback[2]])
  15797. {
  15798. return child[callback[0]][callback[1]][callback[2]];
  15799. }
  15800. }
  15801. else if (length == 4)
  15802. {
  15803. if (child[callback[0]][callback[1]][callback[2]][callback[3]])
  15804. {
  15805. return child[callback[0]][callback[1]][callback[2]][callback[3]];
  15806. }
  15807. }
  15808. else
  15809. {
  15810. if (child[callback])
  15811. {
  15812. return child[callback];
  15813. }
  15814. }
  15815. return false;
  15816. };
  15817. /**
  15818. * Calls a function on all of the children regardless if they are dead or alive (see callAllExists if you need control over that)
  15819. * After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child.
  15820. *
  15821. * @method Phaser.Group#callAll
  15822. * @param {string} method - A string containing the name of the function that will be called. The function must exist on the child.
  15823. * @param {string} [context=null] - A string containing the context under which the method will be executed. Set to null to default to the child.
  15824. * @param {...*} parameter - Additional parameters that will be passed to the method.
  15825. */
  15826. Phaser.Group.prototype.callAll = function (method, context) {
  15827. if (typeof method === 'undefined')
  15828. {
  15829. return;
  15830. }
  15831. // Extract the method into an array
  15832. method = method.split('.');
  15833. var methodLength = method.length;
  15834. if (typeof context === 'undefined' || context === null || context === '')
  15835. {
  15836. context = null;
  15837. }
  15838. else
  15839. {
  15840. // Extract the context into an array
  15841. if (typeof context === 'string')
  15842. {
  15843. context = context.split('.');
  15844. var contextLength = context.length;
  15845. }
  15846. }
  15847. var args = Array.prototype.splice.call(arguments, 2);
  15848. var callback = null;
  15849. var callbackContext = null;
  15850. for (var i = 0, len = this.children.length; i < len; i++)
  15851. {
  15852. callback = this.callbackFromArray(this.children[i], method, methodLength);
  15853. if (context && callback)
  15854. {
  15855. callbackContext = this.callbackFromArray(this.children[i], context, contextLength);
  15856. if (callback)
  15857. {
  15858. callback.apply(callbackContext, args);
  15859. }
  15860. }
  15861. else if (callback)
  15862. {
  15863. callback.apply(this.children[i], args);
  15864. }
  15865. }
  15866. };
  15867. /**
  15868. * The core preUpdate - as called by World.
  15869. * @method Phaser.Group#preUpdate
  15870. * @protected
  15871. */
  15872. Phaser.Group.prototype.preUpdate = function () {
  15873. if (!this.exists || !this.parent.exists)
  15874. {
  15875. this.renderOrderID = -1;
  15876. return false;
  15877. }
  15878. var i = this.children.length;
  15879. while (i--)
  15880. {
  15881. this.children[i].preUpdate();
  15882. }
  15883. return true;
  15884. };
  15885. /**
  15886. * The core update - as called by World.
  15887. * @method Phaser.Group#update
  15888. * @protected
  15889. */
  15890. Phaser.Group.prototype.update = function () {
  15891. var i = this.children.length;
  15892. while (i--)
  15893. {
  15894. this.children[i].update();
  15895. }
  15896. };
  15897. /**
  15898. * The core postUpdate - as called by World.
  15899. * @method Phaser.Group#postUpdate
  15900. * @protected
  15901. */
  15902. Phaser.Group.prototype.postUpdate = function () {
  15903. // Fixed to Camera?
  15904. if (this._cache[7] === 1)
  15905. {
  15906. this.x = this.game.camera.view.x + this.cameraOffset.x;
  15907. this.y = this.game.camera.view.y + this.cameraOffset.y;
  15908. }
  15909. var i = this.children.length;
  15910. while (i--)
  15911. {
  15912. this.children[i].postUpdate();
  15913. }
  15914. };
  15915. /**
  15916. * Allows you to call your own function on each member of this Group. You must pass the callback and context in which it will run.
  15917. * After the checkExists parameter you can add as many parameters as you like, which will all be passed to the callback along with the child.
  15918. * For example: Group.forEach(awardBonusGold, this, true, 100, 500)
  15919. * Note: Currently this will skip any children which are Groups themselves.
  15920. *
  15921. * @method Phaser.Group#forEach
  15922. * @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter.
  15923. * @param {Object} callbackContext - The context in which the function should be called (usually 'this').
  15924. * @param {boolean} [checkExists=false] - If set only children with exists=true will be passed to the callback, otherwise all children will be passed.
  15925. */
  15926. Phaser.Group.prototype.forEach = function (callback, callbackContext, checkExists) {
  15927. if (typeof checkExists === 'undefined') { checkExists = false; }
  15928. var args = Array.prototype.splice.call(arguments, 3);
  15929. args.unshift(null);
  15930. for (var i = 0, len = this.children.length; i < len; i++)
  15931. {
  15932. if (!checkExists || (checkExists && this.children[i].exists))
  15933. {
  15934. args[0] = this.children[i];
  15935. callback.apply(callbackContext, args);
  15936. }
  15937. }
  15938. };
  15939. /**
  15940. * Allows you to call your own function on each member of this Group where child.exists=true. You must pass the callback and context in which it will run.
  15941. * You can add as many parameters as you like, which will all be passed to the callback along with the child.
  15942. * For example: Group.forEachExists(causeDamage, this, 500)
  15943. *
  15944. * @method Phaser.Group#forEachExists
  15945. * @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter.
  15946. * @param {Object} callbackContext - The context in which the function should be called (usually 'this').
  15947. */
  15948. Phaser.Group.prototype.forEachExists = function (callback, callbackContext) {
  15949. var args = Array.prototype.splice.call(arguments, 2);
  15950. args.unshift(null);
  15951. this.iterate('exists', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
  15952. };
  15953. /**
  15954. * Allows you to call your own function on each alive member of this Group (where child.alive=true). You must pass the callback and context in which it will run.
  15955. * You can add as many parameters as you like, which will all be passed to the callback along with the child.
  15956. * For example: Group.forEachAlive(causeDamage, this, 500)
  15957. *
  15958. * @method Phaser.Group#forEachAlive
  15959. * @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter.
  15960. * @param {Object} callbackContext - The context in which the function should be called (usually 'this').
  15961. */
  15962. Phaser.Group.prototype.forEachAlive = function (callback, callbackContext) {
  15963. var args = Array.prototype.splice.call(arguments, 2);
  15964. args.unshift(null);
  15965. this.iterate('alive', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
  15966. };
  15967. /**
  15968. * Allows you to call your own function on each dead member of this Group (where alive=false). You must pass the callback and context in which it will run.
  15969. * You can add as many parameters as you like, which will all be passed to the callback along with the child.
  15970. * For example: Group.forEachDead(bringToLife, this)
  15971. *
  15972. * @method Phaser.Group#forEachDead
  15973. * @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter.
  15974. * @param {Object} callbackContext - The context in which the function should be called (usually 'this').
  15975. */
  15976. Phaser.Group.prototype.forEachDead = function (callback, callbackContext) {
  15977. var args = Array.prototype.splice.call(arguments, 2);
  15978. args.unshift(null);
  15979. this.iterate('alive', false, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
  15980. };
  15981. /**
  15982. * Call this function to sort the group according to a particular value and order.
  15983. * 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()`.
  15984. *
  15985. * @method Phaser.Group#sort
  15986. * @param {string} [index='z'] - The `string` name of the property you want to sort on. Defaults to the objects z-depth value.
  15987. * @param {number} [order=Phaser.Group.SORT_ASCENDING] - The `Group` constant that defines the sort order. Possible values are Phaser.Group.SORT_ASCENDING and Phaser.Group.SORT_DESCENDING.
  15988. */
  15989. Phaser.Group.prototype.sort = function (index, order) {
  15990. if (this.children.length < 2)
  15991. {
  15992. // Nothing to swap
  15993. return;
  15994. }
  15995. if (typeof index === 'undefined') { index = 'z'; }
  15996. if (typeof order === 'undefined') { order = Phaser.Group.SORT_ASCENDING; }
  15997. this._sortProperty = index;
  15998. if (order === Phaser.Group.SORT_ASCENDING)
  15999. {
  16000. this.children.sort(this.ascendingSortHandler.bind(this));
  16001. }
  16002. else
  16003. {
  16004. this.children.sort(this.descendingSortHandler.bind(this));
  16005. }
  16006. this.updateZ();
  16007. };
  16008. /**
  16009. * This allows you to use your own sort handler function.
  16010. * It will be sent two parameters: the two children involved in the comparison (a and b). It should return -1 if a > b, 1 if a < b or 0 if a === b.
  16011. *
  16012. * @method Phaser.Group#customSort
  16013. * @param {function} sortHandler - Your sort handler function. It will be sent two parameters: the two children involved in the comparison. It must return -1, 1 or 0.
  16014. * @param {object} context - The scope in which the sortHandler is called.
  16015. */
  16016. Phaser.Group.prototype.customSort = function (sortHandler, context) {
  16017. if (this.children.length < 2)
  16018. {
  16019. // Nothing to swap
  16020. return;
  16021. }
  16022. this.children.sort(sortHandler.bind(context));
  16023. this.updateZ();
  16024. };
  16025. /**
  16026. * An internal helper function for the sort process.
  16027. *
  16028. * @method Phaser.Group#ascendingSortHandler
  16029. * @param {object} a - The first object being sorted.
  16030. * @param {object} b - The second object being sorted.
  16031. */
  16032. Phaser.Group.prototype.ascendingSortHandler = function (a, b) {
  16033. if (a[this._sortProperty] < b[this._sortProperty])
  16034. {
  16035. return -1;
  16036. }
  16037. else if (a[this._sortProperty] > b[this._sortProperty])
  16038. {
  16039. return 1;
  16040. }
  16041. else
  16042. {
  16043. if (a.z < b.z)
  16044. {
  16045. return -1;
  16046. }
  16047. else
  16048. {
  16049. return 1;
  16050. }
  16051. }
  16052. };
  16053. /**
  16054. * An internal helper function for the sort process.
  16055. *
  16056. * @method Phaser.Group#descendingSortHandler
  16057. * @param {object} a - The first object being sorted.
  16058. * @param {object} b - The second object being sorted.
  16059. */
  16060. Phaser.Group.prototype.descendingSortHandler = function (a, b) {
  16061. if (a[this._sortProperty] < b[this._sortProperty])
  16062. {
  16063. return 1;
  16064. }
  16065. else if (a[this._sortProperty] > b[this._sortProperty])
  16066. {
  16067. return -1;
  16068. }
  16069. else
  16070. {
  16071. return 0;
  16072. }
  16073. };
  16074. /**
  16075. * Iterates over the children of the Group. When a child has a property matching key that equals the given value, it is considered as a match.
  16076. * Matched children can be sent to the optional callback, or simply returned or counted.
  16077. * You can add as many callback parameters as you like, which will all be passed to the callback along with the child, after the callbackContext parameter.
  16078. *
  16079. * @method Phaser.Group#iterate
  16080. * @param {string} key - The child property to check, i.e. 'exists', 'alive', 'health'
  16081. * @param {any} value - If child.key === this value it will be considered a match. Note that a strict comparison is used.
  16082. * @param {number} returnType - How to return the data from this method. Either Phaser.Group.RETURN_NONE, Phaser.Group.RETURN_TOTAL or Phaser.Group.RETURN_CHILD.
  16083. * @param {function} [callback=null] - Optional function that will be called on each matching child. Each child of the Group will be passed to it as its first parameter.
  16084. * @param {Object} [callbackContext] - The context in which the function should be called (usually 'this').
  16085. * @return {any} Returns either a numeric total (if RETURN_TOTAL was specified) or the child object.
  16086. */
  16087. Phaser.Group.prototype.iterate = function (key, value, returnType, callback, callbackContext, args) {
  16088. if (returnType === Phaser.Group.RETURN_TOTAL && this.children.length === 0)
  16089. {
  16090. return 0;
  16091. }
  16092. if (typeof callback === 'undefined')
  16093. {
  16094. callback = false;
  16095. }
  16096. var total = 0;
  16097. for (var i = 0, len = this.children.length; i < len; i++)
  16098. {
  16099. if (this.children[i][key] === value)
  16100. {
  16101. total++;
  16102. if (callback)
  16103. {
  16104. args[0] = this.children[i];
  16105. callback.apply(callbackContext, args);
  16106. }
  16107. if (returnType === Phaser.Group.RETURN_CHILD)
  16108. {
  16109. return this.children[i];
  16110. }
  16111. }
  16112. }
  16113. if (returnType === Phaser.Group.RETURN_TOTAL)
  16114. {
  16115. return total;
  16116. }
  16117. else if (returnType === Phaser.Group.RETURN_CHILD)
  16118. {
  16119. return null;
  16120. }
  16121. };
  16122. /**
  16123. * Call this function to retrieve the first object with exists == (the given state) in the Group.
  16124. *
  16125. * @method Phaser.Group#getFirstExists
  16126. * @param {boolean} state - True or false.
  16127. * @return {Any} The first child, or null if none found.
  16128. */
  16129. Phaser.Group.prototype.getFirstExists = function (state) {
  16130. if (typeof state !== 'boolean')
  16131. {
  16132. state = true;
  16133. }
  16134. return this.iterate('exists', state, Phaser.Group.RETURN_CHILD);
  16135. };
  16136. /**
  16137. * Call this function to retrieve the first object with alive === true in the group.
  16138. * This is handy for checking if everything has been wiped out, or choosing a squad leader, etc.
  16139. *
  16140. * @method Phaser.Group#getFirstAlive
  16141. * @return {Any} The first alive child, or null if none found.
  16142. */
  16143. Phaser.Group.prototype.getFirstAlive = function () {
  16144. return this.iterate('alive', true, Phaser.Group.RETURN_CHILD);
  16145. };
  16146. /**
  16147. * Call this function to retrieve the first object with alive === false in the group.
  16148. * This is handy for checking if everything has been wiped out, or choosing a squad leader, etc.
  16149. *
  16150. * @method Phaser.Group#getFirstDead
  16151. * @return {Any} The first dead child, or null if none found.
  16152. */
  16153. Phaser.Group.prototype.getFirstDead = function () {
  16154. return this.iterate('alive', false, Phaser.Group.RETURN_CHILD);
  16155. };
  16156. /**
  16157. * Returns the child at the top of this Group. The top is the one being displayed (rendered) above every other child.
  16158. *
  16159. * @method Phaser.Group#getTop
  16160. * @return {Any} The child at the top of the Group.
  16161. */
  16162. Phaser.Group.prototype.getTop = function () {
  16163. if (this.children.length > 0)
  16164. {
  16165. return this.children[this.children.length - 1];
  16166. }
  16167. };
  16168. /**
  16169. * Returns the child at the bottom of this Group. The bottom is the one being displayed (rendered) below every other child.
  16170. *
  16171. * @method Phaser.Group#getBottom
  16172. * @return {Any} The child at the bottom of the Group.
  16173. */
  16174. Phaser.Group.prototype.getBottom = function () {
  16175. if (this.children.length > 0)
  16176. {
  16177. return this.children[0];
  16178. }
  16179. };
  16180. /**
  16181. * Call this function to find out how many members of the group are alive.
  16182. *
  16183. * @method Phaser.Group#countLiving
  16184. * @return {number} The number of children flagged as alive.
  16185. */
  16186. Phaser.Group.prototype.countLiving = function () {
  16187. return this.iterate('alive', true, Phaser.Group.RETURN_TOTAL);
  16188. };
  16189. /**
  16190. * Call this function to find out how many members of the group are dead.
  16191. *
  16192. * @method Phaser.Group#countDead
  16193. * @return {number} The number of children flagged as dead.
  16194. */
  16195. Phaser.Group.prototype.countDead = function () {
  16196. return this.iterate('alive', false, Phaser.Group.RETURN_TOTAL);
  16197. };
  16198. /**
  16199. * Returns a member at random from the group.
  16200. *
  16201. * @method Phaser.Group#getRandom
  16202. * @param {number} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array.
  16203. * @param {number} length - Optional restriction on the number of values you want to randomly select from.
  16204. * @return {Any} A random child of this Group.
  16205. */
  16206. Phaser.Group.prototype.getRandom = function (startIndex, length) {
  16207. if (this.children.length === 0)
  16208. {
  16209. return null;
  16210. }
  16211. startIndex = startIndex || 0;
  16212. length = length || this.children.length;
  16213. return this.game.math.getRandom(this.children, startIndex, length);
  16214. };
  16215. /**
  16216. * Removes the given child from this Group. This will dispatch an onRemovedFromGroup event from the child (if it has one),
  16217. * reset the Group cursor and optionally destroy the child.
  16218. *
  16219. * @method Phaser.Group#remove
  16220. * @param {Any} child - The child to remove.
  16221. * @param {boolean} [destroy=false] - You can optionally call destroy on the child that was removed.
  16222. * @param {boolean} [silent=false] - If the silent parameter is `true` the child will not dispatch the onRemovedFromGroup event.
  16223. * @return {boolean} true if the child was removed from this Group, otherwise false.
  16224. */
  16225. Phaser.Group.prototype.remove = function (child, destroy, silent) {
  16226. if (typeof destroy === 'undefined') { destroy = false; }
  16227. if (typeof silent === 'undefined') { silent = false; }
  16228. if (this.children.length === 0 || this.children.indexOf(child) === -1)
  16229. {
  16230. return false;
  16231. }
  16232. if (!silent && child.events && !child.destroyPhase)
  16233. {
  16234. child.events.onRemovedFromGroup.dispatch(child, this);
  16235. }
  16236. var removed = this.removeChild(child);
  16237. this.updateZ();
  16238. if (this.cursor === child)
  16239. {
  16240. this.next();
  16241. }
  16242. if (destroy && removed)
  16243. {
  16244. removed.destroy(true);
  16245. }
  16246. return true;
  16247. };
  16248. /**
  16249. * Removes all children from this Group, setting the group properties of the children to `null`.
  16250. * The Group container remains on the display list.
  16251. *
  16252. * @method Phaser.Group#removeAll
  16253. * @param {boolean} [destroy=false] - You can optionally call destroy on each child that is removed.
  16254. * @param {boolean} [silent=false] - If the silent parameter is `true` the children will not dispatch their onRemovedFromGroup events.
  16255. */
  16256. Phaser.Group.prototype.removeAll = function (destroy, silent) {
  16257. if (typeof destroy === 'undefined') { destroy = false; }
  16258. if (typeof silent === 'undefined') { silent = false; }
  16259. if (this.children.length === 0)
  16260. {
  16261. return;
  16262. }
  16263. do
  16264. {
  16265. if (!silent && this.children[0].events)
  16266. {
  16267. this.children[0].events.onRemovedFromGroup.dispatch(this.children[0], this);
  16268. }
  16269. var removed = this.removeChild(this.children[0]);
  16270. if (destroy && removed)
  16271. {
  16272. removed.destroy(true);
  16273. }
  16274. }
  16275. while (this.children.length > 0);
  16276. this.cursor = null;
  16277. };
  16278. /**
  16279. * Removes all children from this Group whos index falls beteen the given startIndex and endIndex values.
  16280. *
  16281. * @method Phaser.Group#removeBetween
  16282. * @param {number} startIndex - The index to start removing children from.
  16283. * @param {number} [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.
  16284. * @param {boolean} [destroy=false] - You can optionally call destroy on the child that was removed.
  16285. * @param {boolean} [silent=false] - If the silent parameter is `true` the children will not dispatch their onRemovedFromGroup events.
  16286. */
  16287. Phaser.Group.prototype.removeBetween = function (startIndex, endIndex, destroy, silent) {
  16288. if (typeof endIndex === 'undefined') { endIndex = this.children.length; }
  16289. if (typeof destroy === 'undefined') { destroy = false; }
  16290. if (typeof silent === 'undefined') { silent = false; }
  16291. if (this.children.length === 0)
  16292. {
  16293. return;
  16294. }
  16295. if (startIndex > endIndex || startIndex < 0 || endIndex > this.children.length)
  16296. {
  16297. return false;
  16298. }
  16299. var i = endIndex;
  16300. while (i >= startIndex)
  16301. {
  16302. if (!silent && this.children[i].events)
  16303. {
  16304. this.children[i].events.onRemovedFromGroup.dispatch(this.children[i], this);
  16305. }
  16306. var removed = this.removeChild(this.children[i]);
  16307. if (destroy && removed)
  16308. {
  16309. removed.destroy(true);
  16310. }
  16311. if (this.cursor === this.children[i])
  16312. {
  16313. this.cursor = null;
  16314. }
  16315. i--;
  16316. }
  16317. this.updateZ();
  16318. };
  16319. /**
  16320. * Destroys this Group. Removes all children, then removes the container from the display list and nulls references.
  16321. *
  16322. * @method Phaser.Group#destroy
  16323. * @param {boolean} [destroyChildren=true] - Should every child of this Group have its destroy method called?
  16324. * @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.
  16325. */
  16326. Phaser.Group.prototype.destroy = function (destroyChildren, soft) {
  16327. if (this.game === null) { return; }
  16328. if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
  16329. if (typeof soft === 'undefined') { soft = false; }
  16330. this.removeAll(destroyChildren);
  16331. this.cursor = null;
  16332. this.filters = null;
  16333. if (!soft)
  16334. {
  16335. if (this.parent)
  16336. {
  16337. this.parent.removeChild(this);
  16338. }
  16339. this.game = null;
  16340. this.exists = false;
  16341. }
  16342. };
  16343. /**
  16344. * @name Phaser.Group#total
  16345. * @property {number} total - The total number of children in this Group who have a state of exists = true.
  16346. * @readonly
  16347. */
  16348. Object.defineProperty(Phaser.Group.prototype, "total", {
  16349. get: function () {
  16350. return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL);
  16351. }
  16352. });
  16353. /**
  16354. * @name Phaser.Group#length
  16355. * @property {number} length - The total number of children in this Group, regardless of their exists/alive status.
  16356. * @readonly
  16357. */
  16358. Object.defineProperty(Phaser.Group.prototype, "length", {
  16359. get: function () {
  16360. return this.children.length;
  16361. }
  16362. });
  16363. /**
  16364. * The angle of rotation of the Group container. This will adjust the Group container itself by modifying its rotation.
  16365. * This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position.
  16366. * @name Phaser.Group#angle
  16367. * @property {number} angle - The angle of rotation given in degrees, where 0 degrees = to the right.
  16368. */
  16369. Object.defineProperty(Phaser.Group.prototype, "angle", {
  16370. get: function() {
  16371. return Phaser.Math.radToDeg(this.rotation);
  16372. },
  16373. set: function(value) {
  16374. this.rotation = Phaser.Math.degToRad(value);
  16375. }
  16376. });
  16377. /**
  16378. * 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.
  16379. * Note that the cameraOffset values are in addition to any parent in the display list.
  16380. * So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x
  16381. *
  16382. * @name Phaser.Group#fixedToCamera
  16383. * @property {boolean} fixedToCamera - Set to true to fix this Group to the Camera at its current world coordinates.
  16384. */
  16385. Object.defineProperty(Phaser.Group.prototype, "fixedToCamera", {
  16386. get: function () {
  16387. return !!this._cache[7];
  16388. },
  16389. set: function (value) {
  16390. if (value)
  16391. {
  16392. this._cache[7] = 1;
  16393. this.cameraOffset.set(this.x, this.y);
  16394. }
  16395. else
  16396. {
  16397. this._cache[7] = 0;
  16398. }
  16399. }
  16400. });
  16401. // Documentation stubs
  16402. /**
  16403. * The x coordinate of the Group container. You can adjust the Group container itself by modifying its coordinates.
  16404. * This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position.
  16405. * @name Phaser.Group#x
  16406. * @property {number} x - The x coordinate of the Group container.
  16407. */
  16408. /**
  16409. * The y coordinate of the Group container. You can adjust the Group container itself by modifying its coordinates.
  16410. * This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position.
  16411. * @name Phaser.Group#y
  16412. * @property {number} y - The y coordinate of the Group container.
  16413. */
  16414. /**
  16415. * The angle of rotation of the Group container. This will adjust the Group container itself by modifying its rotation.
  16416. * This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position.
  16417. * @name Phaser.Group#rotation
  16418. * @property {number} rotation - The angle of rotation given in radians.
  16419. */
  16420. /**
  16421. * @name Phaser.Group#visible
  16422. * @property {boolean} visible - The visible state of the Group. Non-visible Groups and all of their children are not rendered.
  16423. */
  16424. /**
  16425. * @name Phaser.Group#alpha
  16426. * @property {number} alpha - The alpha value of the Group container.
  16427. */
  16428. /**
  16429. * @author Richard Davey <rich@photonstorm.com>
  16430. * @copyright 2014 Photon Storm Ltd.
  16431. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  16432. */
  16433. /**
  16434. * "This world is but a canvas to our imagination." - Henry David Thoreau
  16435. *
  16436. * A game has only one world. The world is an abstract place in which all game objects live. It is not bound
  16437. * by stage limits and can be any size. You look into the world via cameras. All game objects live within
  16438. * the world at world-based coordinates. By default a world is created the same size as your Stage.
  16439. *
  16440. * @class Phaser.World
  16441. * @extends Phaser.Group
  16442. * @constructor
  16443. * @param {Phaser.Game} game - Reference to the current game instance.
  16444. */
  16445. Phaser.World = function (game) {
  16446. Phaser.Group.call(this, game, null, '__world', false);
  16447. /**
  16448. * 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.
  16449. * 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.
  16450. * 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.
  16451. * 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.
  16452. * @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from.
  16453. */
  16454. this.bounds = new Phaser.Rectangle(0, 0, game.width, game.height);
  16455. /**
  16456. * @property {Phaser.Camera} camera - Camera instance.
  16457. */
  16458. this.camera = null;
  16459. };
  16460. Phaser.World.prototype = Object.create(Phaser.Group.prototype);
  16461. Phaser.World.prototype.constructor = Phaser.World;
  16462. /**
  16463. * Initialises the game world.
  16464. *
  16465. * @method Phaser.World#boot
  16466. * @protected
  16467. */
  16468. Phaser.World.prototype.boot = function () {
  16469. this.camera = new Phaser.Camera(this.game, 0, 0, 0, this.game.width, this.game.height);
  16470. this.camera.displayObject = this;
  16471. this.camera.scale = this.scale;
  16472. this.game.camera = this.camera;
  16473. this.game.stage.addChild(this);
  16474. };
  16475. /**
  16476. * Updates the size of this world. Note that this doesn't modify the world x/y coordinates, just the width and height.
  16477. *
  16478. * @method Phaser.World#setBounds
  16479. * @param {number} x - Top left most corner of the world.
  16480. * @param {number} y - Top left most corner of the world.
  16481. * @param {number} width - New width of the world. Can never be smaller than the Game.width.
  16482. * @param {number} height - New height of the world. Can never be smaller than the Game.height.
  16483. */
  16484. Phaser.World.prototype.setBounds = function (x, y, width, height) {
  16485. if (width < this.game.width)
  16486. {
  16487. width = this.game.width;
  16488. }
  16489. if (height < this.game.height)
  16490. {
  16491. height = this.game.height;
  16492. }
  16493. this.bounds.setTo(x, y, width, height);
  16494. if (this.camera.bounds)
  16495. {
  16496. // The Camera can never be smaller than the game size
  16497. this.camera.bounds.setTo(x, y, width, height);
  16498. }
  16499. this.game.physics.setBoundsToWorld();
  16500. };
  16501. /**
  16502. * Destroyer of worlds.
  16503. *
  16504. * @method Phaser.World#shutdown
  16505. */
  16506. Phaser.World.prototype.shutdown = function () {
  16507. // World is a Group, so run a soft destruction on this and all children.
  16508. this.destroy(true, true);
  16509. };
  16510. /**
  16511. * This will take the given game object and check if its x/y coordinates fall outside of the world bounds.
  16512. * If they do it will reposition the object to the opposite side of the world, creating a wrap-around effect.
  16513. *
  16514. * @method Phaser.World#wrap
  16515. * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text} sprite - The object you wish to wrap around the world bounds.
  16516. * @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.
  16517. * @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.
  16518. * @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally.
  16519. * @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically.
  16520. */
  16521. Phaser.World.prototype.wrap = function (sprite, padding, useBounds, horizontal, vertical) {
  16522. if (typeof padding === 'undefined') { padding = 0; }
  16523. if (typeof useBounds === 'undefined') { useBounds = false; }
  16524. if (typeof horizontal === 'undefined') { horizontal = true; }
  16525. if (typeof vertical === 'undefined') { vertical = true; }
  16526. if (!useBounds)
  16527. {
  16528. if (horizontal && sprite.x + padding < this.bounds.x)
  16529. {
  16530. sprite.x = this.bounds.right + padding;
  16531. }
  16532. else if (horizontal && sprite.x - padding > this.bounds.right)
  16533. {
  16534. sprite.x = this.bounds.left - padding;
  16535. }
  16536. if (vertical && sprite.y + padding < this.bounds.top)
  16537. {
  16538. sprite.y = this.bounds.bottom + padding;
  16539. }
  16540. else if (vertical && sprite.y - padding > this.bounds.bottom)
  16541. {
  16542. sprite.y = this.bounds.top - padding;
  16543. }
  16544. }
  16545. else
  16546. {
  16547. sprite.getBounds();
  16548. if (horizontal)
  16549. {
  16550. if ((sprite.x + sprite._currentBounds.width) < this.bounds.x)
  16551. {
  16552. sprite.x = this.bounds.right;
  16553. }
  16554. else if (sprite.x > this.bounds.right)
  16555. {
  16556. sprite.x = this.bounds.left;
  16557. }
  16558. }
  16559. if (vertical)
  16560. {
  16561. if ((sprite.y + sprite._currentBounds.height) < this.bounds.top)
  16562. {
  16563. sprite.y = this.bounds.bottom;
  16564. }
  16565. else if (sprite.y > this.bounds.bottom)
  16566. {
  16567. sprite.y = this.bounds.top;
  16568. }
  16569. }
  16570. }
  16571. };
  16572. /**
  16573. * @name Phaser.World#width
  16574. * @property {number} width - Gets or sets the current width of the game world.
  16575. */
  16576. Object.defineProperty(Phaser.World.prototype, "width", {
  16577. get: function () {
  16578. return this.bounds.width;
  16579. },
  16580. set: function (value) {
  16581. this.bounds.width = value;
  16582. }
  16583. });
  16584. /**
  16585. * @name Phaser.World#height
  16586. * @property {number} height - Gets or sets the current height of the game world.
  16587. */
  16588. Object.defineProperty(Phaser.World.prototype, "height", {
  16589. get: function () {
  16590. return this.bounds.height;
  16591. },
  16592. set: function (value) {
  16593. this.bounds.height = value;
  16594. }
  16595. });
  16596. /**
  16597. * @name Phaser.World#centerX
  16598. * @property {number} centerX - Gets the X position corresponding to the center point of the world.
  16599. * @readonly
  16600. */
  16601. Object.defineProperty(Phaser.World.prototype, "centerX", {
  16602. get: function () {
  16603. return this.bounds.halfWidth;
  16604. }
  16605. });
  16606. /**
  16607. * @name Phaser.World#centerY
  16608. * @property {number} centerY - Gets the Y position corresponding to the center point of the world.
  16609. * @readonly
  16610. */
  16611. Object.defineProperty(Phaser.World.prototype, "centerY", {
  16612. get: function () {
  16613. return this.bounds.halfHeight;
  16614. }
  16615. });
  16616. /**
  16617. * @name Phaser.World#randomX
  16618. * @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world.
  16619. * @readonly
  16620. */
  16621. Object.defineProperty(Phaser.World.prototype, "randomX", {
  16622. get: function () {
  16623. if (this.bounds.x < 0)
  16624. {
  16625. return this.game.rnd.integerInRange(this.bounds.x, (this.bounds.width - Math.abs(this.bounds.x)));
  16626. }
  16627. else
  16628. {
  16629. return this.game.rnd.integerInRange(this.bounds.x, this.bounds.width);
  16630. }
  16631. }
  16632. });
  16633. /**
  16634. * @name Phaser.World#randomY
  16635. * @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world.
  16636. * @readonly
  16637. */
  16638. Object.defineProperty(Phaser.World.prototype, "randomY", {
  16639. get: function () {
  16640. if (this.bounds.y < 0)
  16641. {
  16642. return this.game.rnd.integerInRange(this.bounds.y, (this.bounds.height - Math.abs(this.bounds.y)));
  16643. }
  16644. else
  16645. {
  16646. return this.game.rnd.integerInRange(this.bounds.y, this.bounds.height);
  16647. }
  16648. }
  16649. });
  16650. /**
  16651. * @author Richard Davey <rich@photonstorm.com>
  16652. * @copyright 2014 Photon Storm Ltd.
  16653. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  16654. */
  16655. /**
  16656. * The ScaleManager object is responsible for helping you manage the scaling, resizing and alignment of your game within the browser.
  16657. *
  16658. * @class Phaser.ScaleManager
  16659. * @constructor
  16660. * @param {Phaser.Game} game - A reference to the currently running game.
  16661. * @param {number} width - The native width of the game.
  16662. * @param {number} height - The native height of the game.
  16663. */
  16664. Phaser.ScaleManager = function (game, width, height) {
  16665. /**
  16666. * @property {Phaser.Game} game - A reference to the currently running game.
  16667. */
  16668. this.game = game;
  16669. /**
  16670. * @property {number} width - Width of the stage after calculation.
  16671. */
  16672. this.width = width;
  16673. /**
  16674. * @property {number} height - Height of the stage after calculation.
  16675. */
  16676. this.height = height;
  16677. /**
  16678. * @property {number} minWidth - Minimum width the canvas should be scaled to (in pixels).
  16679. */
  16680. this.minWidth = null;
  16681. /**
  16682. * @property {number} maxWidth - Maximum width the canvas should be scaled to (in pixels). If null it will scale to whatever width the browser can handle.
  16683. */
  16684. this.maxWidth = null;
  16685. /**
  16686. * @property {number} minHeight - Minimum height the canvas should be scaled to (in pixels).
  16687. */
  16688. this.minHeight = null;
  16689. /**
  16690. * @property {number} maxHeight - Maximum height the canvas should be scaled to (in pixels). If null it will scale to whatever height the browser can handle.
  16691. */
  16692. this.maxHeight = null;
  16693. /**
  16694. * @property {boolean} forceLandscape - If the game should be forced to use Landscape mode, this is set to true by Game.Stage
  16695. * @default
  16696. */
  16697. this.forceLandscape = false;
  16698. /**
  16699. * @property {boolean} forcePortrait - If the game should be forced to use Portrait mode, this is set to true by Game.Stage
  16700. * @default
  16701. */
  16702. this.forcePortrait = false;
  16703. /**
  16704. * @property {boolean} incorrectOrientation - If the game should be forced to use a specific orientation and the device currently isn't in that orientation this is set to true.
  16705. * @default
  16706. */
  16707. this.incorrectOrientation = false;
  16708. /**
  16709. * @property {boolean} pageAlignHorizontally - If you wish to align your game in the middle of the page then you can set this value to true.
  16710. * It will place a re-calculated margin-left pixel value onto the canvas element which is updated on orientation/resizing.
  16711. * It doesn't care about any other DOM element that may be on the page, it literally just sets the margin.
  16712. * @default
  16713. */
  16714. this.pageAlignHorizontally = false;
  16715. /**
  16716. * @property {boolean} pageAlignVertically - If you wish to align your game in the middle of the page then you can set this value to true.
  16717. * It will place a re-calculated margin-left pixel value onto the canvas element which is updated on orientation/resizing.
  16718. * It doesn't care about any other DOM element that may be on the page, it literally just sets the margin.
  16719. * @default
  16720. */
  16721. this.pageAlignVertically = false;
  16722. /**
  16723. * @property {number} maxIterations - The maximum number of times it will try to resize the canvas to fill the browser.
  16724. * @default
  16725. */
  16726. this.maxIterations = 5;
  16727. /**
  16728. * @property {PIXI.Sprite} orientationSprite - The Sprite that is optionally displayed if the browser enters an unsupported orientation.
  16729. */
  16730. this.orientationSprite = null;
  16731. /**
  16732. * @property {Phaser.Signal} enterLandscape - The event that is dispatched when the browser enters landscape orientation.
  16733. */
  16734. this.enterLandscape = new Phaser.Signal();
  16735. /**
  16736. * @property {Phaser.Signal} enterPortrait - The event that is dispatched when the browser enters horizontal orientation.
  16737. */
  16738. this.enterPortrait = new Phaser.Signal();
  16739. /**
  16740. * @property {Phaser.Signal} enterIncorrectOrientation - The event that is dispatched when the browser enters an incorrect orientation, as defined by forceOrientation.
  16741. */
  16742. this.enterIncorrectOrientation = new Phaser.Signal();
  16743. /**
  16744. * @property {Phaser.Signal} leaveIncorrectOrientation - The event that is dispatched when the browser leaves an incorrect orientation, as defined by forceOrientation.
  16745. */
  16746. this.leaveIncorrectOrientation = new Phaser.Signal();
  16747. /**
  16748. * @property {Phaser.Signal} hasResized - The event that is dispatched when the game scale changes.
  16749. */
  16750. this.hasResized = new Phaser.Signal();
  16751. /**
  16752. * This is the DOM element that will have the Full Screen mode called on it. It defaults to the game canvas, but can be retargetted to any valid DOM element.
  16753. * If you adjust this property it's up to you to see it has the correct CSS applied, and that you have contained the game canvas correctly.
  16754. * Note that if you use a scale property of EXACT_FIT then fullScreenTarget will have its width and height style set to 100%.
  16755. * @property {any} fullScreenTarget
  16756. */
  16757. this.fullScreenTarget = this.game.canvas;
  16758. /**
  16759. * @property {Phaser.Signal} enterFullScreen - The event that is dispatched when the browser enters full screen mode (if it supports the FullScreen API).
  16760. */
  16761. this.enterFullScreen = new Phaser.Signal();
  16762. /**
  16763. * @property {Phaser.Signal} leaveFullScreen - The event that is dispatched when the browser leaves full screen mode (if it supports the FullScreen API).
  16764. */
  16765. this.leaveFullScreen = new Phaser.Signal();
  16766. /**
  16767. * @property {number} orientation - The orientation value of the game (as defined by window.orientation if set). 90 = landscape. 0 = portrait.
  16768. */
  16769. this.orientation = 0;
  16770. if (window['orientation'])
  16771. {
  16772. this.orientation = window['orientation'];
  16773. }
  16774. else
  16775. {
  16776. if (window.outerWidth > window.outerHeight)
  16777. {
  16778. this.orientation = 90;
  16779. }
  16780. }
  16781. /**
  16782. * @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions.
  16783. * @readonly
  16784. */
  16785. this.scaleFactor = new Phaser.Point(1, 1);
  16786. /**
  16787. * @property {Phaser.Point} scaleFactorInversed - The inversed scale factor. The displayed dimensions divided by the game dimensions.
  16788. * @readonly
  16789. */
  16790. this.scaleFactorInversed = new Phaser.Point(1, 1);
  16791. /**
  16792. * @property {Phaser.Point} margin - If the game canvas is set to align by adjusting the margin, the margin calculation values are stored in this Point.
  16793. * @readonly
  16794. */
  16795. this.margin = new Phaser.Point(0, 0);
  16796. /**
  16797. * @property {Phaser.Rectangle} bounds - 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.
  16798. * @readonly
  16799. */
  16800. this.bounds = new Phaser.Rectangle(0, 0, width, height);
  16801. /**
  16802. * @property {number} aspectRatio - The aspect ratio of the scaled game.
  16803. * @readonly
  16804. */
  16805. this.aspectRatio = 0;
  16806. /**
  16807. * @property {number} sourceAspectRatio - The aspect ratio (width / height) of the original game dimensions.
  16808. * @readonly
  16809. */
  16810. this.sourceAspectRatio = width / height;
  16811. /**
  16812. * @property {any} event- The native browser events from full screen API changes.
  16813. */
  16814. this.event = null;
  16815. /**
  16816. * @property {number} scaleMode - The current scaleMode.
  16817. */
  16818. this.scaleMode = Phaser.ScaleManager.NO_SCALE;
  16819. /*
  16820. * @property {number} fullScreenScaleMode - Scale mode to be used in fullScreen
  16821. */
  16822. this.fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE;
  16823. /**
  16824. * @property {number} _startHeight - Internal cache var. Stage height when starting the game.
  16825. * @private
  16826. */
  16827. this._startHeight = 0;
  16828. /**
  16829. * @property {number} _width - Cached stage width for full screen mode.
  16830. * @private
  16831. */
  16832. this._width = 0;
  16833. /**
  16834. * @property {number} _height - Cached stage height for full screen mode.
  16835. * @private
  16836. */
  16837. this._height = 0;
  16838. /**
  16839. * @property {number} _check - Cached size interval var.
  16840. * @private
  16841. */
  16842. this._check = null;
  16843. var _this = this;
  16844. window.addEventListener('orientationchange', function (event) {
  16845. return _this.checkOrientation(event);
  16846. }, false);
  16847. window.addEventListener('resize', function (event) {
  16848. return _this.checkResize(event);
  16849. }, false);
  16850. if (!this.game.device.cocoonJS)
  16851. {
  16852. document.addEventListener('webkitfullscreenchange', function (event) {
  16853. return _this.fullScreenChange(event);
  16854. }, false);
  16855. document.addEventListener('mozfullscreenchange', function (event) {
  16856. return _this.fullScreenChange(event);
  16857. }, false);
  16858. document.addEventListener('fullscreenchange', function (event) {
  16859. return _this.fullScreenChange(event);
  16860. }, false);
  16861. }
  16862. };
  16863. /**
  16864. * @constant
  16865. * @type {number}
  16866. */
  16867. Phaser.ScaleManager.EXACT_FIT = 0;
  16868. /**
  16869. * @constant
  16870. * @type {number}
  16871. */
  16872. Phaser.ScaleManager.NO_SCALE = 1;
  16873. /**
  16874. * @constant
  16875. * @type {number}
  16876. */
  16877. Phaser.ScaleManager.SHOW_ALL = 2;
  16878. Phaser.ScaleManager.prototype = {
  16879. /**
  16880. * Tries to enter the browser into full screen mode.
  16881. * Please note that this needs to be supported by the web browser and isn't the same thing as setting your game to fill the browser.
  16882. * @method Phaser.ScaleManager#startFullScreen
  16883. * @param {boolean} antialias - You can toggle the anti-alias feature of the canvas before jumping in to full screen (false = retain pixel art, true = smooth art)
  16884. */
  16885. startFullScreen: function (antialias) {
  16886. if (this.isFullScreen || !this.game.device.fullscreen)
  16887. {
  16888. return;
  16889. }
  16890. if (typeof antialias !== 'undefined' && this.game.renderType === Phaser.CANVAS)
  16891. {
  16892. this.game.stage.smoothed = antialias;
  16893. }
  16894. this._width = this.width;
  16895. this._height = this.height;
  16896. if (this.game.device.fullscreenKeyboard)
  16897. {
  16898. this.fullScreenTarget[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT);
  16899. }
  16900. else
  16901. {
  16902. this.fullScreenTarget[this.game.device.requestFullscreen]();
  16903. }
  16904. },
  16905. /**
  16906. * Stops full screen mode if the browser is in it.
  16907. * @method Phaser.ScaleManager#stopFullScreen
  16908. */
  16909. stopFullScreen: function () {
  16910. document[this.game.device.cancelFullscreen]();
  16911. },
  16912. /**
  16913. * Called automatically when the browser enters of leaves full screen mode.
  16914. * @method Phaser.ScaleManager#fullScreenChange
  16915. * @param {Event} event - The fullscreenchange event
  16916. * @protected
  16917. */
  16918. fullScreenChange: function (event) {
  16919. this.event = event;
  16920. if (this.isFullScreen)
  16921. {
  16922. if (this.fullScreenScaleMode === Phaser.ScaleManager.EXACT_FIT)
  16923. {
  16924. this.fullScreenTarget.style['width'] = '100%';
  16925. this.fullScreenTarget.style['height'] = '100%';
  16926. this.width = window.outerWidth;
  16927. this.height = window.outerHeight;
  16928. this.game.input.scale.setTo(this.game.width / this.width, this.game.height / this.height);
  16929. this.aspectRatio = this.width / this.height;
  16930. this.scaleFactor.x = this.game.width / this.width;
  16931. this.scaleFactor.y = this.game.height / this.height;
  16932. this.checkResize();
  16933. }
  16934. else if (this.fullScreenScaleMode === Phaser.ScaleManager.SHOW_ALL)
  16935. {
  16936. this.setShowAll();
  16937. this.refresh();
  16938. }
  16939. this.enterFullScreen.dispatch(this.width, this.height);
  16940. }
  16941. else
  16942. {
  16943. this.fullScreenTarget.style['width'] = this.game.width + 'px';
  16944. this.fullScreenTarget.style['height'] = this.game.height + 'px';
  16945. this.width = this._width;
  16946. this.height = this._height;
  16947. this.game.input.scale.setTo(this.game.width / this.width, this.game.height / this.height);
  16948. this.aspectRatio = this.width / this.height;
  16949. this.scaleFactor.x = this.game.width / this.width;
  16950. this.scaleFactor.y = this.game.height / this.height;
  16951. this.leaveFullScreen.dispatch(this.width, this.height);
  16952. }
  16953. },
  16954. /**
  16955. * If you need your game to run in only one orientation you can force that to happen.
  16956. * The optional orientationImage is displayed when the game is in the incorrect orientation.
  16957. * @method Phaser.ScaleManager#forceOrientation
  16958. * @param {boolean} forceLandscape - true if the game should run in landscape mode only.
  16959. * @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only.
  16960. * @param {string} [orientationImage=''] - The string of an image in the Phaser.Cache to display when this game is in the incorrect orientation.
  16961. */
  16962. forceOrientation: function (forceLandscape, forcePortrait, orientationImage) {
  16963. if (typeof forcePortrait === 'undefined') { forcePortrait = false; }
  16964. this.forceLandscape = forceLandscape;
  16965. this.forcePortrait = forcePortrait;
  16966. if (typeof orientationImage !== 'undefined')
  16967. {
  16968. if (orientationImage === null || this.game.cache.checkImageKey(orientationImage) === false)
  16969. {
  16970. orientationImage = '__default';
  16971. }
  16972. this.orientationSprite = new Phaser.Image(this.game, this.game.width / 2, this.game.height / 2, orientationImage);
  16973. this.orientationSprite.anchor.set(0.5);
  16974. this.checkOrientationState();
  16975. if (this.incorrectOrientation)
  16976. {
  16977. this.orientationSprite.visible = true;
  16978. this.game.world.visible = false;
  16979. }
  16980. else
  16981. {
  16982. this.orientationSprite.visible = false;
  16983. this.game.world.visible = true;
  16984. }
  16985. this.game.stage.addChild(this.orientationSprite);
  16986. }
  16987. },
  16988. /**
  16989. * Checks if the browser is in the correct orientation for your game (if forceLandscape or forcePortrait have been set)
  16990. * @method Phaser.ScaleManager#checkOrientationState
  16991. */
  16992. checkOrientationState: function () {
  16993. // They are in the wrong orientation
  16994. if (this.incorrectOrientation)
  16995. {
  16996. if ((this.forceLandscape && window.innerWidth > window.innerHeight) || (this.forcePortrait && window.innerHeight > window.innerWidth))
  16997. {
  16998. // Back to normal
  16999. this.incorrectOrientation = false;
  17000. this.leaveIncorrectOrientation.dispatch();
  17001. if (this.orientationSprite)
  17002. {
  17003. this.orientationSprite.visible = false;
  17004. this.game.world.visible = true;
  17005. }
  17006. if (this.scaleMode !== Phaser.ScaleManager.NO_SCALE)
  17007. {
  17008. this.refresh();
  17009. }
  17010. }
  17011. }
  17012. else
  17013. {
  17014. if ((this.forceLandscape && window.innerWidth < window.innerHeight) || (this.forcePortrait && window.innerHeight < window.innerWidth))
  17015. {
  17016. // Show orientation screen
  17017. this.incorrectOrientation = true;
  17018. this.enterIncorrectOrientation.dispatch();
  17019. if (this.orientationSprite && this.orientationSprite.visible === false)
  17020. {
  17021. this.orientationSprite.visible = true;
  17022. this.game.world.visible = false;
  17023. }
  17024. if (this.scaleMode !== Phaser.ScaleManager.NO_SCALE)
  17025. {
  17026. this.refresh();
  17027. }
  17028. }
  17029. }
  17030. },
  17031. /**
  17032. * Handle window.orientationchange events
  17033. * @method Phaser.ScaleManager#checkOrientation
  17034. * @param {Event} event - The orientationchange event data.
  17035. */
  17036. checkOrientation: function (event) {
  17037. this.event = event;
  17038. this.orientation = window['orientation'];
  17039. if (this.isLandscape)
  17040. {
  17041. this.enterLandscape.dispatch(this.orientation, true, false);
  17042. }
  17043. else
  17044. {
  17045. this.enterPortrait.dispatch(this.orientation, false, true);
  17046. }
  17047. if (this.scaleMode !== Phaser.ScaleManager.NO_SCALE)
  17048. {
  17049. this.refresh();
  17050. }
  17051. },
  17052. /**
  17053. * Handle window.resize events
  17054. * @method Phaser.ScaleManager#checkResize
  17055. * @param {Event} event - The resize event data.
  17056. */
  17057. checkResize: function (event) {
  17058. this.event = event;
  17059. if (window.outerWidth > window.outerHeight)
  17060. {
  17061. this.orientation = 90;
  17062. }
  17063. else
  17064. {
  17065. this.orientation = 0;
  17066. }
  17067. if (this.isLandscape)
  17068. {
  17069. this.enterLandscape.dispatch(this.orientation, true, false);
  17070. }
  17071. else
  17072. {
  17073. this.enterPortrait.dispatch(this.orientation, false, true);
  17074. }
  17075. if (this.scaleMode !== Phaser.ScaleManager.NO_SCALE)
  17076. {
  17077. this.refresh();
  17078. }
  17079. this.checkOrientationState();
  17080. },
  17081. /**
  17082. * Re-calculate scale mode and update screen size.
  17083. * @method Phaser.ScaleManager#refresh
  17084. */
  17085. refresh: function () {
  17086. // We can't do anything about the status bars in iPads, web apps or desktops
  17087. if (!this.game.device.iPad && !this.game.device.webApp && !this.game.device.desktop)
  17088. {
  17089. // TODO - Test this
  17090. // this._startHeight = window.innerHeight;
  17091. if (this.game.device.android && !this.game.device.chrome)
  17092. {
  17093. window.scrollTo(0, 1);
  17094. }
  17095. else
  17096. {
  17097. window.scrollTo(0, 0);
  17098. }
  17099. }
  17100. if (this._check === null && this.maxIterations > 0)
  17101. {
  17102. this._iterations = this.maxIterations;
  17103. var _this = this;
  17104. this._check = window.setInterval(function () {
  17105. return _this.setScreenSize();
  17106. }, 10);
  17107. this.setScreenSize();
  17108. }
  17109. },
  17110. /**
  17111. * Set screen size automatically based on the scaleMode.
  17112. * @param {boolean} force - If force is true it will try to resize the game regardless of the document dimensions.
  17113. */
  17114. setScreenSize: function (force) {
  17115. if (typeof force === 'undefined')
  17116. {
  17117. force = false;
  17118. }
  17119. if (!this.game.device.iPad && !this.game.device.webApp && !this.game.device.desktop)
  17120. {
  17121. if (this.game.device.android && !this.game.device.chrome)
  17122. {
  17123. window.scrollTo(0, 1);
  17124. }
  17125. else
  17126. {
  17127. window.scrollTo(0, 0);
  17128. }
  17129. }
  17130. this._iterations--;
  17131. if (force || window.innerHeight > this._startHeight || this._iterations < 0)
  17132. {
  17133. // Set minimum height of content to new window height
  17134. document.documentElement['style'].minHeight = window.innerHeight + 'px';
  17135. if (this.incorrectOrientation)
  17136. {
  17137. this.setMaximum();
  17138. }
  17139. else if (!this.isFullScreen)
  17140. {
  17141. if (this.scaleMode === Phaser.ScaleManager.EXACT_FIT)
  17142. {
  17143. this.setExactFit();
  17144. }
  17145. else if (this.scaleMode === Phaser.ScaleManager.SHOW_ALL)
  17146. {
  17147. this.setShowAll();
  17148. }
  17149. }
  17150. else
  17151. {
  17152. if (this.fullScreenScaleMode === Phaser.ScaleManager.EXACT_FIT)
  17153. {
  17154. this.setExactFit();
  17155. }
  17156. else if (this.fullScreenScaleMode === Phaser.ScaleManager.SHOW_ALL)
  17157. {
  17158. this.setShowAll();
  17159. }
  17160. }
  17161. this.setSize();
  17162. clearInterval(this._check);
  17163. this._check = null;
  17164. }
  17165. },
  17166. /**
  17167. * Sets the canvas style width and height values based on minWidth/Height and maxWidth/Height.
  17168. * @method Phaser.ScaleManager#setSize
  17169. */
  17170. setSize: function () {
  17171. if (!this.incorrectOrientation)
  17172. {
  17173. if (this.maxWidth && this.width > this.maxWidth)
  17174. {
  17175. this.width = this.maxWidth;
  17176. }
  17177. if (this.maxHeight && this.height > this.maxHeight)
  17178. {
  17179. this.height = this.maxHeight;
  17180. }
  17181. if (this.minWidth && this.width < this.minWidth)
  17182. {
  17183. this.width = this.minWidth;
  17184. }
  17185. if (this.minHeight && this.height < this.minHeight)
  17186. {
  17187. this.height = this.minHeight;
  17188. }
  17189. }
  17190. this.game.canvas.style.width = this.width + 'px';
  17191. this.game.canvas.style.height = this.height + 'px';
  17192. this.game.input.scale.setTo(this.game.width / this.width, this.game.height / this.height);
  17193. if (this.pageAlignHorizontally)
  17194. {
  17195. if (this.width < window.innerWidth && !this.incorrectOrientation)
  17196. {
  17197. this.margin.x = Math.round((window.innerWidth - this.width) / 2);
  17198. this.game.canvas.style.marginLeft = this.margin.x + 'px';
  17199. }
  17200. else
  17201. {
  17202. this.margin.x = 0;
  17203. this.game.canvas.style.marginLeft = '0px';
  17204. }
  17205. }
  17206. if (this.pageAlignVertically)
  17207. {
  17208. if (this.height < window.innerHeight && !this.incorrectOrientation)
  17209. {
  17210. this.margin.y = Math.round((window.innerHeight - this.height) / 2);
  17211. this.game.canvas.style.marginTop = this.margin.y + 'px';
  17212. }
  17213. else
  17214. {
  17215. this.margin.y = 0;
  17216. this.game.canvas.style.marginTop = '0px';
  17217. }
  17218. }
  17219. Phaser.Canvas.getOffset(this.game.canvas, this.game.stage.offset);
  17220. this.bounds.setTo(this.game.stage.offset.x, this.game.stage.offset.y, this.width, this.height);
  17221. this.aspectRatio = this.width / this.height;
  17222. this.scaleFactor.x = this.game.width / this.width;
  17223. this.scaleFactor.y = this.game.height / this.height;
  17224. this.scaleFactorInversed.x = this.width / this.game.width;
  17225. this.scaleFactorInversed.y = this.height / this.game.height;
  17226. this.hasResized.dispatch(this.width, this.height);
  17227. this.checkOrientationState();
  17228. },
  17229. /**
  17230. * Sets this.width equal to window.innerWidth and this.height equal to window.innerHeight
  17231. * @method Phaser.ScaleManager#setMaximum
  17232. */
  17233. setMaximum: function () {
  17234. this.width = window.innerWidth;
  17235. this.height = window.innerHeight;
  17236. },
  17237. /**
  17238. * Calculates the multiplier needed to scale the game proportionally.
  17239. * @method Phaser.ScaleManager#setShowAll
  17240. */
  17241. setShowAll: function () {
  17242. var multiplier = Math.min((window.innerHeight / this.game.height), (window.innerWidth / this.game.width));
  17243. this.width = Math.round(this.game.width * multiplier);
  17244. this.height = Math.round(this.game.height * multiplier);
  17245. },
  17246. /**
  17247. * Sets the width and height values of the canvas, no larger than the maxWidth/Height.
  17248. * @method Phaser.ScaleManager#setExactFit
  17249. */
  17250. setExactFit: function () {
  17251. var availableWidth = window.innerWidth;
  17252. var availableHeight = window.innerHeight;
  17253. if (this.maxWidth && availableWidth > this.maxWidth)
  17254. {
  17255. this.width = this.maxWidth;
  17256. }
  17257. else
  17258. {
  17259. this.width = availableWidth;
  17260. }
  17261. if (this.maxHeight && availableHeight > this.maxHeight)
  17262. {
  17263. this.height = this.maxHeight;
  17264. }
  17265. else
  17266. {
  17267. this.height = availableHeight;
  17268. }
  17269. }
  17270. };
  17271. Phaser.ScaleManager.prototype.constructor = Phaser.ScaleManager;
  17272. /**
  17273. * @name Phaser.ScaleManager#isFullScreen
  17274. * @property {boolean} isFullScreen - Returns true if the browser is in full screen mode, otherwise false.
  17275. * @readonly
  17276. */
  17277. Object.defineProperty(Phaser.ScaleManager.prototype, "isFullScreen", {
  17278. get: function () {
  17279. return (document['fullscreenElement'] || document['mozFullScreenElement'] || document['webkitFullscreenElement']);
  17280. }
  17281. });
  17282. /**
  17283. * @name Phaser.ScaleManager#isPortrait
  17284. * @property {boolean} isPortrait - Returns true if the browser dimensions match a portrait display.
  17285. * @readonly
  17286. */
  17287. Object.defineProperty(Phaser.ScaleManager.prototype, "isPortrait", {
  17288. get: function () {
  17289. return (this.orientation === 0 || this.orientation === 180);
  17290. }
  17291. });
  17292. /**
  17293. * @name Phaser.ScaleManager#isLandscape
  17294. * @property {boolean} isLandscape - Returns true if the browser dimensions match a landscape display.
  17295. * @readonly
  17296. */
  17297. Object.defineProperty(Phaser.ScaleManager.prototype, "isLandscape", {
  17298. get: function () {
  17299. return (this.orientation === 90 || this.orientation === -90);
  17300. }
  17301. });
  17302. /**
  17303. * @author Richard Davey <rich@photonstorm.com>
  17304. * @copyright 2014 Photon Storm Ltd.
  17305. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  17306. */
  17307. /**
  17308. * Game constructor
  17309. *
  17310. * Instantiate a new <code>Phaser.Game</code> object.
  17311. * @class Phaser.Game
  17312. * @classdesc This is where the magic happens. The Game object is the heart of your game,
  17313. * providing quick access to common functions and handling the boot process.
  17314. * "Hell, there are no rules here - we're trying to accomplish something."
  17315. * Thomas A. Edison
  17316. * @constructor
  17317. * @param {number} [width=800] - The width of your game in game pixels.
  17318. * @param {number} [height=600] - The height of your game in game pixels.
  17319. * @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).
  17320. * @param {string|HTMLElement} [parent=''] - The DOM element into which this games canvas will be injected. Either a DOM ID (string) or the element itself.
  17321. * @param {object} [state=null] - The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null.
  17322. * @param {boolean} [transparent=false] - Use a transparent canvas background or not.
  17323. * @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.
  17324. * @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation.
  17325. */
  17326. Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias, physicsConfig) {
  17327. /**
  17328. * @property {number} id - Phaser Game ID (for when Pixi supports multiple instances).
  17329. */
  17330. this.id = Phaser.GAMES.push(this) - 1;
  17331. /**
  17332. * @property {object} config - The Phaser.Game configuration object.
  17333. */
  17334. this.config = null;
  17335. /**
  17336. * @property {object} physicsConfig - The Phaser.Physics.World configuration object.
  17337. */
  17338. this.physicsConfig = physicsConfig;
  17339. /**
  17340. * @property {string|HTMLElement} parent - The Games DOM parent.
  17341. * @default
  17342. */
  17343. this.parent = '';
  17344. /**
  17345. * @property {number} width - The Game width (in pixels).
  17346. * @default
  17347. */
  17348. this.width = 800;
  17349. /**
  17350. * @property {number} height - The Game height (in pixels).
  17351. * @default
  17352. */
  17353. this.height = 600;
  17354. /**
  17355. * @property {boolean} transparent - Use a transparent canvas background or not.
  17356. * @default
  17357. */
  17358. this.transparent = false;
  17359. /**
  17360. * @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.
  17361. * @default
  17362. */
  17363. this.antialias = true;
  17364. /**
  17365. * @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering.
  17366. * @default
  17367. */
  17368. this.preserveDrawingBuffer = false;
  17369. /**
  17370. * @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer.
  17371. */
  17372. this.renderer = null;
  17373. /**
  17374. * @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS or Phaser.WEBGL.
  17375. */
  17376. this.renderType = Phaser.AUTO;
  17377. /**
  17378. * @property {Phaser.StateManager} state - The StateManager.
  17379. */
  17380. this.state = null;
  17381. /**
  17382. * @property {boolean} isBooted - Whether the game engine is booted, aka available.
  17383. * @default
  17384. */
  17385. this.isBooted = false;
  17386. /**
  17387. * @property {boolean} id -Is game running or paused?
  17388. * @default
  17389. */
  17390. this.isRunning = false;
  17391. /**
  17392. * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout
  17393. */
  17394. this.raf = null;
  17395. /**
  17396. * @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory.
  17397. */
  17398. this.add = null;
  17399. /**
  17400. * @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator.
  17401. */
  17402. this.make = null;
  17403. /**
  17404. * @property {Phaser.Cache} cache - Reference to the assets cache.
  17405. */
  17406. this.cache = null;
  17407. /**
  17408. * @property {Phaser.Input} input - Reference to the input manager
  17409. */
  17410. this.input = null;
  17411. /**
  17412. * @property {Phaser.Loader} load - Reference to the assets loader.
  17413. */
  17414. this.load = null;
  17415. /**
  17416. * @property {Phaser.Math} math - Reference to the math helper.
  17417. */
  17418. this.math = null;
  17419. /**
  17420. * @property {Phaser.Net} net - Reference to the network class.
  17421. */
  17422. this.net = null;
  17423. /**
  17424. * @property {Phaser.ScaleManager} scale - The game scale manager.
  17425. */
  17426. this.scale = null;
  17427. /**
  17428. * @property {Phaser.SoundManager} sound - Reference to the sound manager.
  17429. */
  17430. this.sound = null;
  17431. /**
  17432. * @property {Phaser.Stage} stage - Reference to the stage.
  17433. */
  17434. this.stage = null;
  17435. /**
  17436. * @property {Phaser.Time} time - Reference to the core game clock.
  17437. */
  17438. this.time = null;
  17439. /**
  17440. * @property {Phaser.TweenManager} tweens - Reference to the tween manager.
  17441. */
  17442. this.tweens = null;
  17443. /**
  17444. * @property {Phaser.World} world - Reference to the world.
  17445. */
  17446. this.world = null;
  17447. /**
  17448. * @property {Phaser.Physics} physics - Reference to the physics manager.
  17449. */
  17450. this.physics = null;
  17451. /**
  17452. * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper.
  17453. */
  17454. this.rnd = null;
  17455. /**
  17456. * @property {Phaser.Device} device - Contains device information and capabilities.
  17457. */
  17458. this.device = null;
  17459. /**
  17460. * @property {Phaser.Camera} camera - A handy reference to world.camera.
  17461. */
  17462. this.camera = null;
  17463. /**
  17464. * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to.
  17465. */
  17466. this.canvas = null;
  17467. /**
  17468. * @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL)
  17469. */
  17470. this.context = null;
  17471. /**
  17472. * @property {Phaser.Utils.Debug} debug - A set of useful debug utilitie.
  17473. */
  17474. this.debug = null;
  17475. /**
  17476. * @property {Phaser.Particles} particles - The Particle Manager.
  17477. */
  17478. this.particles = null;
  17479. /**
  17480. * @property {boolean} stepping - Enable core loop stepping with Game.enableStep().
  17481. * @default
  17482. * @readonly
  17483. */
  17484. this.stepping = false;
  17485. /**
  17486. * @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects.
  17487. * @default
  17488. * @readonly
  17489. */
  17490. this.pendingStep = false;
  17491. /**
  17492. * @property {number} stepCount - When stepping is enabled this contains the current step cycle.
  17493. * @default
  17494. * @readonly
  17495. */
  17496. this.stepCount = 0;
  17497. /**
  17498. * @property {Phaser.Signal} onPause - This event is fired when the game pauses.
  17499. */
  17500. this.onPause = null;
  17501. /**
  17502. * @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state.
  17503. */
  17504. this.onResume = null;
  17505. /**
  17506. * @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide).
  17507. */
  17508. this.onBlur = null;
  17509. /**
  17510. * @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show).
  17511. */
  17512. this.onFocus = null;
  17513. /**
  17514. * @property {boolean} _paused - Is game paused?
  17515. * @private
  17516. */
  17517. this._paused = false;
  17518. /**
  17519. * @property {boolean} _codePaused - Was the game paused via code or a visibility change?
  17520. * @private
  17521. */
  17522. this._codePaused = false;
  17523. // Parse the configuration object (if any)
  17524. if (arguments.length === 1 && typeof arguments[0] === 'object')
  17525. {
  17526. this.parseConfig(arguments[0]);
  17527. }
  17528. else
  17529. {
  17530. this.config = { enableDebug: true };
  17531. if (typeof width !== 'undefined')
  17532. {
  17533. this.width = width;
  17534. }
  17535. if (typeof height !== 'undefined')
  17536. {
  17537. this.height = height;
  17538. }
  17539. if (typeof renderer !== 'undefined')
  17540. {
  17541. this.renderer = renderer;
  17542. this.renderType = renderer;
  17543. }
  17544. if (typeof parent !== 'undefined')
  17545. {
  17546. this.parent = parent;
  17547. }
  17548. if (typeof transparent !== 'undefined')
  17549. {
  17550. this.transparent = transparent;
  17551. }
  17552. if (typeof antialias !== 'undefined')
  17553. {
  17554. this.antialias = antialias;
  17555. }
  17556. this.rnd = new Phaser.RandomDataGenerator([(Date.now() * Math.random()).toString()]);
  17557. this.state = new Phaser.StateManager(this, state);
  17558. }
  17559. var _this = this;
  17560. this._onBoot = function () {
  17561. return _this.boot();
  17562. };
  17563. if (document.readyState === 'complete' || document.readyState === 'interactive')
  17564. {
  17565. window.setTimeout(this._onBoot, 0);
  17566. }
  17567. else
  17568. {
  17569. document.addEventListener('DOMContentLoaded', this._onBoot, false);
  17570. window.addEventListener('load', this._onBoot, false);
  17571. }
  17572. return this;
  17573. };
  17574. Phaser.Game.prototype = {
  17575. /**
  17576. * Parses a Game configuration object.
  17577. *
  17578. * @method Phaser.Game#parseConfig
  17579. * @protected
  17580. */
  17581. parseConfig: function (config) {
  17582. this.config = config;
  17583. if (config['width'])
  17584. {
  17585. this.width = Phaser.Utils.parseDimension(config['width'], 0);
  17586. }
  17587. if (config['height'])
  17588. {
  17589. this.height = Phaser.Utils.parseDimension(config['height'], 1);
  17590. }
  17591. if (config['renderer'])
  17592. {
  17593. this.renderer = config['renderer'];
  17594. this.renderType = config['renderer'];
  17595. }
  17596. if (config['parent'])
  17597. {
  17598. this.parent = config['parent'];
  17599. }
  17600. if (config['transparent'])
  17601. {
  17602. this.transparent = config['transparent'];
  17603. }
  17604. if (config['antialias'])
  17605. {
  17606. this.antialias = config['antialias'];
  17607. }
  17608. if (config['preserveDrawingBuffer'])
  17609. {
  17610. this.preserveDrawingBuffer = config['preserveDrawingBuffer'];
  17611. }
  17612. if (config['physicsConfig'])
  17613. {
  17614. this.physicsConfig = config['physicsConfig'];
  17615. }
  17616. var seed = [(Date.now() * Math.random()).toString()];
  17617. if (config['seed'])
  17618. {
  17619. seed = config['seed'];
  17620. }
  17621. this.rnd = new Phaser.RandomDataGenerator(seed);
  17622. var state = null;
  17623. if (config['state'])
  17624. {
  17625. state = config['state'];
  17626. }
  17627. this.state = new Phaser.StateManager(this, state);
  17628. },
  17629. /**
  17630. * Initialize engine sub modules and start the game.
  17631. *
  17632. * @method Phaser.Game#boot
  17633. * @protected
  17634. */
  17635. boot: function () {
  17636. if (this.isBooted)
  17637. {
  17638. return;
  17639. }
  17640. if (!document.body)
  17641. {
  17642. window.setTimeout(this._onBoot, 20);
  17643. }
  17644. else
  17645. {
  17646. document.removeEventListener('DOMContentLoaded', this._onBoot);
  17647. window.removeEventListener('load', this._onBoot);
  17648. this.onPause = new Phaser.Signal();
  17649. this.onResume = new Phaser.Signal();
  17650. this.onBlur = new Phaser.Signal();
  17651. this.onFocus = new Phaser.Signal();
  17652. this.isBooted = true;
  17653. this.device = new Phaser.Device(this);
  17654. this.math = Phaser.Math;
  17655. this.stage = new Phaser.Stage(this, this.width, this.height);
  17656. this.setUpRenderer();
  17657. this.scale = new Phaser.ScaleManager(this, this.width, this.height);
  17658. this.device.checkFullScreenSupport();
  17659. this.world = new Phaser.World(this);
  17660. this.add = new Phaser.GameObjectFactory(this);
  17661. this.make = new Phaser.GameObjectCreator(this);
  17662. this.cache = new Phaser.Cache(this);
  17663. this.load = new Phaser.Loader(this);
  17664. this.time = new Phaser.Time(this);
  17665. this.tweens = new Phaser.TweenManager(this);
  17666. this.input = new Phaser.Input(this);
  17667. this.sound = new Phaser.SoundManager(this);
  17668. this.physics = new Phaser.Physics(this, this.physicsConfig);
  17669. this.particles = new Phaser.Particles(this);
  17670. this.plugins = new Phaser.PluginManager(this);
  17671. this.net = new Phaser.Net(this);
  17672. this.time.boot();
  17673. this.stage.boot();
  17674. this.world.boot();
  17675. this.input.boot();
  17676. this.sound.boot();
  17677. this.state.boot();
  17678. if (this.config['enableDebug'])
  17679. {
  17680. this.debug = new Phaser.Utils.Debug(this);
  17681. this.debug.boot();
  17682. }
  17683. this.showDebugHeader();
  17684. this.isRunning = true;
  17685. if (this.config && this.config['forceSetTimeOut'])
  17686. {
  17687. this.raf = new Phaser.RequestAnimationFrame(this, this.config['forceSetTimeOut']);
  17688. }
  17689. else
  17690. {
  17691. this.raf = new Phaser.RequestAnimationFrame(this, false);
  17692. }
  17693. this.raf.start();
  17694. }
  17695. },
  17696. /**
  17697. * Displays a Phaser version debug header in the console.
  17698. *
  17699. * @method Phaser.Game#showDebugHeader
  17700. * @protected
  17701. */
  17702. showDebugHeader: function () {
  17703. var v = Phaser.VERSION;
  17704. var r = 'Canvas';
  17705. var a = 'HTML Audio';
  17706. var c = 1;
  17707. if (this.renderType === Phaser.WEBGL)
  17708. {
  17709. r = 'WebGL';
  17710. c++;
  17711. }
  17712. else if (this.renderType == Phaser.HEADLESS)
  17713. {
  17714. r = 'Headless';
  17715. }
  17716. if (this.device.webAudio)
  17717. {
  17718. a = 'WebAudio';
  17719. c++;
  17720. }
  17721. if (this.device.chrome)
  17722. {
  17723. var args = [
  17724. '%c %c %c Phaser v' + v + ' | Pixi.js ' + PIXI.VERSION + ' | ' + r + ' | ' + a + ' %c %c ' + ' http://phaser.io %c %c \u2665%c\u2665%c\u2665 ',
  17725. 'background: #0cf300',
  17726. 'background: #00bc17',
  17727. 'color: #ffffff; background: #00711f;',
  17728. 'background: #00bc17',
  17729. 'background: #0cf300',
  17730. 'background: #00bc17'
  17731. ];
  17732. for (var i = 0; i < 3; i++)
  17733. {
  17734. if (i < c)
  17735. {
  17736. args.push('color: #ff2424; background: #fff');
  17737. }
  17738. else
  17739. {
  17740. args.push('color: #959595; background: #fff');
  17741. }
  17742. }
  17743. console.log.apply(console, args);
  17744. }
  17745. else if (window['console'])
  17746. {
  17747. console.log('Phaser v' + v + ' | Pixi.js ' + PIXI.VERSION + ' | ' + r + ' | ' + a + ' | http://phaser.io');
  17748. }
  17749. },
  17750. /**
  17751. * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not.
  17752. *
  17753. * @method Phaser.Game#setUpRenderer
  17754. * @protected
  17755. */
  17756. setUpRenderer: function () {
  17757. if (this.device.trident)
  17758. {
  17759. // Pixi WebGL renderer on IE11 doesn't work correctly at the moment, the pre-multiplied alpha gets all washed out.
  17760. // So we're forcing canvas for now until this is fixed, sorry. It's got to be better than no game appearing at all, right?
  17761. this.renderType = Phaser.CANVAS;
  17762. }
  17763. if (this.config['canvasID'])
  17764. {
  17765. this.canvas = Phaser.Canvas.create(this.width, this.height, this.config['canvasID']);
  17766. }
  17767. else
  17768. {
  17769. this.canvas = Phaser.Canvas.create(this.width, this.height);
  17770. }
  17771. if (this.config['canvasStyle'])
  17772. {
  17773. this.canvas.style = this.config['canvasStyle'];
  17774. }
  17775. else
  17776. {
  17777. this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%';
  17778. }
  17779. if (this.device.cocoonJS)
  17780. {
  17781. // Enable screencanvas for Cocoon on this Canvas object only
  17782. this.canvas.screencanvas = true;
  17783. }
  17784. if (this.renderType === Phaser.HEADLESS || this.renderType === Phaser.CANVAS || (this.renderType === Phaser.AUTO && this.device.webGL === false))
  17785. {
  17786. if (this.device.canvas)
  17787. {
  17788. if (this.renderType === Phaser.AUTO)
  17789. {
  17790. this.renderType = Phaser.CANVAS;
  17791. }
  17792. this.renderer = new PIXI.CanvasRenderer(this.width, this.height, this.canvas, this.transparent);
  17793. this.context = this.renderer.context;
  17794. }
  17795. else
  17796. {
  17797. throw new Error('Phaser.Game - cannot create Canvas or WebGL context, aborting.');
  17798. }
  17799. }
  17800. else
  17801. {
  17802. // They requested WebGL and their browser supports it
  17803. this.renderType = Phaser.WEBGL;
  17804. this.renderer = new PIXI.WebGLRenderer(this.width, this.height, this.canvas, this.transparent, this.antialias, this.preserveDrawingBuffer);
  17805. this.context = null;
  17806. }
  17807. if (this.renderType !== Phaser.HEADLESS)
  17808. {
  17809. this.stage.smoothed = this.antialias;
  17810. Phaser.Canvas.addToDOM(this.canvas, this.parent, false);
  17811. Phaser.Canvas.setTouchAction(this.canvas);
  17812. }
  17813. },
  17814. /**
  17815. * The core game loop.
  17816. *
  17817. * @method Phaser.Game#update
  17818. * @protected
  17819. * @param {number} time - The current time as provided by RequestAnimationFrame.
  17820. */
  17821. update: function (time) {
  17822. this.time.update(time);
  17823. if (!this._paused && !this.pendingStep)
  17824. {
  17825. if (this.stepping)
  17826. {
  17827. this.pendingStep = true;
  17828. }
  17829. if (this.config['enableDebug'])
  17830. {
  17831. this.debug.preUpdate();
  17832. }
  17833. this.physics.preUpdate();
  17834. this.state.preUpdate();
  17835. this.plugins.preUpdate();
  17836. this.stage.preUpdate();
  17837. this.state.update();
  17838. this.stage.update();
  17839. this.tweens.update();
  17840. this.sound.update();
  17841. this.input.update();
  17842. this.physics.update();
  17843. this.particles.update();
  17844. this.plugins.update();
  17845. this.stage.postUpdate();
  17846. this.plugins.postUpdate();
  17847. }
  17848. else
  17849. {
  17850. this.state.pauseUpdate();
  17851. if (this.config['enableDebug'])
  17852. {
  17853. this.debug.preUpdate();
  17854. }
  17855. }
  17856. if (this.renderType != Phaser.HEADLESS)
  17857. {
  17858. this.state.preRender();
  17859. this.renderer.render(this.stage);
  17860. this.plugins.render();
  17861. this.state.render();
  17862. this.plugins.postRender();
  17863. if (this.device.cocoonJS && this.renderType === Phaser.CANVAS && this.stage.currentRenderOrderID === 1)
  17864. {
  17865. // Horrible hack! But without it Cocoon fails to render a scene with just a single drawImage call on it.
  17866. this.context.fillRect(0, 0, 0, 0);
  17867. }
  17868. }
  17869. },
  17870. /**
  17871. * Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?)
  17872. * Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors!
  17873. *
  17874. * @method Phaser.Game#enableStep
  17875. */
  17876. enableStep: function () {
  17877. this.stepping = true;
  17878. this.pendingStep = false;
  17879. this.stepCount = 0;
  17880. },
  17881. /**
  17882. * Disables core game loop stepping.
  17883. *
  17884. * @method Phaser.Game#disableStep
  17885. */
  17886. disableStep: function () {
  17887. this.stepping = false;
  17888. this.pendingStep = false;
  17889. },
  17890. /**
  17891. * When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame.
  17892. * This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress.
  17893. *
  17894. * @method Phaser.Game#step
  17895. */
  17896. step: function () {
  17897. this.pendingStep = false;
  17898. this.stepCount++;
  17899. },
  17900. /**
  17901. * Nuke the entire game from orbit
  17902. *
  17903. * @method Phaser.Game#destroy
  17904. */
  17905. destroy: function () {
  17906. this.raf.stop();
  17907. this.input.destroy();
  17908. this.state.destroy();
  17909. this.physics.destroy();
  17910. this.state = null;
  17911. this.cache = null;
  17912. this.input = null;
  17913. this.load = null;
  17914. this.sound = null;
  17915. this.stage = null;
  17916. this.time = null;
  17917. this.world = null;
  17918. this.isBooted = false;
  17919. },
  17920. /**
  17921. * Called by the Stage visibility handler.
  17922. *
  17923. * @method Phaser.Game#gamePaused
  17924. * @param {object} event - The DOM event that caused the game to pause, if any.
  17925. * @protected
  17926. */
  17927. gamePaused: function (event) {
  17928. // If the game is already paused it was done via game code, so don't re-pause it
  17929. if (!this._paused)
  17930. {
  17931. this._paused = true;
  17932. this.time.gamePaused();
  17933. this.sound.setMute();
  17934. this.onPause.dispatch(event);
  17935. }
  17936. },
  17937. /**
  17938. * Called by the Stage visibility handler.
  17939. *
  17940. * @method Phaser.Game#gameResumed
  17941. * @param {object} event - The DOM event that caused the game to pause, if any.
  17942. * @protected
  17943. */
  17944. gameResumed: function (event) {
  17945. // Game is paused, but wasn't paused via code, so resume it
  17946. if (this._paused && !this._codePaused)
  17947. {
  17948. this._paused = false;
  17949. this.time.gameResumed();
  17950. this.input.reset();
  17951. this.sound.unsetMute();
  17952. this.onResume.dispatch(event);
  17953. }
  17954. },
  17955. /**
  17956. * Called by the Stage visibility handler.
  17957. *
  17958. * @method Phaser.Game#focusLoss
  17959. * @param {object} event - The DOM event that caused the game to pause, if any.
  17960. * @protected
  17961. */
  17962. focusLoss: function (event) {
  17963. this.onBlur.dispatch(event);
  17964. if (!this.stage.disableVisibilityChange)
  17965. {
  17966. this.gamePaused(event);
  17967. }
  17968. },
  17969. /**
  17970. * Called by the Stage visibility handler.
  17971. *
  17972. * @method Phaser.Game#focusGain
  17973. * @param {object} event - The DOM event that caused the game to pause, if any.
  17974. * @protected
  17975. */
  17976. focusGain: function (event) {
  17977. this.onFocus.dispatch(event);
  17978. if (!this.stage.disableVisibilityChange)
  17979. {
  17980. this.gameResumed(event);
  17981. }
  17982. }
  17983. };
  17984. Phaser.Game.prototype.constructor = Phaser.Game;
  17985. /**
  17986. * The paused state of the Game. A paused game doesn't update any of its subsystems.
  17987. * When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched.
  17988. * @name Phaser.Game#paused
  17989. * @property {boolean} paused - Gets and sets the paused state of the Game.
  17990. */
  17991. Object.defineProperty(Phaser.Game.prototype, "paused", {
  17992. get: function () {
  17993. return this._paused;
  17994. },
  17995. set: function (value) {
  17996. if (value === true)
  17997. {
  17998. if (this._paused === false)
  17999. {
  18000. this._paused = true;
  18001. this.sound.setMute();
  18002. this.time.gamePaused();
  18003. this.onPause.dispatch(this);
  18004. }
  18005. this._codePaused = true;
  18006. }
  18007. else
  18008. {
  18009. if (this._paused)
  18010. {
  18011. this._paused = false;
  18012. this.input.reset();
  18013. this.sound.unsetMute();
  18014. this.time.gameResumed();
  18015. this.onResume.dispatch(this);
  18016. }
  18017. this._codePaused = false;
  18018. }
  18019. }
  18020. });
  18021. /**
  18022. * "Deleted code is debugged code." - Jeff Sickel
  18023. */
  18024. /**
  18025. * @author Richard Davey <rich@photonstorm.com>
  18026. * @copyright 2014 Photon Storm Ltd.
  18027. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  18028. */
  18029. /**
  18030. * Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer.
  18031. * The Input manager is updated automatically by the core game loop.
  18032. *
  18033. * @class Phaser.Input
  18034. * @constructor
  18035. * @param {Phaser.Game} game - Current game instance.
  18036. */
  18037. Phaser.Input = function (game) {
  18038. /**
  18039. * @property {Phaser.Game} game - A reference to the currently running game.
  18040. */
  18041. this.game = game;
  18042. /**
  18043. * @property {HTMLCanvasElement} hitCanvas - The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection.
  18044. * @default
  18045. */
  18046. this.hitCanvas = null;
  18047. /**
  18048. * @property {CanvasRenderingContext2D} hitContext - The context of the pixel perfect hit canvas.
  18049. * @default
  18050. */
  18051. this.hitContext = null;
  18052. /**
  18053. * @property {array} moveCallbacks - An array of callbacks that will be fired every time the activePointer receives a move event from the DOM.
  18054. */
  18055. this.moveCallbacks = [];
  18056. /**
  18057. * @property {function} moveCallback - An optional callback that will be fired every time the activePointer receives a move event from the DOM. Set to null to disable.
  18058. */
  18059. this.moveCallback = null;
  18060. /**
  18061. * @property {object} moveCallbackContext - The context in which the moveCallback will be sent. Defaults to Phaser.Input but can be set to any valid JS object.
  18062. */
  18063. this.moveCallbackContext = this;
  18064. /**
  18065. * @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.
  18066. * @default
  18067. */
  18068. this.pollRate = 0;
  18069. /**
  18070. * You can disable all Input by setting Input.disabled = true. While set all new input related events will be ignored.
  18071. * If you need to disable just one type of input; for example mouse; use Input.mouse.disabled = true instead
  18072. * @property {boolean} disabled
  18073. * @default
  18074. */
  18075. this.disabled = false;
  18076. /**
  18077. * @property {number} multiInputOverride - Controls the expected behaviour when using a mouse and touch together on a multi-input device.
  18078. * @default
  18079. */
  18080. this.multiInputOverride = Phaser.Input.MOUSE_TOUCH_COMBINE;
  18081. /**
  18082. * @property {Phaser.Point} position - A point object representing the current position of the Pointer.
  18083. * @default
  18084. */
  18085. this.position = null;
  18086. /**
  18087. * @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.
  18088. */
  18089. this.speed = null;
  18090. /**
  18091. * A Circle object centered on the x/y screen coordinates of the Input.
  18092. * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything.
  18093. * @property {Phaser.Circle} circle
  18094. */
  18095. this.circle = null;
  18096. /**
  18097. * @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.
  18098. */
  18099. this.scale = null;
  18100. /**
  18101. * @property {number} maxPointers - The maximum number of Pointers allowed to be active at any one time. For lots of games it's useful to set this to 1.
  18102. * @default
  18103. */
  18104. this.maxPointers = 10;
  18105. /**
  18106. * @property {number} currentPointers - The current number of active Pointers.
  18107. * @default
  18108. */
  18109. this.currentPointers = 0;
  18110. /**
  18111. * @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.
  18112. * @default
  18113. */
  18114. this.tapRate = 200;
  18115. /**
  18116. * @property {number} doubleTapRate - The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click.
  18117. * @default
  18118. */
  18119. this.doubleTapRate = 300;
  18120. /**
  18121. * @property {number} holdRate - The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event.
  18122. * @default
  18123. */
  18124. this.holdRate = 2000;
  18125. /**
  18126. * @property {number} justPressedRate - The number of milliseconds below which the Pointer is considered justPressed.
  18127. * @default
  18128. */
  18129. this.justPressedRate = 200;
  18130. /**
  18131. * @property {number} justReleasedRate - The number of milliseconds below which the Pointer is considered justReleased .
  18132. * @default
  18133. */
  18134. this.justReleasedRate = 200;
  18135. /**
  18136. * Sets if the Pointer objects should record a history of x/y coordinates they have passed through.
  18137. * The history is cleared each time the Pointer is pressed down.
  18138. * The history is updated at the rate specified in Input.pollRate
  18139. * @property {boolean} recordPointerHistory
  18140. * @default
  18141. */
  18142. this.recordPointerHistory = false;
  18143. /**
  18144. * @property {number} recordRate - The rate in milliseconds at which the Pointer objects should update their tracking history.
  18145. * @default
  18146. */
  18147. this.recordRate = 100;
  18148. /**
  18149. * The total number of entries that can be recorded into the Pointer objects tracking history.
  18150. * If the Pointer is tracking one event every 100ms; then a trackLimit of 100 would store the last 10 seconds worth of history.
  18151. * @property {number} recordLimit
  18152. * @default
  18153. */
  18154. this.recordLimit = 100;
  18155. /**
  18156. * @property {Phaser.Pointer} pointer1 - A Pointer object.
  18157. */
  18158. this.pointer1 = null;
  18159. /**
  18160. * @property {Phaser.Pointer} pointer2 - A Pointer object.
  18161. */
  18162. this.pointer2 = null;
  18163. /**
  18164. * @property {Phaser.Pointer} pointer3 - A Pointer object.
  18165. */
  18166. this.pointer3 = null;
  18167. /**
  18168. * @property {Phaser.Pointer} pointer4 - A Pointer object.
  18169. */
  18170. this.pointer4 = null;
  18171. /**
  18172. * @property {Phaser.Pointer} pointer5 - A Pointer object.
  18173. */
  18174. this.pointer5 = null;
  18175. /**
  18176. * @property {Phaser.Pointer} pointer6 - A Pointer object.
  18177. */
  18178. this.pointer6 = null;
  18179. /**
  18180. * @property {Phaser.Pointer} pointer7 - A Pointer object.
  18181. */
  18182. this.pointer7 = null;
  18183. /**
  18184. * @property {Phaser.Pointer} pointer8 - A Pointer object.
  18185. */
  18186. this.pointer8 = null;
  18187. /**
  18188. * @property {Phaser.Pointer} pointer9 - A Pointer object.
  18189. */
  18190. this.pointer9 = null;
  18191. /**
  18192. * @property {Phaser.Pointer} pointer10 - A Pointer object.
  18193. */
  18194. this.pointer10 = null;
  18195. /**
  18196. * The most recently active Pointer object.
  18197. * When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse.
  18198. * @property {Phaser.Pointer} activePointer
  18199. */
  18200. this.activePointer = null;
  18201. /**
  18202. * @property {Pointer} mousePointer - The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game.
  18203. */
  18204. this.mousePointer = null;
  18205. /**
  18206. * @property {Phaser.Mouse} mouse - The Mouse Input manager.
  18207. */
  18208. this.mouse = null;
  18209. /**
  18210. * @property {Phaser.Keyboard} keyboard - The Keyboard Input manager.
  18211. */
  18212. this.keyboard = null;
  18213. /**
  18214. * @property {Phaser.Touch} touch - the Touch Input manager.
  18215. */
  18216. this.touch = null;
  18217. /**
  18218. * @property {Phaser.MSPointer} mspointer - The MSPointer Input manager.
  18219. */
  18220. this.mspointer = null;
  18221. /**
  18222. * @property {Phaser.Gamepad} gamepad - The Gamepad Input manager.
  18223. */
  18224. this.gamepad = null;
  18225. /**
  18226. * @property {Phaser.Gestures} gestures - The Gestures manager.
  18227. */
  18228. // this.gestures = null;
  18229. /**
  18230. * @property {boolean} resetLocked - If the Input Manager has been reset locked then all calls made to InputManager.reset, such as from a State change, are ignored.
  18231. * @default
  18232. */
  18233. this.resetLocked = false;
  18234. /**
  18235. * @property {Phaser.Signal} onDown - A Signal that is dispatched each time a pointer is pressed down.
  18236. */
  18237. this.onDown = null;
  18238. /**
  18239. * @property {Phaser.Signal} onUp - A Signal that is dispatched each time a pointer is released.
  18240. */
  18241. this.onUp = null;
  18242. /**
  18243. * @property {Phaser.Signal} onTap - A Signal that is dispatched each time a pointer is tapped.
  18244. */
  18245. this.onTap = null;
  18246. /**
  18247. * @property {Phaser.Signal} onHold - A Signal that is dispatched each time a pointer is held down.
  18248. */
  18249. this.onHold = null;
  18250. /**
  18251. * @property {number} minPriorityID - You can tell all Pointers to ignore any object with a priorityID lower than the minPriorityID. Useful when stacking UI layers. Set to zero to disable.
  18252. * @default
  18253. */
  18254. this.minPriorityID = 0;
  18255. /**
  18256. * A list of interactive objects. The InputHandler components add and remove themselves from this list.
  18257. * @property {Phaser.ArrayList} interactiveItems
  18258. */
  18259. this.interactiveItems = new Phaser.ArrayList();
  18260. /**
  18261. * @property {Phaser.Point} _localPoint - Internal cache var.
  18262. * @private
  18263. */
  18264. this._localPoint = new Phaser.Point();
  18265. /**
  18266. * @property {number} _pollCounter - Internal var holding the current poll counter.
  18267. * @private
  18268. */
  18269. this._pollCounter = 0;
  18270. /**
  18271. * @property {Phaser.Point} _oldPosition - A point object representing the previous position of the Pointer.
  18272. * @private
  18273. */
  18274. this._oldPosition = null;
  18275. /**
  18276. * @property {number} _x - x coordinate of the most recent Pointer event
  18277. * @private
  18278. */
  18279. this._x = 0;
  18280. /**
  18281. * @property {number} _y - Y coordinate of the most recent Pointer event
  18282. * @private
  18283. */
  18284. this._y = 0;
  18285. };
  18286. /**
  18287. * @constant
  18288. * @type {number}
  18289. */
  18290. Phaser.Input.MOUSE_OVERRIDES_TOUCH = 0;
  18291. /**
  18292. * @constant
  18293. * @type {number}
  18294. */
  18295. Phaser.Input.TOUCH_OVERRIDES_MOUSE = 1;
  18296. /**
  18297. * @constant
  18298. * @type {number}
  18299. */
  18300. Phaser.Input.MOUSE_TOUCH_COMBINE = 2;
  18301. Phaser.Input.prototype = {
  18302. /**
  18303. * Starts the Input Manager running.
  18304. * @method Phaser.Input#boot
  18305. * @protected
  18306. */
  18307. boot: function () {
  18308. this.mousePointer = new Phaser.Pointer(this.game, 0);
  18309. this.pointer1 = new Phaser.Pointer(this.game, 1);
  18310. this.pointer2 = new Phaser.Pointer(this.game, 2);
  18311. this.mouse = new Phaser.Mouse(this.game);
  18312. this.keyboard = new Phaser.Keyboard(this.game);
  18313. this.touch = new Phaser.Touch(this.game);
  18314. this.mspointer = new Phaser.MSPointer(this.game);
  18315. this.gamepad = new Phaser.Gamepad(this.game);
  18316. // this.gestures = new Phaser.Gestures(this.game);
  18317. this.onDown = new Phaser.Signal();
  18318. this.onUp = new Phaser.Signal();
  18319. this.onTap = new Phaser.Signal();
  18320. this.onHold = new Phaser.Signal();
  18321. this.scale = new Phaser.Point(1, 1);
  18322. this.speed = new Phaser.Point();
  18323. this.position = new Phaser.Point();
  18324. this._oldPosition = new Phaser.Point();
  18325. this.circle = new Phaser.Circle(0, 0, 44);
  18326. this.activePointer = this.mousePointer;
  18327. this.currentPointers = 0;
  18328. this.hitCanvas = document.createElement('canvas');
  18329. this.hitCanvas.width = 1;
  18330. this.hitCanvas.height = 1;
  18331. this.hitContext = this.hitCanvas.getContext('2d');
  18332. this.mouse.start();
  18333. this.keyboard.start();
  18334. this.touch.start();
  18335. this.mspointer.start();
  18336. this.mousePointer.active = true;
  18337. },
  18338. /**
  18339. * Stops all of the Input Managers from running.
  18340. * @method Phaser.Input#destroy
  18341. */
  18342. destroy: function () {
  18343. this.mouse.stop();
  18344. this.keyboard.stop();
  18345. this.touch.stop();
  18346. this.mspointer.stop();
  18347. this.gamepad.stop();
  18348. // this.gestures.stop();
  18349. this.moveCallbacks = [];
  18350. // DEPRECATED
  18351. this.moveCallback = null;
  18352. },
  18353. /**
  18354. * DEPRECATED: This method will be removed in a future major point release. Please use Input.addMoveCallback instead.
  18355. *
  18356. * Sets a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove.
  18357. * 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
  18358. * to only use if you've limited input to a single pointer (i.e. mouse or touch)
  18359. *
  18360. * @method Phaser.Input#setMoveCallback
  18361. * @param {function} callback - The callback that will be called each time the activePointer receives a DOM move event.
  18362. * @param {object} callbackContext - The context in which the callback will be called.
  18363. */
  18364. setMoveCallback: function (callback, callbackContext) {
  18365. this.moveCallback = callback;
  18366. this.moveCallbackContext = callbackContext;
  18367. },
  18368. /**
  18369. * Adds a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove.
  18370. * 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
  18371. * to only use if you've limited input to a single pointer (i.e. mouse or touch).
  18372. * The callback is added to the Phaser.Input.moveCallbacks array and should be removed with Phaser.Input.deleteMoveCallback.
  18373. *
  18374. * @method Phaser.Input#addMoveCallback
  18375. * @param {function} callback - The callback that will be called each time the activePointer receives a DOM move event.
  18376. * @param {object} callbackContext - The context in which the callback will be called.
  18377. * @return {number} The index of the callback entry. Use this index when calling Input.deleteMoveCallback.
  18378. */
  18379. addMoveCallback: function (callback, callbackContext) {
  18380. return this.moveCallbacks.push( { callback: callback, context: callbackContext }) - 1;
  18381. },
  18382. /**
  18383. * Removes the callback at the defined index from the Phaser.Input.moveCallbacks array
  18384. *
  18385. * @method Phaser.Input#deleteMoveCallback
  18386. * @param {number} index - The index of the callback to remove.
  18387. */
  18388. deleteMoveCallback: function (index) {
  18389. if (this.moveCallbacks[index])
  18390. {
  18391. this.moveCallbacks.splice(index, 1);
  18392. }
  18393. },
  18394. /**
  18395. * Add a new Pointer object to the Input Manager. By default Input creates 3 pointer objects: mousePointer, pointer1 and pointer2.
  18396. * If you need more then use this to create a new one, up to a maximum of 10.
  18397. * @method Phaser.Input#addPointer
  18398. * @return {Phaser.Pointer} A reference to the new Pointer object that was created.
  18399. */
  18400. addPointer: function () {
  18401. var next = 0;
  18402. for (var i = 10; i > 0; i--)
  18403. {
  18404. if (this['pointer' + i] === null)
  18405. {
  18406. next = i;
  18407. }
  18408. }
  18409. if (next === 0)
  18410. {
  18411. console.warn("You can only have 10 Pointer objects");
  18412. return null;
  18413. }
  18414. else
  18415. {
  18416. this['pointer' + next] = new Phaser.Pointer(this.game, next);
  18417. return this['pointer' + next];
  18418. }
  18419. },
  18420. /**
  18421. * Updates the Input Manager. Called by the core Game loop.
  18422. *
  18423. * @method Phaser.Input#update
  18424. * @protected
  18425. */
  18426. update: function () {
  18427. this.keyboard.update();
  18428. if (this.pollRate > 0 && this._pollCounter < this.pollRate)
  18429. {
  18430. this._pollCounter++;
  18431. return;
  18432. }
  18433. this.speed.x = this.position.x - this._oldPosition.x;
  18434. this.speed.y = this.position.y - this._oldPosition.y;
  18435. this._oldPosition.copyFrom(this.position);
  18436. this.mousePointer.update();
  18437. if (this.gamepad.active) { this.gamepad.update(); }
  18438. this.pointer1.update();
  18439. this.pointer2.update();
  18440. if (this.pointer3) { this.pointer3.update(); }
  18441. if (this.pointer4) { this.pointer4.update(); }
  18442. if (this.pointer5) { this.pointer5.update(); }
  18443. if (this.pointer6) { this.pointer6.update(); }
  18444. if (this.pointer7) { this.pointer7.update(); }
  18445. if (this.pointer8) { this.pointer8.update(); }
  18446. if (this.pointer9) { this.pointer9.update(); }
  18447. if (this.pointer10) { this.pointer10.update(); }
  18448. this._pollCounter = 0;
  18449. // if (this.gestures.active) { this.gestures.update(); }
  18450. },
  18451. /**
  18452. * Reset all of the Pointers and Input states. The optional `hard` parameter will reset any events or callbacks that may be bound.
  18453. * Input.reset is called automatically during a State change or if a game loses focus / visibility. If you wish to control the reset
  18454. * directly yourself then set InputManager.resetLocked to `true`.
  18455. *
  18456. * @method Phaser.Input#reset
  18457. * @param {boolean} [hard=false] - A soft reset won't reset any events or callbacks that are bound. A hard reset will.
  18458. */
  18459. reset: function (hard) {
  18460. if (!this.game.isBooted || this.resetLocked)
  18461. {
  18462. return;
  18463. }
  18464. if (typeof hard === 'undefined') { hard = false; }
  18465. this.keyboard.reset(hard);
  18466. this.mousePointer.reset();
  18467. this.gamepad.reset();
  18468. for (var i = 1; i <= 10; i++)
  18469. {
  18470. if (this['pointer' + i])
  18471. {
  18472. this['pointer' + i].reset();
  18473. }
  18474. }
  18475. this.currentPointers = 0;
  18476. if (this.game.canvas.style.cursor !== 'none')
  18477. {
  18478. this.game.canvas.style.cursor = 'inherit';
  18479. }
  18480. if (hard)
  18481. {
  18482. this.onDown.dispose();
  18483. this.onUp.dispose();
  18484. this.onTap.dispose();
  18485. this.onHold.dispose();
  18486. this.onDown = new Phaser.Signal();
  18487. this.onUp = new Phaser.Signal();
  18488. this.onTap = new Phaser.Signal();
  18489. this.onHold = new Phaser.Signal();
  18490. this.moveCallbacks = [];
  18491. }
  18492. this._pollCounter = 0;
  18493. },
  18494. /**
  18495. * Resets the speed and old position properties.
  18496. * @method Phaser.Input#resetSpeed
  18497. * @param {number} x - Sets the oldPosition.x value.
  18498. * @param {number} y - Sets the oldPosition.y value.
  18499. */
  18500. resetSpeed: function (x, y) {
  18501. this._oldPosition.setTo(x, y);
  18502. this.speed.setTo(0, 0);
  18503. },
  18504. /**
  18505. * Find the first free Pointer object and start it, passing in the event data. This is called automatically by Phaser.Touch and Phaser.MSPointer.
  18506. * @method Phaser.Input#startPointer
  18507. * @param {Any} event - The event data from the Touch event.
  18508. * @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available.
  18509. */
  18510. startPointer: function (event) {
  18511. if (this.maxPointers < 10 && this.totalActivePointers == this.maxPointers)
  18512. {
  18513. return null;
  18514. }
  18515. if (this.pointer1.active === false)
  18516. {
  18517. return this.pointer1.start(event);
  18518. }
  18519. else if (this.pointer2.active === false)
  18520. {
  18521. return this.pointer2.start(event);
  18522. }
  18523. else
  18524. {
  18525. for (var i = 3; i <= 10; i++)
  18526. {
  18527. if (this['pointer' + i] && this['pointer' + i].active === false)
  18528. {
  18529. return this['pointer' + i].start(event);
  18530. }
  18531. }
  18532. }
  18533. return null;
  18534. },
  18535. /**
  18536. * Updates the matching Pointer object, passing in the event data. This is called automatically and should not normally need to be invoked.
  18537. * @method Phaser.Input#updatePointer
  18538. * @param {Any} event - The event data from the Touch event.
  18539. * @return {Phaser.Pointer} The Pointer object that was updated or null if no Pointer object is available.
  18540. */
  18541. updatePointer: function (event) {
  18542. if (this.pointer1.active && this.pointer1.identifier == event.identifier)
  18543. {
  18544. return this.pointer1.move(event);
  18545. }
  18546. else if (this.pointer2.active && this.pointer2.identifier == event.identifier)
  18547. {
  18548. return this.pointer2.move(event);
  18549. }
  18550. else
  18551. {
  18552. for (var i = 3; i <= 10; i++)
  18553. {
  18554. if (this['pointer' + i] && this['pointer' + i].active && this['pointer' + i].identifier == event.identifier)
  18555. {
  18556. return this['pointer' + i].move(event);
  18557. }
  18558. }
  18559. }
  18560. return null;
  18561. },
  18562. /**
  18563. * Stops the matching Pointer object, passing in the event data.
  18564. * @method Phaser.Input#stopPointer
  18565. * @param {Any} event - The event data from the Touch event.
  18566. * @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available.
  18567. */
  18568. stopPointer: function (event) {
  18569. if (this.pointer1.active && this.pointer1.identifier == event.identifier)
  18570. {
  18571. return this.pointer1.stop(event);
  18572. }
  18573. else if (this.pointer2.active && this.pointer2.identifier == event.identifier)
  18574. {
  18575. return this.pointer2.stop(event);
  18576. }
  18577. else
  18578. {
  18579. for (var i = 3; i <= 10; i++)
  18580. {
  18581. if (this['pointer' + i] && this['pointer' + i].active && this['pointer' + i].identifier == event.identifier)
  18582. {
  18583. return this['pointer' + i].stop(event);
  18584. }
  18585. }
  18586. }
  18587. return null;
  18588. },
  18589. /**
  18590. * Get the next Pointer object whos active property matches the given state
  18591. * @method Phaser.Input#getPointer
  18592. * @param {boolean} state - The state the Pointer should be in (false for inactive, true for active).
  18593. * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state.
  18594. */
  18595. getPointer: function (state) {
  18596. state = state || false;
  18597. if (this.pointer1.active == state)
  18598. {
  18599. return this.pointer1;
  18600. }
  18601. else if (this.pointer2.active == state)
  18602. {
  18603. return this.pointer2;
  18604. }
  18605. else
  18606. {
  18607. for (var i = 3; i <= 10; i++)
  18608. {
  18609. if (this['pointer' + i] && this['pointer' + i].active == state)
  18610. {
  18611. return this['pointer' + i];
  18612. }
  18613. }
  18614. }
  18615. return null;
  18616. },
  18617. /**
  18618. * Get the Pointer object whos `identifier` property matches the given identifier value.
  18619. * The identifier property is not set until the Pointer has been used at least once, as its populated by the DOM event.
  18620. * Also it can change every time you press the pointer down, and is not fixed once set.
  18621. * Note: Not all browsers set the identifier property and it's not part of the W3C spec, so you may need getPointerFromId instead.
  18622. *
  18623. * @method Phaser.Input#getPointerFromIdentifier
  18624. * @param {number} identifier - The Pointer.identifier value to search for.
  18625. * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier.
  18626. */
  18627. getPointerFromIdentifier: function (identifier) {
  18628. if (this.pointer1.identifier === identifier)
  18629. {
  18630. return this.pointer1;
  18631. }
  18632. else if (this.pointer2.identifier === identifier)
  18633. {
  18634. return this.pointer2;
  18635. }
  18636. else
  18637. {
  18638. for (var i = 3; i <= 10; i++)
  18639. {
  18640. if (this['pointer' + i] && this['pointer' + i].identifier === identifier)
  18641. {
  18642. return this['pointer' + i];
  18643. }
  18644. }
  18645. }
  18646. return null;
  18647. },
  18648. /**
  18649. * Get the Pointer object whos `pointerId` property matches the given value.
  18650. * The pointerId property is not set until the Pointer has been used at least once, as its populated by the DOM event.
  18651. * Also it can change every time you press the pointer down if the browser recycles it.
  18652. *
  18653. * @method Phaser.Input#getPointerFromId
  18654. * @param {number} pointerId - The Pointer.pointerId value to search for.
  18655. * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier.
  18656. */
  18657. getPointerFromId: function (pointerId) {
  18658. if (this.pointer1.pointerId === pointerId)
  18659. {
  18660. return this.pointer1;
  18661. }
  18662. else if (this.pointer2.pointerId === pointerId)
  18663. {
  18664. return this.pointer2;
  18665. }
  18666. else
  18667. {
  18668. for (var i = 3; i <= 10; i++)
  18669. {
  18670. if (this['pointer' + i] && this['pointer' + i].pointerId === pointerId)
  18671. {
  18672. return this['pointer' + i];
  18673. }
  18674. }
  18675. }
  18676. return null;
  18677. },
  18678. /**
  18679. * This will return the local coordinates of the specified displayObject based on the given Pointer.
  18680. * @method Phaser.Input#getLocalPosition
  18681. * @param {Phaser.Sprite|Phaser.Image} displayObject - The DisplayObject to get the local coordinates for.
  18682. * @param {Phaser.Pointer} pointer - The Pointer to use in the check against the displayObject.
  18683. * @return {Phaser.Point} A point containing the coordinates of the Pointer position relative to the DisplayObject.
  18684. */
  18685. getLocalPosition: function (displayObject, pointer, output) {
  18686. if (typeof output === 'undefined') { output = new Phaser.Point(); }
  18687. var wt = displayObject.worldTransform;
  18688. var id = 1 / (wt.a * wt.d + wt.b * -wt.c);
  18689. return output.setTo(
  18690. wt.d * id * pointer.x + -wt.b * id * pointer.y + (wt.ty * wt.b - wt.tx * wt.d) * id,
  18691. wt.a * id * pointer.y + -wt.c * id * pointer.x + (-wt.ty * wt.a + wt.tx * wt.c) * id
  18692. );
  18693. },
  18694. /**
  18695. * Tests if the pointer hits the given object.
  18696. *
  18697. * @method Phaser.Input#hitTest
  18698. * @param {DisplayObject} displayObject - The displayObject to test for a hit.
  18699. * @param {Phaser.Pointer} pointer - The pointer to use for the test.
  18700. * @param {Phaser.Point} localPoint - The local translated point.
  18701. */
  18702. hitTest: function (displayObject, pointer, localPoint) {
  18703. if (!displayObject.worldVisible)
  18704. {
  18705. return false;
  18706. }
  18707. this.getLocalPosition(displayObject, pointer, this._localPoint);
  18708. localPoint.copyFrom(this._localPoint);
  18709. if (displayObject.hitArea && displayObject.hitArea.contains)
  18710. {
  18711. if (displayObject.hitArea.contains(this._localPoint.x, this._localPoint.y))
  18712. {
  18713. return true;
  18714. }
  18715. return false;
  18716. }
  18717. else if (displayObject instanceof Phaser.TileSprite)
  18718. {
  18719. var width = displayObject.width;
  18720. var height = displayObject.height;
  18721. var x1 = -width * displayObject.anchor.x;
  18722. if (this._localPoint.x > x1 && this._localPoint.x < x1 + width)
  18723. {
  18724. var y1 = -height * displayObject.anchor.y;
  18725. if (this._localPoint.y > y1 && this._localPoint.y < y1 + height)
  18726. {
  18727. return true;
  18728. }
  18729. }
  18730. }
  18731. else if (displayObject instanceof PIXI.Sprite)
  18732. {
  18733. var width = displayObject.texture.frame.width;
  18734. var height = displayObject.texture.frame.height;
  18735. var x1 = -width * displayObject.anchor.x;
  18736. if (this._localPoint.x > x1 && this._localPoint.x < x1 + width)
  18737. {
  18738. var y1 = -height * displayObject.anchor.y;
  18739. if (this._localPoint.y > y1 && this._localPoint.y < y1 + height)
  18740. {
  18741. return true;
  18742. }
  18743. }
  18744. }
  18745. for (var i = 0, len = displayObject.children.length; i < len; i++)
  18746. {
  18747. if (this.hitTest(displayObject.children[i], pointer, localPoint))
  18748. {
  18749. return true;
  18750. }
  18751. }
  18752. return false;
  18753. }
  18754. };
  18755. Phaser.Input.prototype.constructor = Phaser.Input;
  18756. /**
  18757. * The X coordinate of the most recently active pointer. This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values.
  18758. * @name Phaser.Input#x
  18759. * @property {number} x - The X coordinate of the most recently active pointer.
  18760. */
  18761. Object.defineProperty(Phaser.Input.prototype, "x", {
  18762. get: function () {
  18763. return this._x;
  18764. },
  18765. set: function (value) {
  18766. this._x = Math.floor(value);
  18767. }
  18768. });
  18769. /**
  18770. * The Y coordinate of the most recently active pointer. This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values.
  18771. * @name Phaser.Input#y
  18772. * @property {number} y - The Y coordinate of the most recently active pointer.
  18773. */
  18774. Object.defineProperty(Phaser.Input.prototype, "y", {
  18775. get: function () {
  18776. return this._y;
  18777. },
  18778. set: function (value) {
  18779. this._y = Math.floor(value);
  18780. }
  18781. });
  18782. /**
  18783. * @name Phaser.Input#pollLocked
  18784. * @property {boolean} pollLocked - True if the Input is currently poll rate locked.
  18785. * @readonly
  18786. */
  18787. Object.defineProperty(Phaser.Input.prototype, "pollLocked", {
  18788. get: function () {
  18789. return (this.pollRate > 0 && this._pollCounter < this.pollRate);
  18790. }
  18791. });
  18792. /**
  18793. * The total number of inactive Pointers
  18794. * @name Phaser.Input#totalInactivePointers
  18795. * @property {number} totalInactivePointers - The total number of inactive Pointers.
  18796. * @readonly
  18797. */
  18798. Object.defineProperty(Phaser.Input.prototype, "totalInactivePointers", {
  18799. get: function () {
  18800. return 10 - this.currentPointers;
  18801. }
  18802. });
  18803. /**
  18804. * The total number of active Pointers
  18805. * @name Phaser.Input#totalActivePointers
  18806. * @property {number} totalActivePointers - The total number of active Pointers.
  18807. * @readonly
  18808. */
  18809. Object.defineProperty(Phaser.Input.prototype, "totalActivePointers", {
  18810. get: function () {
  18811. this.currentPointers = 0;
  18812. for (var i = 1; i <= 10; i++)
  18813. {
  18814. if (this['pointer' + i] && this['pointer' + i].active)
  18815. {
  18816. this.currentPointers++;
  18817. }
  18818. }
  18819. return this.currentPointers;
  18820. }
  18821. });
  18822. /**
  18823. * The world X coordinate of the most recently active pointer.
  18824. * @name Phaser.Input#worldX
  18825. * @property {number} worldX - The world X coordinate of the most recently active pointer.
  18826. */
  18827. Object.defineProperty(Phaser.Input.prototype, "worldX", {
  18828. get: function () {
  18829. return this.game.camera.view.x + this.x;
  18830. }
  18831. });
  18832. /**
  18833. * The world Y coordinate of the most recently active pointer.
  18834. * @name Phaser.Input#worldY
  18835. * @property {number} worldY - The world Y coordinate of the most recently active pointer.
  18836. */
  18837. Object.defineProperty(Phaser.Input.prototype, "worldY", {
  18838. get: function () {
  18839. return this.game.camera.view.y + this.y;
  18840. }
  18841. });
  18842. /**
  18843. * @author Richard Davey <rich@photonstorm.com>
  18844. * @copyright 2014 Photon Storm Ltd.
  18845. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  18846. */
  18847. /**
  18848. * @class Phaser.Key
  18849. * @classdesc If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects.
  18850. * @constructor
  18851. * @param {Phaser.Game} game - Current game instance.
  18852. * @param {number} keycode - The key code this Key is responsible for.
  18853. */
  18854. Phaser.Key = function (game, keycode) {
  18855. /**
  18856. * @property {Phaser.Game} game - A reference to the currently running game.
  18857. */
  18858. this.game = game;
  18859. /**
  18860. * @property {boolean} enabled - An enabled key processes its update and dispatches events. You can toggle this at run-time to disable a key without deleting it.
  18861. * @default
  18862. */
  18863. this.enabled = true;
  18864. /**
  18865. * @property {object} event - Stores the most recent DOM event.
  18866. * @readonly
  18867. */
  18868. this.event = null;
  18869. /**
  18870. * @property {boolean} isDown - The "down" state of the key.
  18871. * @default
  18872. */
  18873. this.isDown = false;
  18874. /**
  18875. * @property {boolean} isUp - The "up" state of the key.
  18876. * @default
  18877. */
  18878. this.isUp = true;
  18879. /**
  18880. * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key.
  18881. * @default
  18882. */
  18883. this.altKey = false;
  18884. /**
  18885. * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key.
  18886. * @default
  18887. */
  18888. this.ctrlKey = false;
  18889. /**
  18890. * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key.
  18891. * @default
  18892. */
  18893. this.shiftKey = false;
  18894. /**
  18895. * @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now.
  18896. */
  18897. this.timeDown = 0;
  18898. /**
  18899. * If the key is down this value holds the duration of that key press and is constantly updated.
  18900. * If the key is up it holds the duration of the previous down session.
  18901. * @property {number} duration - The number of milliseconds this key has been held down for.
  18902. * @default
  18903. */
  18904. this.duration = 0;
  18905. /**
  18906. * @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now.
  18907. * @default
  18908. */
  18909. this.timeUp = -2500;
  18910. /**
  18911. * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'.
  18912. * @default
  18913. */
  18914. this.repeats = 0;
  18915. /**
  18916. * @property {number} keyCode - The keycode of this key.
  18917. */
  18918. this.keyCode = keycode;
  18919. /**
  18920. * @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).
  18921. */
  18922. this.onDown = new Phaser.Signal();
  18923. /**
  18924. * @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.
  18925. */
  18926. this.onHoldCallback = null;
  18927. /**
  18928. * @property {object} onHoldContext - The context under which the onHoldCallback will be called.
  18929. */
  18930. this.onHoldContext = null;
  18931. /**
  18932. * @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again).
  18933. */
  18934. this.onUp = new Phaser.Signal();
  18935. };
  18936. Phaser.Key.prototype = {
  18937. update: function () {
  18938. if (!this.enabled) { return; }
  18939. if (this.isDown)
  18940. {
  18941. this.duration = this.game.time.now - this.timeDown;
  18942. this.repeats++;
  18943. if (this.onHoldCallback)
  18944. {
  18945. this.onHoldCallback.call(this.onHoldContext, this);
  18946. }
  18947. }
  18948. },
  18949. /**
  18950. * Called automatically by Phaser.Keyboard.
  18951. * @method Phaser.Key#processKeyDown
  18952. * @param {KeyboardEvent} event.
  18953. * @protected
  18954. */
  18955. processKeyDown: function (event) {
  18956. if (!this.enabled) { return; }
  18957. this.event = event;
  18958. if (this.isDown)
  18959. {
  18960. return;
  18961. }
  18962. this.altKey = event.altKey;
  18963. this.ctrlKey = event.ctrlKey;
  18964. this.shiftKey = event.shiftKey;
  18965. this.isDown = true;
  18966. this.isUp = false;
  18967. this.timeDown = this.game.time.now;
  18968. this.duration = 0;
  18969. this.repeats = 0;
  18970. this.onDown.dispatch(this);
  18971. },
  18972. /**
  18973. * Called automatically by Phaser.Keyboard.
  18974. * @method Phaser.Key#processKeyUp
  18975. * @param {KeyboardEvent} event.
  18976. * @protected
  18977. */
  18978. processKeyUp: function (event) {
  18979. if (!this.enabled) { return; }
  18980. this.event = event;
  18981. if (this.isUp)
  18982. {
  18983. return;
  18984. }
  18985. this.isDown = false;
  18986. this.isUp = true;
  18987. this.timeUp = this.game.time.now;
  18988. this.duration = this.game.time.now - this.timeDown;
  18989. this.onUp.dispatch(this);
  18990. },
  18991. /**
  18992. * Resets the state of this Key. This sets isDown to false, isUp to true, resets the time to be the current time and clears any callbacks
  18993. * associated with the onDown and onUp events and nulls the onHoldCallback if set.
  18994. *
  18995. * @method Phaser.Key#reset
  18996. * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to this Key. A hard reset will.
  18997. */
  18998. reset: function (hard) {
  18999. if (typeof hard === 'undefined') { hard = true; }
  19000. this.isDown = false;
  19001. this.isUp = true;
  19002. this.timeUp = this.game.time.now;
  19003. this.duration = 0;
  19004. this.enabled = true;
  19005. if (hard)
  19006. {
  19007. this.onDown.removeAll();
  19008. this.onUp.removeAll();
  19009. this.onHoldCallback = null;
  19010. this.onHoldContext = null;
  19011. }
  19012. },
  19013. /**
  19014. * Returns the "just pressed" state of the Key. Just pressed is considered true if the key was pressed down within the duration given (default 250ms)
  19015. * @method Phaser.Key#justPressed
  19016. * @param {number} [duration=50] - The duration below which the key is considered as being just pressed.
  19017. * @return {boolean} True if the key is just pressed otherwise false.
  19018. */
  19019. justPressed: function (duration) {
  19020. if (typeof duration === "undefined") { duration = 50; }
  19021. return (this.isDown && this.duration < duration);
  19022. },
  19023. /**
  19024. * Returns the "just released" state of the Key. Just released is considered as being true if the key was released within the duration given (default 250ms)
  19025. * @method Phaser.Key#justReleased
  19026. * @param {number} [duration=50] - The duration below which the key is considered as being just released.
  19027. * @return {boolean} True if the key is just released otherwise false.
  19028. */
  19029. justReleased: function (duration) {
  19030. if (typeof duration === "undefined") { duration = 50; }
  19031. return (!this.isDown && ((this.game.time.now - this.timeUp) < duration));
  19032. }
  19033. };
  19034. Phaser.Key.prototype.constructor = Phaser.Key;
  19035. /**
  19036. * @author Richard Davey <rich@photonstorm.com>
  19037. * @copyright 2014 Photon Storm Ltd.
  19038. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  19039. */
  19040. /**
  19041. * The Keyboard class handles looking after keyboard input for your game.
  19042. * It will recognise and respond to key presses and dispatch the required events.
  19043. * Please be aware that lots of keyboards are unable to process certain combinations of keys due to hardware
  19044. * limitations known as ghosting. Full details here: http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/
  19045. *
  19046. * @class Phaser.Keyboard
  19047. * @constructor
  19048. * @param {Phaser.Game} game - A reference to the currently running game.
  19049. */
  19050. Phaser.Keyboard = function (game) {
  19051. /**
  19052. * @property {Phaser.Game} game - Local reference to game.
  19053. */
  19054. this.game = game;
  19055. /**
  19056. * You can disable all Keyboard Input by setting disabled to true. While true all new input related events will be ignored.
  19057. * @property {boolean} disabled - The disabled state of the Keyboard.
  19058. * @default
  19059. */
  19060. this.disabled = false;
  19061. /**
  19062. * @property {Object} event - The most recent DOM event from keydown or keyup. This is updated every time a new key is pressed or released.
  19063. */
  19064. this.event = null;
  19065. /**
  19066. * @property {Object} pressEvent - The most recent DOM event from keypress.
  19067. */
  19068. this.pressEvent = null;
  19069. /**
  19070. * @property {Object} callbackContext - The context under which the callbacks are run.
  19071. */
  19072. this.callbackContext = this;
  19073. /**
  19074. * @property {function} onDownCallback - This callback is invoked every time a key is pressed down, including key repeats when a key is held down.
  19075. */
  19076. this.onDownCallback = null;
  19077. /**
  19078. * @property {function} onPressCallback - This callback is invoked every time a DOM onkeypress event is raised, which is only for printable keys.
  19079. */
  19080. this.onPressCallback = null;
  19081. /**
  19082. * @property {function} onUpCallback - This callback is invoked every time a key is released.
  19083. */
  19084. this.onUpCallback = null;
  19085. /**
  19086. * @property {array<Phaser.Key>} _keys - The array the Phaser.Key objects are stored in.
  19087. * @private
  19088. */
  19089. this._keys = [];
  19090. /**
  19091. * @property {array} _capture - The array the key capture values are stored in.
  19092. * @private
  19093. */
  19094. this._capture = [];
  19095. /**
  19096. * @property {function} _onKeyDown
  19097. * @private
  19098. * @default
  19099. */
  19100. this._onKeyDown = null;
  19101. /**
  19102. * @property {function} _onKeyPress
  19103. * @private
  19104. * @default
  19105. */
  19106. this._onKeyPress = null;
  19107. /**
  19108. * @property {function} _onKeyUp
  19109. * @private
  19110. * @default
  19111. */
  19112. this._onKeyUp = null;
  19113. /**
  19114. * @property {number} _i - Internal cache var
  19115. * @private
  19116. */
  19117. this._i = 0;
  19118. /**
  19119. * @property {number} _k - Internal cache var
  19120. * @private
  19121. */
  19122. this._k = 0;
  19123. };
  19124. Phaser.Keyboard.prototype = {
  19125. /**
  19126. * Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated.
  19127. *
  19128. * @method Phaser.Keyboard#addCallbacks
  19129. * @param {Object} context - The context under which the callbacks are run.
  19130. * @param {function} [onDown=null] - This callback is invoked every time a key is pressed down.
  19131. * @param {function} [onUp=null] - This callback is invoked every time a key is released.
  19132. * @param {function} [onPress=null] - This callback is invoked every time the onkeypress event is raised.
  19133. */
  19134. addCallbacks: function (context, onDown, onUp, onPress) {
  19135. this.callbackContext = context;
  19136. if (typeof onDown !== 'undefined')
  19137. {
  19138. this.onDownCallback = onDown;
  19139. }
  19140. if (typeof onUp !== 'undefined')
  19141. {
  19142. this.onUpCallback = onUp;
  19143. }
  19144. if (typeof onPress !== 'undefined')
  19145. {
  19146. this.onPressCallback = onPress;
  19147. }
  19148. },
  19149. /**
  19150. * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method.
  19151. * The Key object can then be polled, have events attached to it, etc.
  19152. *
  19153. * @method Phaser.Keyboard#addKey
  19154. * @param {number} keycode - The keycode of the key, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
  19155. * @return {Phaser.Key} The Key object which you can store locally and reference directly.
  19156. */
  19157. addKey: function (keycode) {
  19158. if (!this._keys[keycode])
  19159. {
  19160. this._keys[keycode] = new Phaser.Key(this.game, keycode);
  19161. this.addKeyCapture(keycode);
  19162. }
  19163. return this._keys[keycode];
  19164. },
  19165. /**
  19166. * Removes a Key object from the Keyboard manager.
  19167. *
  19168. * @method Phaser.Keyboard#removeKey
  19169. * @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
  19170. */
  19171. removeKey: function (keycode) {
  19172. if (this._keys[keycode])
  19173. {
  19174. this._keys[keycode] = null;
  19175. this.removeKeyCapture(keycode);
  19176. }
  19177. },
  19178. /**
  19179. * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right.
  19180. *
  19181. * @method Phaser.Keyboard#createCursorKeys
  19182. * @return {object} An object containing properties: up, down, left and right. Which can be polled like any other Phaser.Key object.
  19183. */
  19184. createCursorKeys: function () {
  19185. return {
  19186. up: this.addKey(Phaser.Keyboard.UP),
  19187. down: this.addKey(Phaser.Keyboard.DOWN),
  19188. left: this.addKey(Phaser.Keyboard.LEFT),
  19189. right: this.addKey(Phaser.Keyboard.RIGHT)
  19190. };
  19191. },
  19192. /**
  19193. * Starts the Keyboard event listeners running (keydown and keyup). They are attached to the window.
  19194. * This is called automatically by Phaser.Input and should not normally be invoked directly.
  19195. *
  19196. * @method Phaser.Keyboard#start
  19197. */
  19198. start: function () {
  19199. if (this.game.device.cocoonJS)
  19200. {
  19201. return;
  19202. }
  19203. if (this._onKeyDown !== null)
  19204. {
  19205. // Avoid setting multiple listeners
  19206. return;
  19207. }
  19208. var _this = this;
  19209. this._onKeyDown = function (event) {
  19210. return _this.processKeyDown(event);
  19211. };
  19212. this._onKeyUp = function (event) {
  19213. return _this.processKeyUp(event);
  19214. };
  19215. this._onKeyPress = function (event) {
  19216. return _this.processKeyPress(event);
  19217. };
  19218. window.addEventListener('keydown', this._onKeyDown, false);
  19219. window.addEventListener('keyup', this._onKeyUp, false);
  19220. window.addEventListener('keypress', this._onKeyPress, false);
  19221. },
  19222. /**
  19223. * Stops the Keyboard event listeners from running (keydown, keyup and keypress). They are removed from the window.
  19224. *
  19225. * @method Phaser.Keyboard#stop
  19226. */
  19227. stop: function () {
  19228. window.removeEventListener('keydown', this._onKeyDown);
  19229. window.removeEventListener('keyup', this._onKeyUp);
  19230. window.removeEventListener('keypress', this._onKeyPress);
  19231. this._onKeyDown = null;
  19232. this._onKeyUp = null;
  19233. this._onKeyPress = null;
  19234. },
  19235. /**
  19236. * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window.
  19237. * Also clears all key captures and currently created Key objects.
  19238. *
  19239. * @method Phaser.Keyboard#destroy
  19240. */
  19241. destroy: function () {
  19242. this.stop();
  19243. this.clearCaptures();
  19244. this._keys.length = 0;
  19245. this._i = 0;
  19246. },
  19247. /**
  19248. * By default when a key is pressed Phaser will not stop the event from propagating up to the browser.
  19249. * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll.
  19250. * You can use addKeyCapture to consume the keyboard event for specific keys so it doesn't bubble up to the the browser.
  19251. * Pass in either a single keycode or an array/hash of keycodes.
  19252. *
  19253. * @method Phaser.Keyboard#addKeyCapture
  19254. * @param {number|array|object} keycode - Either a single numeric keycode or an array/hash of keycodes: [65, 67, 68].
  19255. */
  19256. addKeyCapture: function (keycode) {
  19257. if (typeof keycode === 'object')
  19258. {
  19259. for (var key in keycode)
  19260. {
  19261. this._capture[keycode[key]] = true;
  19262. }
  19263. }
  19264. else
  19265. {
  19266. this._capture[keycode] = true;
  19267. }
  19268. },
  19269. /**
  19270. * Removes an existing key capture.
  19271. *
  19272. * @method Phaser.Keyboard#removeKeyCapture
  19273. * @param {number} keycode
  19274. */
  19275. removeKeyCapture: function (keycode) {
  19276. delete this._capture[keycode];
  19277. },
  19278. /**
  19279. * Clear all set key captures.
  19280. *
  19281. * @method Phaser.Keyboard#clearCaptures
  19282. */
  19283. clearCaptures: function () {
  19284. this._capture = {};
  19285. },
  19286. /**
  19287. * Updates all currently defined keys.
  19288. *
  19289. * @method Phaser.Keyboard#update
  19290. */
  19291. update: function () {
  19292. this._i = this._keys.length;
  19293. while (this._i--)
  19294. {
  19295. if (this._keys[this._i])
  19296. {
  19297. this._keys[this._i].update();
  19298. }
  19299. }
  19300. },
  19301. /**
  19302. * Process the keydown event.
  19303. *
  19304. * @method Phaser.Keyboard#processKeyDown
  19305. * @param {KeyboardEvent} event
  19306. * @protected
  19307. */
  19308. processKeyDown: function (event) {
  19309. this.event = event;
  19310. if (this.game.input.disabled || this.disabled)
  19311. {
  19312. return;
  19313. }
  19314. // The event is being captured but another hotkey may need it
  19315. if (this._capture[event.keyCode])
  19316. {
  19317. event.preventDefault();
  19318. }
  19319. if (!this._keys[event.keyCode])
  19320. {
  19321. this._keys[event.keyCode] = new Phaser.Key(this.game, event.keyCode);
  19322. }
  19323. this._keys[event.keyCode].processKeyDown(event);
  19324. this._k = event.keyCode;
  19325. if (this.onDownCallback)
  19326. {
  19327. this.onDownCallback.call(this.callbackContext, event);
  19328. }
  19329. },
  19330. /**
  19331. * Process the keypress event.
  19332. *
  19333. * @method Phaser.Keyboard#processKeyPress
  19334. * @param {KeyboardEvent} event
  19335. * @protected
  19336. */
  19337. processKeyPress: function (event) {
  19338. this.pressEvent = event;
  19339. if (this.game.input.disabled || this.disabled)
  19340. {
  19341. return;
  19342. }
  19343. if (this.onPressCallback)
  19344. {
  19345. this.onPressCallback.call(this.callbackContext, String.fromCharCode(event.charCode), event);
  19346. }
  19347. },
  19348. /**
  19349. * Process the keyup event.
  19350. *
  19351. * @method Phaser.Keyboard#processKeyUp
  19352. * @param {KeyboardEvent} event
  19353. * @protected
  19354. */
  19355. processKeyUp: function (event) {
  19356. this.event = event;
  19357. if (this.game.input.disabled || this.disabled)
  19358. {
  19359. return;
  19360. }
  19361. if (this._capture[event.keyCode])
  19362. {
  19363. event.preventDefault();
  19364. }
  19365. if (!this._keys[event.keyCode])
  19366. {
  19367. this._keys[event.keyCode] = new Phaser.Key(this.game, event.keyCode);
  19368. }
  19369. this._keys[event.keyCode].processKeyUp(event);
  19370. if (this.onUpCallback)
  19371. {
  19372. this.onUpCallback.call(this.callbackContext, event);
  19373. }
  19374. },
  19375. /**
  19376. * Resets all Keys.
  19377. *
  19378. * @method Phaser.Keyboard#reset
  19379. * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to the Keys. A hard reset will.
  19380. */
  19381. reset: function (hard) {
  19382. if (typeof hard === 'undefined') { hard = true; }
  19383. this.event = null;
  19384. var i = this._keys.length;
  19385. while (i--)
  19386. {
  19387. if (this._keys[i])
  19388. {
  19389. this._keys[i].reset(hard);
  19390. }
  19391. }
  19392. },
  19393. /**
  19394. * Returns the "just pressed" state of the key. Just pressed is considered true if the key was pressed down within the duration given (default 250ms)
  19395. *
  19396. * @method Phaser.Keyboard#justPressed
  19397. * @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
  19398. * @param {number} [duration=50] - The duration below which the key is considered as being just pressed.
  19399. * @return {boolean} True if the key is just pressed otherwise false.
  19400. */
  19401. justPressed: function (keycode, duration) {
  19402. if (typeof duration === 'undefined') { duration = 50; }
  19403. if (this._keys[keycode])
  19404. {
  19405. return this._keys[keycode].justPressed(duration);
  19406. }
  19407. else
  19408. {
  19409. return false;
  19410. }
  19411. },
  19412. /**
  19413. * Returns the "just released" state of the Key. Just released is considered as being true if the key was released within the duration given (default 250ms)
  19414. *
  19415. * @method Phaser.Keyboard#justReleased
  19416. * @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
  19417. * @param {number} [duration=50] - The duration below which the key is considered as being just released.
  19418. * @return {boolean} True if the key is just released otherwise false.
  19419. */
  19420. justReleased: function (keycode, duration) {
  19421. if (typeof duration === 'undefined') { duration = 50; }
  19422. if (this._keys[keycode])
  19423. {
  19424. return this._keys[keycode].justReleased(duration);
  19425. }
  19426. else
  19427. {
  19428. return false;
  19429. }
  19430. },
  19431. /**
  19432. * Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser.
  19433. *
  19434. * @method Phaser.Keyboard#isDown
  19435. * @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
  19436. * @return {boolean} True if the key is currently down.
  19437. */
  19438. isDown: function (keycode) {
  19439. if (this._keys[keycode])
  19440. {
  19441. return this._keys[keycode].isDown;
  19442. }
  19443. return false;
  19444. }
  19445. };
  19446. /**
  19447. * Returns the string value of the most recently pressed key.
  19448. * @name Phaser.Keyboard#lastChar
  19449. * @property {string} lastChar - The string value of the most recently pressed key.
  19450. * @readonly
  19451. */
  19452. Object.defineProperty(Phaser.Keyboard.prototype, "lastChar", {
  19453. get: function () {
  19454. if (this.event.charCode === 32)
  19455. {
  19456. return '';
  19457. }
  19458. else
  19459. {
  19460. return String.fromCharCode(this.pressEvent.charCode);
  19461. }
  19462. }
  19463. });
  19464. /**
  19465. * Returns the most recently pressed Key. This is a Phaser.Key object and it changes every time a key is pressed.
  19466. * @name Phaser.Keyboard#lastKey
  19467. * @property {Phaser.Key} lastKey - The most recently pressed Key.
  19468. * @readonly
  19469. */
  19470. Object.defineProperty(Phaser.Keyboard.prototype, "lastKey", {
  19471. get: function () {
  19472. return this._keys[this._k];
  19473. }
  19474. });
  19475. Phaser.Keyboard.prototype.constructor = Phaser.Keyboard;
  19476. Phaser.Keyboard.A = "A".charCodeAt(0);
  19477. Phaser.Keyboard.B = "B".charCodeAt(0);
  19478. Phaser.Keyboard.C = "C".charCodeAt(0);
  19479. Phaser.Keyboard.D = "D".charCodeAt(0);
  19480. Phaser.Keyboard.E = "E".charCodeAt(0);
  19481. Phaser.Keyboard.F = "F".charCodeAt(0);
  19482. Phaser.Keyboard.G = "G".charCodeAt(0);
  19483. Phaser.Keyboard.H = "H".charCodeAt(0);
  19484. Phaser.Keyboard.I = "I".charCodeAt(0);
  19485. Phaser.Keyboard.J = "J".charCodeAt(0);
  19486. Phaser.Keyboard.K = "K".charCodeAt(0);
  19487. Phaser.Keyboard.L = "L".charCodeAt(0);
  19488. Phaser.Keyboard.M = "M".charCodeAt(0);
  19489. Phaser.Keyboard.N = "N".charCodeAt(0);
  19490. Phaser.Keyboard.O = "O".charCodeAt(0);
  19491. Phaser.Keyboard.P = "P".charCodeAt(0);
  19492. Phaser.Keyboard.Q = "Q".charCodeAt(0);
  19493. Phaser.Keyboard.R = "R".charCodeAt(0);
  19494. Phaser.Keyboard.S = "S".charCodeAt(0);
  19495. Phaser.Keyboard.T = "T".charCodeAt(0);
  19496. Phaser.Keyboard.U = "U".charCodeAt(0);
  19497. Phaser.Keyboard.V = "V".charCodeAt(0);
  19498. Phaser.Keyboard.W = "W".charCodeAt(0);
  19499. Phaser.Keyboard.X = "X".charCodeAt(0);
  19500. Phaser.Keyboard.Y = "Y".charCodeAt(0);
  19501. Phaser.Keyboard.Z = "Z".charCodeAt(0);
  19502. Phaser.Keyboard.ZERO = "0".charCodeAt(0);
  19503. Phaser.Keyboard.ONE = "1".charCodeAt(0);
  19504. Phaser.Keyboard.TWO = "2".charCodeAt(0);
  19505. Phaser.Keyboard.THREE = "3".charCodeAt(0);
  19506. Phaser.Keyboard.FOUR = "4".charCodeAt(0);
  19507. Phaser.Keyboard.FIVE = "5".charCodeAt(0);
  19508. Phaser.Keyboard.SIX = "6".charCodeAt(0);
  19509. Phaser.Keyboard.SEVEN = "7".charCodeAt(0);
  19510. Phaser.Keyboard.EIGHT = "8".charCodeAt(0);
  19511. Phaser.Keyboard.NINE = "9".charCodeAt(0);
  19512. Phaser.Keyboard.NUMPAD_0 = 96;
  19513. Phaser.Keyboard.NUMPAD_1 = 97;
  19514. Phaser.Keyboard.NUMPAD_2 = 98;
  19515. Phaser.Keyboard.NUMPAD_3 = 99;
  19516. Phaser.Keyboard.NUMPAD_4 = 100;
  19517. Phaser.Keyboard.NUMPAD_5 = 101;
  19518. Phaser.Keyboard.NUMPAD_6 = 102;
  19519. Phaser.Keyboard.NUMPAD_7 = 103;
  19520. Phaser.Keyboard.NUMPAD_8 = 104;
  19521. Phaser.Keyboard.NUMPAD_9 = 105;
  19522. Phaser.Keyboard.NUMPAD_MULTIPLY = 106;
  19523. Phaser.Keyboard.NUMPAD_ADD = 107;
  19524. Phaser.Keyboard.NUMPAD_ENTER = 108;
  19525. Phaser.Keyboard.NUMPAD_SUBTRACT = 109;
  19526. Phaser.Keyboard.NUMPAD_DECIMAL = 110;
  19527. Phaser.Keyboard.NUMPAD_DIVIDE = 111;
  19528. Phaser.Keyboard.F1 = 112;
  19529. Phaser.Keyboard.F2 = 113;
  19530. Phaser.Keyboard.F3 = 114;
  19531. Phaser.Keyboard.F4 = 115;
  19532. Phaser.Keyboard.F5 = 116;
  19533. Phaser.Keyboard.F6 = 117;
  19534. Phaser.Keyboard.F7 = 118;
  19535. Phaser.Keyboard.F8 = 119;
  19536. Phaser.Keyboard.F9 = 120;
  19537. Phaser.Keyboard.F10 = 121;
  19538. Phaser.Keyboard.F11 = 122;
  19539. Phaser.Keyboard.F12 = 123;
  19540. Phaser.Keyboard.F13 = 124;
  19541. Phaser.Keyboard.F14 = 125;
  19542. Phaser.Keyboard.F15 = 126;
  19543. Phaser.Keyboard.COLON = 186;
  19544. Phaser.Keyboard.EQUALS = 187;
  19545. Phaser.Keyboard.UNDERSCORE = 189;
  19546. Phaser.Keyboard.QUESTION_MARK = 191;
  19547. Phaser.Keyboard.TILDE = 192;
  19548. Phaser.Keyboard.OPEN_BRACKET = 219;
  19549. Phaser.Keyboard.BACKWARD_SLASH = 220;
  19550. Phaser.Keyboard.CLOSED_BRACKET = 221;
  19551. Phaser.Keyboard.QUOTES = 222;
  19552. Phaser.Keyboard.BACKSPACE = 8;
  19553. Phaser.Keyboard.TAB = 9;
  19554. Phaser.Keyboard.CLEAR = 12;
  19555. Phaser.Keyboard.ENTER = 13;
  19556. Phaser.Keyboard.SHIFT = 16;
  19557. Phaser.Keyboard.CONTROL = 17;
  19558. Phaser.Keyboard.ALT = 18;
  19559. Phaser.Keyboard.CAPS_LOCK = 20;
  19560. Phaser.Keyboard.ESC = 27;
  19561. Phaser.Keyboard.SPACEBAR = 32;
  19562. Phaser.Keyboard.PAGE_UP = 33;
  19563. Phaser.Keyboard.PAGE_DOWN = 34;
  19564. Phaser.Keyboard.END = 35;
  19565. Phaser.Keyboard.HOME = 36;
  19566. Phaser.Keyboard.LEFT = 37;
  19567. Phaser.Keyboard.UP = 38;
  19568. Phaser.Keyboard.RIGHT = 39;
  19569. Phaser.Keyboard.DOWN = 40;
  19570. Phaser.Keyboard.INSERT = 45;
  19571. Phaser.Keyboard.DELETE = 46;
  19572. Phaser.Keyboard.HELP = 47;
  19573. Phaser.Keyboard.NUM_LOCK = 144;
  19574. /**
  19575. * @author Richard Davey <rich@photonstorm.com>
  19576. * @copyright 2014 Photon Storm Ltd.
  19577. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  19578. */
  19579. /**
  19580. * Phaser.Mouse is responsible for handling all aspects of mouse interaction with the browser. It captures and processes mouse events.
  19581. *
  19582. * @class Phaser.Mouse
  19583. * @constructor
  19584. * @param {Phaser.Game} game - A reference to the currently running game.
  19585. */
  19586. Phaser.Mouse = function (game) {
  19587. /**
  19588. * @property {Phaser.Game} game - A reference to the currently running game.
  19589. */
  19590. this.game = game;
  19591. /**
  19592. * @property {Object} callbackContext - The context under which callbacks are called.
  19593. */
  19594. this.callbackContext = this.game;
  19595. /**
  19596. * @property {function} mouseDownCallback - A callback that can be fired when the mouse is pressed down.
  19597. */
  19598. this.mouseDownCallback = null;
  19599. /**
  19600. * @property {function} mouseMoveCallback - A callback that can be fired when the mouse is moved while pressed down.
  19601. */
  19602. this.mouseMoveCallback = null;
  19603. /**
  19604. * @property {function} mouseUpCallback - A callback that can be fired when the mouse is released from a pressed down state.
  19605. */
  19606. this.mouseUpCallback = null;
  19607. /**
  19608. * @property {function} mouseOutCallback - A callback that can be fired when the mouse is no longer over the game canvas.
  19609. */
  19610. this.mouseOutCallback = null;
  19611. /**
  19612. * @property {function} mouseOverCallback - A callback that can be fired when the mouse enters the game canvas (usually after a mouseout).
  19613. */
  19614. this.mouseOverCallback = null;
  19615. /**
  19616. * @property {function} mouseWheelCallback - A callback that can be fired when the mousewheel is used.
  19617. */
  19618. this.mouseWheelCallback = null;
  19619. /**
  19620. * @property {boolean} capture - If true the DOM mouse events will have event.preventDefault applied to them, if false they will propogate fully.
  19621. */
  19622. this.capture = false;
  19623. /**
  19624. * @property {number} button- The type of click, either: Phaser.Mouse.NO_BUTTON, Phaser.Mouse.LEFT_BUTTON, Phaser.Mouse.MIDDLE_BUTTON or Phaser.Mouse.RIGHT_BUTTON.
  19625. * @default
  19626. */
  19627. this.button = -1;
  19628. /**
  19629. * @property {number} wheelDelta - The direction of the mousewheel usage 1 for up -1 for down
  19630. */
  19631. this.wheelDelta = 0;
  19632. /**
  19633. * @property {boolean} disabled - You can disable all Input by setting disabled = true. While set all new input related events will be ignored.
  19634. * @default
  19635. */
  19636. this.disabled = false;
  19637. /**
  19638. * @property {boolean} locked - If the mouse has been Pointer Locked successfully this will be set to true.
  19639. * @default
  19640. */
  19641. this.locked = false;
  19642. /**
  19643. * @property {boolean} stopOnGameOut - If true Pointer.stop will be called if the mouse leaves the game canvas.
  19644. * @default
  19645. */
  19646. this.stopOnGameOut = false;
  19647. /**
  19648. * @property {Phaser.Signal} pointerLock - This event is dispatched when the browser enters or leaves pointer lock state.
  19649. * @default
  19650. */
  19651. this.pointerLock = new Phaser.Signal();
  19652. /**
  19653. * @property {MouseEvent} event - The browser mouse DOM event. Will be set to null if no mouse event has ever been received.
  19654. * @default
  19655. */
  19656. this.event = null;
  19657. /**
  19658. * @property {function} _onMouseDown - Internal event handler reference.
  19659. * @private
  19660. */
  19661. this._onMouseDown = null;
  19662. /**
  19663. * @property {function} _onMouseMove - Internal event handler reference.
  19664. * @private
  19665. */
  19666. this._onMouseMove = null;
  19667. /**
  19668. * @property {function} _onMouseUp - Internal event handler reference.
  19669. * @private
  19670. */
  19671. this._onMouseUp = null;
  19672. /**
  19673. * @property {function} _onMouseOut - Internal event handler reference.
  19674. * @private
  19675. */
  19676. this._onMouseOut = null;
  19677. /**
  19678. * @property {function} _onMouseOver - Internal event handler reference.
  19679. * @private
  19680. */
  19681. this._onMouseOver = null;
  19682. /**
  19683. * @property {function} _onMouseWheel - Internal event handler reference.
  19684. * @private
  19685. */
  19686. this._onMouseWheel = null;
  19687. };
  19688. /**
  19689. * @constant
  19690. * @type {number}
  19691. */
  19692. Phaser.Mouse.NO_BUTTON = -1;
  19693. /**
  19694. * @constant
  19695. * @type {number}
  19696. */
  19697. Phaser.Mouse.LEFT_BUTTON = 0;
  19698. /**
  19699. * @constant
  19700. * @type {number}
  19701. */
  19702. Phaser.Mouse.MIDDLE_BUTTON = 1;
  19703. /**
  19704. * @constant
  19705. * @type {number}
  19706. */
  19707. Phaser.Mouse.RIGHT_BUTTON = 2;
  19708. /**
  19709. * @constant
  19710. * @type {number}
  19711. */
  19712. Phaser.Mouse.WHEEL_UP = 1;
  19713. /**
  19714. * @constant
  19715. * @type {number}
  19716. */
  19717. Phaser.Mouse.WHEEL_DOWN = -1;
  19718. Phaser.Mouse.prototype = {
  19719. /**
  19720. * Starts the event listeners running.
  19721. * @method Phaser.Mouse#start
  19722. */
  19723. start: function () {
  19724. if (this.game.device.android && this.game.device.chrome === false)
  19725. {
  19726. // Android stock browser fires mouse events even if you preventDefault on the touchStart, so ...
  19727. return;
  19728. }
  19729. if (this._onMouseDown !== null)
  19730. {
  19731. // Avoid setting multiple listeners
  19732. return;
  19733. }
  19734. var _this = this;
  19735. this._onMouseDown = function (event) {
  19736. return _this.onMouseDown(event);
  19737. };
  19738. this._onMouseMove = function (event) {
  19739. return _this.onMouseMove(event);
  19740. };
  19741. this._onMouseUp = function (event) {
  19742. return _this.onMouseUp(event);
  19743. };
  19744. this._onMouseOut = function (event) {
  19745. return _this.onMouseOut(event);
  19746. };
  19747. this._onMouseOver = function (event) {
  19748. return _this.onMouseOver(event);
  19749. };
  19750. this._onMouseWheel = function (event) {
  19751. return _this.onMouseWheel(event);
  19752. };
  19753. this.game.canvas.addEventListener('mousedown', this._onMouseDown, true);
  19754. this.game.canvas.addEventListener('mousemove', this._onMouseMove, true);
  19755. this.game.canvas.addEventListener('mouseup', this._onMouseUp, true);
  19756. this.game.canvas.addEventListener('mousewheel', this._onMouseWheel, true);
  19757. this.game.canvas.addEventListener('DOMMouseScroll', this._onMouseWheel, true);
  19758. if (!this.game.device.cocoonJS)
  19759. {
  19760. this.game.canvas.addEventListener('mouseover', this._onMouseOver, true);
  19761. this.game.canvas.addEventListener('mouseout', this._onMouseOut, true);
  19762. }
  19763. },
  19764. /**
  19765. * The internal method that handles the mouse down event from the browser.
  19766. * @method Phaser.Mouse#onMouseDown
  19767. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  19768. */
  19769. onMouseDown: function (event) {
  19770. this.event = event;
  19771. if (this.capture)
  19772. {
  19773. event.preventDefault();
  19774. }
  19775. this.button = event.button;
  19776. if (this.mouseDownCallback)
  19777. {
  19778. this.mouseDownCallback.call(this.callbackContext, event);
  19779. }
  19780. if (this.game.input.disabled || this.disabled)
  19781. {
  19782. return;
  19783. }
  19784. event['identifier'] = 0;
  19785. this.game.input.mousePointer.start(event);
  19786. },
  19787. /**
  19788. * The internal method that handles the mouse move event from the browser.
  19789. * @method Phaser.Mouse#onMouseMove
  19790. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  19791. */
  19792. onMouseMove: function (event) {
  19793. this.event = event;
  19794. if (this.capture)
  19795. {
  19796. event.preventDefault();
  19797. }
  19798. if (this.mouseMoveCallback)
  19799. {
  19800. this.mouseMoveCallback.call(this.callbackContext, event);
  19801. }
  19802. if (this.game.input.disabled || this.disabled)
  19803. {
  19804. return;
  19805. }
  19806. event['identifier'] = 0;
  19807. this.game.input.mousePointer.move(event);
  19808. },
  19809. /**
  19810. * The internal method that handles the mouse up event from the browser.
  19811. * @method Phaser.Mouse#onMouseUp
  19812. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  19813. */
  19814. onMouseUp: function (event) {
  19815. this.event = event;
  19816. if (this.capture)
  19817. {
  19818. event.preventDefault();
  19819. }
  19820. this.button = Phaser.Mouse.NO_BUTTON;
  19821. if (this.mouseUpCallback)
  19822. {
  19823. this.mouseUpCallback.call(this.callbackContext, event);
  19824. }
  19825. if (this.game.input.disabled || this.disabled)
  19826. {
  19827. return;
  19828. }
  19829. event['identifier'] = 0;
  19830. this.game.input.mousePointer.stop(event);
  19831. },
  19832. /**
  19833. * The internal method that handles the mouse out event from the browser.
  19834. *
  19835. * @method Phaser.Mouse#onMouseOut
  19836. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  19837. */
  19838. onMouseOut: function (event) {
  19839. this.event = event;
  19840. if (this.capture)
  19841. {
  19842. event.preventDefault();
  19843. }
  19844. if (this.mouseOutCallback)
  19845. {
  19846. this.mouseOutCallback.call(this.callbackContext, event);
  19847. }
  19848. if (this.game.input.disabled || this.disabled)
  19849. {
  19850. return;
  19851. }
  19852. this.game.input.mousePointer.withinGame = false;
  19853. if (this.stopOnGameOut)
  19854. {
  19855. event['identifier'] = 0;
  19856. this.game.input.mousePointer.stop(event);
  19857. }
  19858. },
  19859. /**
  19860. * The internal method that handles the mouse wheel event from the browser.
  19861. *
  19862. * @method Phaser.Mouse#onMouseWheel
  19863. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  19864. */
  19865. onMouseWheel: function (event) {
  19866. this.event = event;
  19867. if (this.capture)
  19868. {
  19869. event.preventDefault();
  19870. }
  19871. // reverse detail for firefox
  19872. this.wheelDelta = Math.max(-1, Math.min(1, (event.wheelDelta || -event.detail)));
  19873. if (this.mouseWheelCallback)
  19874. {
  19875. this.mouseWheelCallback.call(this.callbackContext, event);
  19876. }
  19877. },
  19878. /**
  19879. * The internal method that handles the mouse over event from the browser.
  19880. *
  19881. * @method Phaser.Mouse#onMouseOver
  19882. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  19883. */
  19884. onMouseOver: function (event) {
  19885. this.event = event;
  19886. if (this.capture)
  19887. {
  19888. event.preventDefault();
  19889. }
  19890. if (this.mouseOverCallback)
  19891. {
  19892. this.mouseOverCallback.call(this.callbackContext, event);
  19893. }
  19894. if (this.game.input.disabled || this.disabled)
  19895. {
  19896. return;
  19897. }
  19898. this.game.input.mousePointer.withinGame = true;
  19899. },
  19900. /**
  19901. * If the browser supports it you can request that the pointer be locked to the browser window.
  19902. * This is classically known as 'FPS controls', where the pointer can't leave the browser until the user presses an exit key.
  19903. * If the browser successfully enters a locked state the event Phaser.Mouse.pointerLock will be dispatched and the first parameter will be 'true'.
  19904. * @method Phaser.Mouse#requestPointerLock
  19905. */
  19906. requestPointerLock: function () {
  19907. if (this.game.device.pointerLock)
  19908. {
  19909. var element = this.game.canvas;
  19910. element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;
  19911. element.requestPointerLock();
  19912. var _this = this;
  19913. this._pointerLockChange = function (event) {
  19914. return _this.pointerLockChange(event);
  19915. };
  19916. document.addEventListener('pointerlockchange', this._pointerLockChange, true);
  19917. document.addEventListener('mozpointerlockchange', this._pointerLockChange, true);
  19918. document.addEventListener('webkitpointerlockchange', this._pointerLockChange, true);
  19919. }
  19920. },
  19921. /**
  19922. * Internal pointerLockChange handler.
  19923. * @method Phaser.Mouse#pointerLockChange
  19924. * @param {pointerlockchange} event - The native event from the browser. This gets stored in Mouse.event.
  19925. */
  19926. pointerLockChange: function (event) {
  19927. var element = this.game.canvas;
  19928. if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element)
  19929. {
  19930. // Pointer was successfully locked
  19931. this.locked = true;
  19932. this.pointerLock.dispatch(true, event);
  19933. }
  19934. else
  19935. {
  19936. // Pointer was unlocked
  19937. this.locked = false;
  19938. this.pointerLock.dispatch(false, event);
  19939. }
  19940. },
  19941. /**
  19942. * Internal release pointer lock handler.
  19943. * @method Phaser.Mouse#releasePointerLock
  19944. */
  19945. releasePointerLock: function () {
  19946. document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock;
  19947. document.exitPointerLock();
  19948. document.removeEventListener('pointerlockchange', this._pointerLockChange, true);
  19949. document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true);
  19950. document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true);
  19951. },
  19952. /**
  19953. * Stop the event listeners.
  19954. * @method Phaser.Mouse#stop
  19955. */
  19956. stop: function () {
  19957. this.game.canvas.removeEventListener('mousedown', this._onMouseDown, true);
  19958. this.game.canvas.removeEventListener('mousemove', this._onMouseMove, true);
  19959. this.game.canvas.removeEventListener('mouseup', this._onMouseUp, true);
  19960. this.game.canvas.removeEventListener('mouseover', this._onMouseOver, true);
  19961. this.game.canvas.removeEventListener('mouseout', this._onMouseOut, true);
  19962. this.game.canvas.removeEventListener('mousewheel', this._onMouseWheel, true);
  19963. this.game.canvas.removeEventListener('DOMMouseScroll', this._onMouseWheel, true);
  19964. }
  19965. };
  19966. Phaser.Mouse.prototype.constructor = Phaser.Mouse;
  19967. /**
  19968. * @author Richard Davey <rich@photonstorm.com>
  19969. * @copyright 2014 Photon Storm Ltd.
  19970. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  19971. */
  19972. /**
  19973. * Phaser - MSPointer constructor.
  19974. *
  19975. * @class Phaser.MSPointer
  19976. * @classdesc The MSPointer class handles touch interactions with the game and the resulting Pointer objects.
  19977. * It will work only in Internet Explorer 10 and Windows Store or Windows Phone 8 apps using JavaScript.
  19978. * http://msdn.microsoft.com/en-us/library/ie/hh673557(v=vs.85).aspx
  19979. * @constructor
  19980. * @param {Phaser.Game} game - A reference to the currently running game.
  19981. */
  19982. Phaser.MSPointer = function (game) {
  19983. /**
  19984. * @property {Phaser.Game} game - A reference to the currently running game.
  19985. */
  19986. this.game = game;
  19987. /**
  19988. * @property {Object} callbackContext - The context under which callbacks are called (defaults to game).
  19989. */
  19990. this.callbackContext = this.game;
  19991. /**
  19992. * You can disable all Input by setting disabled = true. While set all new input related events will be ignored.
  19993. * @property {boolean} disabled
  19994. */
  19995. this.disabled = false;
  19996. /**
  19997. * @property {function} _onMSPointerDown - Internal function to handle MSPointer events.
  19998. * @private
  19999. */
  20000. this._onMSPointerDown = null;
  20001. /**
  20002. * @property {function} _onMSPointerMove - Internal function to handle MSPointer events.
  20003. * @private
  20004. */
  20005. this._onMSPointerMove = null;
  20006. /**
  20007. * @property {function} _onMSPointerUp - Internal function to handle MSPointer events.
  20008. * @private
  20009. */
  20010. this._onMSPointerUp = null;
  20011. };
  20012. Phaser.MSPointer.prototype = {
  20013. /**
  20014. * Starts the event listeners running.
  20015. * @method Phaser.MSPointer#start
  20016. */
  20017. start: function () {
  20018. if (this._onMSPointerDown !== null)
  20019. {
  20020. // Avoid setting multiple listeners
  20021. return;
  20022. }
  20023. var _this = this;
  20024. if (this.game.device.mspointer === true)
  20025. {
  20026. this._onMSPointerDown = function (event) {
  20027. return _this.onPointerDown(event);
  20028. };
  20029. this._onMSPointerMove = function (event) {
  20030. return _this.onPointerMove(event);
  20031. };
  20032. this._onMSPointerUp = function (event) {
  20033. return _this.onPointerUp(event);
  20034. };
  20035. this.game.renderer.view.addEventListener('MSPointerDown', this._onMSPointerDown, false);
  20036. this.game.renderer.view.addEventListener('MSPointerMove', this._onMSPointerMove, false);
  20037. this.game.renderer.view.addEventListener('MSPointerUp', this._onMSPointerUp, false);
  20038. // IE11+ uses non-prefix events
  20039. this.game.renderer.view.addEventListener('pointerDown', this._onMSPointerDown, false);
  20040. this.game.renderer.view.addEventListener('pointerMove', this._onMSPointerMove, false);
  20041. this.game.renderer.view.addEventListener('pointerUp', this._onMSPointerUp, false);
  20042. this.game.renderer.view.style['-ms-content-zooming'] = 'none';
  20043. this.game.renderer.view.style['-ms-touch-action'] = 'none';
  20044. }
  20045. },
  20046. /**
  20047. * The function that handles the PointerDown event.
  20048. * @method Phaser.MSPointer#onPointerDown
  20049. * @param {PointerEvent} event
  20050. */
  20051. onPointerDown: function (event) {
  20052. if (this.game.input.disabled || this.disabled)
  20053. {
  20054. return;
  20055. }
  20056. event.preventDefault();
  20057. event.identifier = event.pointerId;
  20058. this.game.input.startPointer(event);
  20059. },
  20060. /**
  20061. * The function that handles the PointerMove event.
  20062. * @method Phaser.MSPointer#onPointerMove
  20063. * @param {PointerEvent } event
  20064. */
  20065. onPointerMove: function (event) {
  20066. if (this.game.input.disabled || this.disabled)
  20067. {
  20068. return;
  20069. }
  20070. event.preventDefault();
  20071. event.identifier = event.pointerId;
  20072. this.game.input.updatePointer(event);
  20073. },
  20074. /**
  20075. * The function that handles the PointerUp event.
  20076. * @method Phaser.MSPointer#onPointerUp
  20077. * @param {PointerEvent} event
  20078. */
  20079. onPointerUp: function (event) {
  20080. if (this.game.input.disabled || this.disabled)
  20081. {
  20082. return;
  20083. }
  20084. event.preventDefault();
  20085. event.identifier = event.pointerId;
  20086. this.game.input.stopPointer(event);
  20087. },
  20088. /**
  20089. * Stop the event listeners.
  20090. * @method Phaser.MSPointer#stop
  20091. */
  20092. stop: function () {
  20093. this.game.canvas.removeEventListener('MSPointerDown', this._onMSPointerDown);
  20094. this.game.canvas.removeEventListener('MSPointerMove', this._onMSPointerMove);
  20095. this.game.canvas.removeEventListener('MSPointerUp', this._onMSPointerUp);
  20096. this.game.canvas.removeEventListener('pointerDown', this._onMSPointerDown);
  20097. this.game.canvas.removeEventListener('pointerMove', this._onMSPointerMove);
  20098. this.game.canvas.removeEventListener('pointerUp', this._onMSPointerUp);
  20099. }
  20100. };
  20101. Phaser.MSPointer.prototype.constructor = Phaser.MSPointer;
  20102. /**
  20103. * @author Richard Davey <rich@photonstorm.com>
  20104. * @copyright 2014 Photon Storm Ltd.
  20105. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  20106. */
  20107. /**
  20108. * Phaser - Pointer constructor.
  20109. *
  20110. * @class Phaser.Pointer
  20111. * @classdesc A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen.
  20112. * @constructor
  20113. * @param {Phaser.Game} game - A reference to the currently running game.
  20114. * @param {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers.
  20115. */
  20116. Phaser.Pointer = function (game, id) {
  20117. /**
  20118. * @property {Phaser.Game} game - A reference to the currently running game.
  20119. */
  20120. this.game = game;
  20121. /**
  20122. * @property {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers.
  20123. */
  20124. this.id = id;
  20125. /**
  20126. * @property {number} type - The const type of this object.
  20127. * @readonly
  20128. */
  20129. this.type = Phaser.POINTER;
  20130. /**
  20131. * @property {boolean} exists - A Pointer object that exists is allowed to be checked for physics collisions and overlaps.
  20132. * @default
  20133. */
  20134. this.exists = true;
  20135. /**
  20136. * @property {number} identifier - The identifier property of the Pointer as set by the DOM event when this Pointer is started.
  20137. * @default
  20138. */
  20139. this.identifier = 0;
  20140. /**
  20141. * @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.
  20142. * @default
  20143. */
  20144. this.pointerId = null;
  20145. /**
  20146. * @property {any} target - The target property of the Pointer as set by the DOM event when this Pointer is started.
  20147. * @default
  20148. */
  20149. this.target = null;
  20150. /**
  20151. * @property {any} button - The button property of the Pointer as set by the DOM event when this Pointer is started.
  20152. * @default
  20153. */
  20154. this.button = null;
  20155. /**
  20156. * @property {boolean} _holdSent - Local private variable to store the status of dispatching a hold event.
  20157. * @private
  20158. * @default
  20159. */
  20160. this._holdSent = false;
  20161. /**
  20162. * @property {array} _history - Local private variable storing the short-term history of pointer movements.
  20163. * @private
  20164. */
  20165. this._history = [];
  20166. /**
  20167. * @property {number} _nextDrop - Local private variable storing the time at which the next history drop should occur.
  20168. * @private
  20169. */
  20170. this._nextDrop = 0;
  20171. /**
  20172. * @property {boolean} _stateReset - Monitor events outside of a state reset loop.
  20173. * @private
  20174. */
  20175. this._stateReset = false;
  20176. /**
  20177. * @property {boolean} withinGame - true if the Pointer is over the game canvas, otherwise false.
  20178. */
  20179. this.withinGame = false;
  20180. /**
  20181. * @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).
  20182. */
  20183. this.clientX = -1;
  20184. /**
  20185. * @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).
  20186. */
  20187. this.clientY = -1;
  20188. /**
  20189. * @property {number} pageX - The horizontal coordinate of the Pointer relative to whole document.
  20190. */
  20191. this.pageX = -1;
  20192. /**
  20193. * @property {number} pageY - The vertical coordinate of the Pointer relative to whole document.
  20194. */
  20195. this.pageY = -1;
  20196. /**
  20197. * @property {number} screenX - The horizontal coordinate of the Pointer relative to the screen.
  20198. */
  20199. this.screenX = -1;
  20200. /**
  20201. * @property {number} screenY - The vertical coordinate of the Pointer relative to the screen.
  20202. */
  20203. this.screenY = -1;
  20204. /**
  20205. * @property {number} rawMovementX - The horizontal raw relative movement of the Pointer in pixels since last event.
  20206. * @default
  20207. */
  20208. this.rawMovementX = 0;
  20209. /**
  20210. * @property {number} rawMovementY - The vertical raw relative movement of the Pointer in pixels since last event.
  20211. * @default
  20212. */
  20213. this.rawMovementY = 0;
  20214. /**
  20215. * @property {number} movementX - The horizontal processed relative movement of the Pointer in pixels since last event.
  20216. * @default
  20217. */
  20218. this.movementX = 0;
  20219. /**
  20220. * @property {number} movementY - The vertical processed relative movement of the Pointer in pixels since last event.
  20221. * @default
  20222. */
  20223. this.movementY = 0;
  20224. /**
  20225. * @property {number} x - The horizontal coordinate of the Pointer. This value is automatically scaled based on the game scale.
  20226. * @default
  20227. */
  20228. this.x = -1;
  20229. /**
  20230. * @property {number} y - The vertical coordinate of the Pointer. This value is automatically scaled based on the game scale.
  20231. * @default
  20232. */
  20233. this.y = -1;
  20234. /**
  20235. * @property {boolean} isMouse - If the Pointer is a mouse this is true, otherwise false.
  20236. * @default
  20237. */
  20238. this.isMouse = false;
  20239. /**
  20240. * @property {boolean} isDown - If the Pointer is touching the touchscreen, or the mouse button is held down, isDown is set to true.
  20241. * @default
  20242. */
  20243. this.isDown = false;
  20244. /**
  20245. * @property {boolean} isUp - If the Pointer is not touching the touchscreen, or the mouse button is up, isUp is set to true.
  20246. * @default
  20247. */
  20248. this.isUp = true;
  20249. /**
  20250. * @property {number} timeDown - A timestamp representing when the Pointer first touched the touchscreen.
  20251. * @default
  20252. */
  20253. this.timeDown = 0;
  20254. /**
  20255. * @property {number} timeUp - A timestamp representing when the Pointer left the touchscreen.
  20256. * @default
  20257. */
  20258. this.timeUp = 0;
  20259. /**
  20260. * @property {number} previousTapTime - A timestamp representing when the Pointer was last tapped or clicked.
  20261. * @default
  20262. */
  20263. this.previousTapTime = 0;
  20264. /**
  20265. * @property {number} totalTouches - The total number of times this Pointer has been touched to the touchscreen.
  20266. * @default
  20267. */
  20268. this.totalTouches = 0;
  20269. /**
  20270. * @property {number} msSinceLastClick - The number of milliseconds since the last click or touch event.
  20271. * @default
  20272. */
  20273. this.msSinceLastClick = Number.MAX_VALUE;
  20274. /**
  20275. * @property {any} targetObject - The Game Object this Pointer is currently over / touching / dragging.
  20276. * @default
  20277. */
  20278. this.targetObject = null;
  20279. /**
  20280. * @property {boolean} active - An active pointer is one that is currently pressed down on the display. A Mouse is always active.
  20281. * @default
  20282. */
  20283. this.active = false;
  20284. /**
  20285. * @property {Phaser.Point} position - A Phaser.Point object containing the current x/y values of the pointer on the display.
  20286. */
  20287. this.position = new Phaser.Point();
  20288. /**
  20289. * @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.
  20290. */
  20291. this.positionDown = new Phaser.Point();
  20292. /**
  20293. * @property {Phaser.Point} positionUp - A Phaser.Point object containing the x/y values of the pointer when it was last released.
  20294. */
  20295. this.positionUp = new Phaser.Point();
  20296. /**
  20297. * A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection.
  20298. * The Circle size is 44px (Apples recommended "finger tip" size).
  20299. * @property {Phaser.Circle} circle
  20300. */
  20301. this.circle = new Phaser.Circle(0, 0, 44);
  20302. if (id === 0)
  20303. {
  20304. this.isMouse = true;
  20305. }
  20306. };
  20307. Phaser.Pointer.prototype = {
  20308. /**
  20309. * Called when the Pointer is pressed onto the touchscreen.
  20310. * @method Phaser.Pointer#start
  20311. * @param {any} event - The DOM event from the browser.
  20312. */
  20313. start: function (event) {
  20314. if (event['pointerId'])
  20315. {
  20316. this.pointerId = event.pointerId;
  20317. }
  20318. this.identifier = event.identifier;
  20319. this.target = event.target;
  20320. if (typeof event.button !== 'undefined')
  20321. {
  20322. this.button = event.button;
  20323. }
  20324. this._history = [];
  20325. this.active = true;
  20326. this.withinGame = true;
  20327. this.isDown = true;
  20328. this.isUp = false;
  20329. // Work out how long it has been since the last click
  20330. this.msSinceLastClick = this.game.time.now - this.timeDown;
  20331. this.timeDown = this.game.time.now;
  20332. this._holdSent = false;
  20333. // This sets the x/y and other local values
  20334. this.move(event, true);
  20335. // x and y are the old values here?
  20336. this.positionDown.setTo(this.x, this.y);
  20337. if (this.game.input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers === 0))
  20338. {
  20339. this.game.input.x = this.x;
  20340. this.game.input.y = this.y;
  20341. this.game.input.position.setTo(this.x, this.y);
  20342. this.game.input.onDown.dispatch(this, event);
  20343. this.game.input.resetSpeed(this.x, this.y);
  20344. }
  20345. this._stateReset = false;
  20346. this.totalTouches++;
  20347. if (!this.isMouse)
  20348. {
  20349. this.game.input.currentPointers++;
  20350. }
  20351. if (this.targetObject !== null)
  20352. {
  20353. this.targetObject._touchedHandler(this);
  20354. }
  20355. return this;
  20356. },
  20357. /**
  20358. * Called by the Input Manager.
  20359. * @method Phaser.Pointer#update
  20360. */
  20361. update: function () {
  20362. if (this.active)
  20363. {
  20364. if (this._holdSent === false && this.duration >= this.game.input.holdRate)
  20365. {
  20366. if (this.game.input.multiInputOverride == Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride == Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride == Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers === 0))
  20367. {
  20368. this.game.input.onHold.dispatch(this);
  20369. }
  20370. this._holdSent = true;
  20371. }
  20372. // Update the droppings history
  20373. if (this.game.input.recordPointerHistory && this.game.time.now >= this._nextDrop)
  20374. {
  20375. this._nextDrop = this.game.time.now + this.game.input.recordRate;
  20376. this._history.push({
  20377. x: this.position.x,
  20378. y: this.position.y
  20379. });
  20380. if (this._history.length > this.game.input.recordLimit)
  20381. {
  20382. this._history.shift();
  20383. }
  20384. }
  20385. }
  20386. },
  20387. /**
  20388. * Called when the Pointer is moved.
  20389. *
  20390. * @method Phaser.Pointer#move
  20391. * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
  20392. * @param {boolean} [fromClick=false] - Was this called from the click event?
  20393. */
  20394. move: function (event, fromClick) {
  20395. if (this.game.input.pollLocked)
  20396. {
  20397. return;
  20398. }
  20399. if (typeof fromClick === 'undefined') { fromClick = false; }
  20400. if (typeof event.button !== 'undefined')
  20401. {
  20402. this.button = event.button;
  20403. }
  20404. this.clientX = event.clientX;
  20405. this.clientY = event.clientY;
  20406. this.pageX = event.pageX;
  20407. this.pageY = event.pageY;
  20408. this.screenX = event.screenX;
  20409. this.screenY = event.screenY;
  20410. if (this.isMouse && this.game.input.mouse.locked && !fromClick)
  20411. {
  20412. this.rawMovementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
  20413. this.rawMovementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;
  20414. this.movementX += this.rawMovementX;
  20415. this.movementY += this.rawMovementY;
  20416. }
  20417. this.x = (this.pageX - this.game.stage.offset.x) * this.game.input.scale.x;
  20418. this.y = (this.pageY - this.game.stage.offset.y) * this.game.input.scale.y;
  20419. this.position.setTo(this.x, this.y);
  20420. this.circle.x = this.x;
  20421. this.circle.y = this.y;
  20422. if (this.game.input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers === 0))
  20423. {
  20424. this.game.input.activePointer = this;
  20425. this.game.input.x = this.x;
  20426. this.game.input.y = this.y;
  20427. this.game.input.position.setTo(this.game.input.x, this.game.input.y);
  20428. this.game.input.circle.x = this.game.input.x;
  20429. this.game.input.circle.y = this.game.input.y;
  20430. }
  20431. this.withinGame = this.game.scale.bounds.contains(this.pageX, this.pageY);
  20432. // If the game is paused we don't process any target objects or callbacks
  20433. if (this.game.paused)
  20434. {
  20435. return this;
  20436. }
  20437. // DEPRECATED - Soon to be removed
  20438. if (this.game.input.moveCallback)
  20439. {
  20440. this.game.input.moveCallback.call(this.game.input.moveCallbackContext, this, this.x, this.y);
  20441. }
  20442. var i = this.game.input.moveCallbacks.length;
  20443. while (i--)
  20444. {
  20445. this.game.input.moveCallbacks[i].callback.call(this.game.input.moveCallbacks[i].context, this, this.x, this.y);
  20446. }
  20447. // Easy out if we're dragging something and it still exists
  20448. if (this.targetObject !== null && this.targetObject.isDragged === true)
  20449. {
  20450. if (this.targetObject.update(this) === false)
  20451. {
  20452. this.targetObject = null;
  20453. }
  20454. return this;
  20455. }
  20456. else if (this.game.input.interactiveItems.total > 0)
  20457. {
  20458. this.processInteractiveObjects(fromClick);
  20459. }
  20460. return this;
  20461. },
  20462. /**
  20463. * Process all interactive objects to find out which ones were updated in the recent Pointer move.
  20464. *
  20465. * @method Phaser.Pointer#processInteractiveObjects
  20466. * @protected
  20467. * @param {boolean} [fromClick=false] - Was this called from the click event?
  20468. */
  20469. processInteractiveObjects: function (fromClick) {
  20470. this.game.input.interactiveItems.setAll('checked', false);
  20471. // Work out which object is on the top
  20472. this._highestRenderOrderID = Number.MAX_SAFE_INTEGER;
  20473. this._highestRenderObject = null;
  20474. this._highestInputPriorityID = -1;
  20475. // First pass gets all objects that the pointer is over that DON'T use pixelPerfect checks and get the highest ID
  20476. // We know they'll be valid for input detection but not which is the top just yet
  20477. var currentNode = this.game.input.interactiveItems.first;
  20478. do
  20479. {
  20480. if (currentNode && currentNode.validForInput(this._highestInputPriorityID, this._highestRenderOrderID, false))
  20481. {
  20482. // Flag it as checked so we don't re-scan it on the next phase
  20483. currentNode.checked = true;
  20484. if ((fromClick && currentNode.checkPointerDown(this, true)) || (!fromClick && currentNode.checkPointerOver(this, true)))
  20485. {
  20486. this._highestRenderOrderID = currentNode.sprite._cache[3]; // renderOrderID
  20487. this._highestInputPriorityID = currentNode.priorityID;
  20488. this._highestRenderObject = currentNode;
  20489. }
  20490. }
  20491. currentNode = this.game.input.interactiveItems.next;
  20492. }
  20493. while (currentNode !== null);
  20494. // Then in the second sweep we process ONLY the pixel perfect ones that are checked and who have a higher ID
  20495. // because if their ID is lower anyway then we can just automatically discount them
  20496. var currentNode = this.game.input.interactiveItems.first;
  20497. do
  20498. {
  20499. if (currentNode && !currentNode.checked && currentNode.validForInput(this._highestInputPriorityID, this._highestRenderOrderID, true))
  20500. {
  20501. if ((fromClick && currentNode.checkPointerDown(this, false)) || (!fromClick && currentNode.checkPointerOver(this, false)))
  20502. {
  20503. this._highestRenderOrderID = currentNode.sprite._cache[3]; // renderOrderID
  20504. this._highestInputPriorityID = currentNode.priorityID;
  20505. this._highestRenderObject = currentNode;
  20506. }
  20507. }
  20508. currentNode = this.game.input.interactiveItems.next;
  20509. }
  20510. while (currentNode !== null);
  20511. // Now we know the top-most item (if any) we can process it
  20512. if (this._highestRenderObject === null)
  20513. {
  20514. // The pointer isn't currently over anything, check if we've got a lingering previous target
  20515. if (this.targetObject)
  20516. {
  20517. this.targetObject._pointerOutHandler(this);
  20518. this.targetObject = null;
  20519. }
  20520. }
  20521. else
  20522. {
  20523. if (this.targetObject === null)
  20524. {
  20525. // And now set the new one
  20526. this.targetObject = this._highestRenderObject;
  20527. this._highestRenderObject._pointerOverHandler(this);
  20528. }
  20529. else
  20530. {
  20531. // We've got a target from the last update
  20532. if (this.targetObject === this._highestRenderObject)
  20533. {
  20534. // Same target as before, so update it
  20535. if (this._highestRenderObject.update(this) === false)
  20536. {
  20537. this.targetObject = null;
  20538. }
  20539. }
  20540. else
  20541. {
  20542. // The target has changed, so tell the old one we've left it
  20543. this.targetObject._pointerOutHandler(this);
  20544. // And now set the new one
  20545. this.targetObject = this._highestRenderObject;
  20546. this.targetObject._pointerOverHandler(this);
  20547. }
  20548. }
  20549. }
  20550. },
  20551. /**
  20552. * Called when the Pointer leaves the target area.
  20553. *
  20554. * @method Phaser.Pointer#leave
  20555. * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
  20556. */
  20557. leave: function (event) {
  20558. this.withinGame = false;
  20559. this.move(event, false);
  20560. },
  20561. /**
  20562. * Called when the Pointer leaves the touchscreen.
  20563. *
  20564. * @method Phaser.Pointer#stop
  20565. * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
  20566. */
  20567. stop: function (event) {
  20568. if (this._stateReset)
  20569. {
  20570. event.preventDefault();
  20571. return;
  20572. }
  20573. this.timeUp = this.game.time.now;
  20574. if (this.game.input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers === 0))
  20575. {
  20576. this.game.input.onUp.dispatch(this, event);
  20577. // Was it a tap?
  20578. if (this.duration >= 0 && this.duration <= this.game.input.tapRate)
  20579. {
  20580. // Was it a double-tap?
  20581. if (this.timeUp - this.previousTapTime < this.game.input.doubleTapRate)
  20582. {
  20583. // Yes, let's dispatch the signal then with the 2nd parameter set to true
  20584. this.game.input.onTap.dispatch(this, true);
  20585. }
  20586. else
  20587. {
  20588. // Wasn't a double-tap, so dispatch a single tap signal
  20589. this.game.input.onTap.dispatch(this, false);
  20590. }
  20591. this.previousTapTime = this.timeUp;
  20592. }
  20593. }
  20594. // Mouse is always active
  20595. if (this.id > 0)
  20596. {
  20597. this.active = false;
  20598. }
  20599. this.withinGame = false;
  20600. this.isDown = false;
  20601. this.isUp = true;
  20602. this.pointerId = null;
  20603. this.identifier = null;
  20604. this.positionUp.setTo(this.x, this.y);
  20605. if (this.isMouse === false)
  20606. {
  20607. this.game.input.currentPointers--;
  20608. }
  20609. this.game.input.interactiveItems.callAll('_releasedHandler', this);
  20610. this.targetObject = null;
  20611. return this;
  20612. },
  20613. /**
  20614. * The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate.
  20615. * 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.
  20616. * If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event.
  20617. * @method Phaser.Pointer#justPressed
  20618. * @param {number} [duration] - The time to check against. If none given it will use InputManager.justPressedRate.
  20619. * @return {boolean} true if the Pointer was pressed down within the duration given.
  20620. */
  20621. justPressed: function (duration) {
  20622. duration = duration || this.game.input.justPressedRate;
  20623. return (this.isDown === true && (this.timeDown + duration) > this.game.time.now);
  20624. },
  20625. /**
  20626. * The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate.
  20627. * 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.
  20628. * If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event.
  20629. * @method Phaser.Pointer#justReleased
  20630. * @param {number} [duration] - The time to check against. If none given it will use InputManager.justReleasedRate.
  20631. * @return {boolean} true if the Pointer was released within the duration given.
  20632. */
  20633. justReleased: function (duration) {
  20634. duration = duration || this.game.input.justReleasedRate;
  20635. return (this.isUp === true && (this.timeUp + duration) > this.game.time.now);
  20636. },
  20637. /**
  20638. * Resets the Pointer properties. Called by InputManager.reset when you perform a State change.
  20639. * @method Phaser.Pointer#reset
  20640. */
  20641. reset: function () {
  20642. if (this.isMouse === false)
  20643. {
  20644. this.active = false;
  20645. }
  20646. this.pointerId = null;
  20647. this.identifier = null;
  20648. this.isDown = false;
  20649. this.isUp = true;
  20650. this.totalTouches = 0;
  20651. this._holdSent = false;
  20652. this._history.length = 0;
  20653. this._stateReset = true;
  20654. if (this.targetObject)
  20655. {
  20656. this.targetObject._releasedHandler(this);
  20657. }
  20658. this.targetObject = null;
  20659. },
  20660. /**
  20661. * Resets the movementX and movementY properties. Use in your update handler after retrieving the values.
  20662. * @method Phaser.Pointer#resetMovement
  20663. */
  20664. resetMovement: function() {
  20665. this.movementX = 0;
  20666. this.movementY = 0;
  20667. }
  20668. };
  20669. Phaser.Pointer.prototype.constructor = Phaser.Pointer;
  20670. /**
  20671. * How long the Pointer has been depressed on the touchscreen. If not currently down it returns -1.
  20672. * @name Phaser.Pointer#duration
  20673. * @property {number} duration - How long the Pointer has been depressed on the touchscreen. If not currently down it returns -1.
  20674. * @readonly
  20675. */
  20676. Object.defineProperty(Phaser.Pointer.prototype, "duration", {
  20677. get: function () {
  20678. if (this.isUp)
  20679. {
  20680. return -1;
  20681. }
  20682. return this.game.time.now - this.timeDown;
  20683. }
  20684. });
  20685. /**
  20686. * Gets the X value of this Pointer in world coordinates based on the world camera.
  20687. * @name Phaser.Pointer#worldX
  20688. * @property {number} duration - The X value of this Pointer in world coordinates based on the world camera.
  20689. * @readonly
  20690. */
  20691. Object.defineProperty(Phaser.Pointer.prototype, "worldX", {
  20692. get: function () {
  20693. return this.game.world.camera.x + this.x;
  20694. }
  20695. });
  20696. /**
  20697. * Gets the Y value of this Pointer in world coordinates based on the world camera.
  20698. * @name Phaser.Pointer#worldY
  20699. * @property {number} duration - The Y value of this Pointer in world coordinates based on the world camera.
  20700. * @readonly
  20701. */
  20702. Object.defineProperty(Phaser.Pointer.prototype, "worldY", {
  20703. get: function () {
  20704. return this.game.world.camera.y + this.y;
  20705. }
  20706. });
  20707. /**
  20708. * @author Richard Davey <rich@photonstorm.com>
  20709. * @copyright 2014 Photon Storm Ltd.
  20710. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  20711. */
  20712. /**
  20713. * Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch.
  20714. *
  20715. * @class Phaser.Touch
  20716. * @classdesc The Touch class handles touch interactions with the game and the resulting Pointer objects.
  20717. * @constructor
  20718. * @param {Phaser.Game} game - A reference to the currently running game.
  20719. */
  20720. Phaser.Touch = function (game) {
  20721. /**
  20722. * @property {Phaser.Game} game - A reference to the currently running game.
  20723. */
  20724. this.game = game;
  20725. /**
  20726. * @property {boolean} disabled - You can disable all Touch events by setting disabled = true. While set all new touch events will be ignored.
  20727. * @return {boolean}
  20728. */
  20729. this.disabled = false;
  20730. /**
  20731. * @property {Object} callbackContext - The context under which callbacks are called.
  20732. */
  20733. this.callbackContext = this.game;
  20734. /**
  20735. * @property {function} touchStartCallback - A callback that can be fired on a touchStart event.
  20736. */
  20737. this.touchStartCallback = null;
  20738. /**
  20739. * @property {function} touchMoveCallback - A callback that can be fired on a touchMove event.
  20740. */
  20741. this.touchMoveCallback = null;
  20742. /**
  20743. * @property {function} touchEndCallback - A callback that can be fired on a touchEnd event.
  20744. */
  20745. this.touchEndCallback = null;
  20746. /**
  20747. * @property {function} touchEnterCallback - A callback that can be fired on a touchEnter event.
  20748. */
  20749. this.touchEnterCallback = null;
  20750. /**
  20751. * @property {function} touchLeaveCallback - A callback that can be fired on a touchLeave event.
  20752. */
  20753. this.touchLeaveCallback = null;
  20754. /**
  20755. * @property {function} touchCancelCallback - A callback that can be fired on a touchCancel event.
  20756. */
  20757. this.touchCancelCallback = null;
  20758. /**
  20759. * @property {boolean} preventDefault - If true the TouchEvent will have prevent.default called on it.
  20760. * @default
  20761. */
  20762. this.preventDefault = true;
  20763. /**
  20764. * @property {TouchEvent} event - The browser touch DOM event. Will be set to null if no touch event has ever been received.
  20765. * @default
  20766. */
  20767. this.event = null;
  20768. /**
  20769. * @property {function} _onTouchStart - Internal event handler reference.
  20770. * @private
  20771. */
  20772. this._onTouchStart = null;
  20773. /**
  20774. * @property {function} _onTouchMove - Internal event handler reference.
  20775. * @private
  20776. */
  20777. this._onTouchMove = null;
  20778. /**
  20779. * @property {function} _onTouchEnd - Internal event handler reference.
  20780. * @private
  20781. */
  20782. this._onTouchEnd = null;
  20783. /**
  20784. * @property {function} _onTouchEnter - Internal event handler reference.
  20785. * @private
  20786. */
  20787. this._onTouchEnter = null;
  20788. /**
  20789. * @property {function} _onTouchLeave - Internal event handler reference.
  20790. * @private
  20791. */
  20792. this._onTouchLeave = null;
  20793. /**
  20794. * @property {function} _onTouchCancel - Internal event handler reference.
  20795. * @private
  20796. */
  20797. this._onTouchCancel = null;
  20798. /**
  20799. * @property {function} _onTouchMove - Internal event handler reference.
  20800. * @private
  20801. */
  20802. this._onTouchMove = null;
  20803. };
  20804. Phaser.Touch.prototype = {
  20805. /**
  20806. * Starts the event listeners running.
  20807. * @method Phaser.Touch#start
  20808. */
  20809. start: function () {
  20810. if (this._onTouchStart !== null)
  20811. {
  20812. // Avoid setting multiple listeners
  20813. return;
  20814. }
  20815. var _this = this;
  20816. if (this.game.device.touch)
  20817. {
  20818. this._onTouchStart = function (event) {
  20819. return _this.onTouchStart(event);
  20820. };
  20821. this._onTouchMove = function (event) {
  20822. return _this.onTouchMove(event);
  20823. };
  20824. this._onTouchEnd = function (event) {
  20825. return _this.onTouchEnd(event);
  20826. };
  20827. this._onTouchEnter = function (event) {
  20828. return _this.onTouchEnter(event);
  20829. };
  20830. this._onTouchLeave = function (event) {
  20831. return _this.onTouchLeave(event);
  20832. };
  20833. this._onTouchCancel = function (event) {
  20834. return _this.onTouchCancel(event);
  20835. };
  20836. this.game.canvas.addEventListener('touchstart', this._onTouchStart, false);
  20837. this.game.canvas.addEventListener('touchmove', this._onTouchMove, false);
  20838. this.game.canvas.addEventListener('touchend', this._onTouchEnd, false);
  20839. this.game.canvas.addEventListener('touchcancel', this._onTouchCancel, false);
  20840. if (!this.game.device.cocoonJS)
  20841. {
  20842. this.game.canvas.addEventListener('touchenter', this._onTouchEnter, false);
  20843. this.game.canvas.addEventListener('touchleave', this._onTouchLeave, false);
  20844. }
  20845. }
  20846. },
  20847. /**
  20848. * Consumes all touchmove events on the document (only enable this if you know you need it!).
  20849. * @method Phaser.Touch#consumeTouchMove
  20850. */
  20851. consumeDocumentTouches: function () {
  20852. this._documentTouchMove = function (event) {
  20853. event.preventDefault();
  20854. };
  20855. document.addEventListener('touchmove', this._documentTouchMove, false);
  20856. },
  20857. /**
  20858. * The internal method that handles the touchstart event from the browser.
  20859. * @method Phaser.Touch#onTouchStart
  20860. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  20861. */
  20862. onTouchStart: function (event) {
  20863. this.event = event;
  20864. if (this.touchStartCallback)
  20865. {
  20866. this.touchStartCallback.call(this.callbackContext, event);
  20867. }
  20868. if (this.game.input.disabled || this.disabled)
  20869. {
  20870. return;
  20871. }
  20872. if (this.preventDefault)
  20873. {
  20874. event.preventDefault();
  20875. }
  20876. // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element)
  20877. // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element
  20878. // event.changedTouches = the touches that CHANGED in this event, not the total number of them
  20879. for (var i = 0; i < event.changedTouches.length; i++)
  20880. {
  20881. this.game.input.startPointer(event.changedTouches[i]);
  20882. }
  20883. },
  20884. /**
  20885. * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome).
  20886. * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears.
  20887. * @method Phaser.Touch#onTouchCancel
  20888. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  20889. */
  20890. onTouchCancel: function (event) {
  20891. this.event = event;
  20892. if (this.touchCancelCallback)
  20893. {
  20894. this.touchCancelCallback.call(this.callbackContext, event);
  20895. }
  20896. if (this.game.input.disabled || this.disabled)
  20897. {
  20898. return;
  20899. }
  20900. if (this.preventDefault)
  20901. {
  20902. event.preventDefault();
  20903. }
  20904. // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome)
  20905. // http://www.w3.org/TR/touch-events/#dfn-touchcancel
  20906. for (var i = 0; i < event.changedTouches.length; i++)
  20907. {
  20908. this.game.input.stopPointer(event.changedTouches[i]);
  20909. }
  20910. },
  20911. /**
  20912. * For touch enter and leave its a list of the touch points that have entered or left the target.
  20913. * Doesn't appear to be supported by most browsers on a canvas element yet.
  20914. * @method Phaser.Touch#onTouchEnter
  20915. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  20916. */
  20917. onTouchEnter: function (event) {
  20918. this.event = event;
  20919. if (this.touchEnterCallback)
  20920. {
  20921. this.touchEnterCallback.call(this.callbackContext, event);
  20922. }
  20923. if (this.game.input.disabled || this.disabled)
  20924. {
  20925. return;
  20926. }
  20927. if (this.preventDefault)
  20928. {
  20929. event.preventDefault();
  20930. }
  20931. },
  20932. /**
  20933. * For touch enter and leave its a list of the touch points that have entered or left the target.
  20934. * Doesn't appear to be supported by most browsers on a canvas element yet.
  20935. * @method Phaser.Touch#onTouchLeave
  20936. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  20937. */
  20938. onTouchLeave: function (event) {
  20939. this.event = event;
  20940. if (this.touchLeaveCallback)
  20941. {
  20942. this.touchLeaveCallback.call(this.callbackContext, event);
  20943. }
  20944. if (this.preventDefault)
  20945. {
  20946. event.preventDefault();
  20947. }
  20948. },
  20949. /**
  20950. * The handler for the touchmove events.
  20951. * @method Phaser.Touch#onTouchMove
  20952. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  20953. */
  20954. onTouchMove: function (event) {
  20955. this.event = event;
  20956. if (this.touchMoveCallback)
  20957. {
  20958. this.touchMoveCallback.call(this.callbackContext, event);
  20959. }
  20960. if (this.preventDefault)
  20961. {
  20962. event.preventDefault();
  20963. }
  20964. for (var i = 0; i < event.changedTouches.length; i++)
  20965. {
  20966. this.game.input.updatePointer(event.changedTouches[i]);
  20967. }
  20968. },
  20969. /**
  20970. * The handler for the touchend events.
  20971. * @method Phaser.Touch#onTouchEnd
  20972. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  20973. */
  20974. onTouchEnd: function (event) {
  20975. this.event = event;
  20976. if (this.touchEndCallback)
  20977. {
  20978. this.touchEndCallback.call(this.callbackContext, event);
  20979. }
  20980. if (this.preventDefault)
  20981. {
  20982. event.preventDefault();
  20983. }
  20984. // For touch end its a list of the touch points that have been removed from the surface
  20985. // https://developer.mozilla.org/en-US/docs/DOM/TouchList
  20986. // event.changedTouches = the touches that CHANGED in this event, not the total number of them
  20987. for (var i = 0; i < event.changedTouches.length; i++)
  20988. {
  20989. this.game.input.stopPointer(event.changedTouches[i]);
  20990. }
  20991. },
  20992. /**
  20993. * Stop the event listeners.
  20994. * @method Phaser.Touch#stop
  20995. */
  20996. stop: function () {
  20997. if (this.game.device.touch)
  20998. {
  20999. this.game.canvas.removeEventListener('touchstart', this._onTouchStart);
  21000. this.game.canvas.removeEventListener('touchmove', this._onTouchMove);
  21001. this.game.canvas.removeEventListener('touchend', this._onTouchEnd);
  21002. this.game.canvas.removeEventListener('touchenter', this._onTouchEnter);
  21003. this.game.canvas.removeEventListener('touchleave', this._onTouchLeave);
  21004. this.game.canvas.removeEventListener('touchcancel', this._onTouchCancel);
  21005. }
  21006. }
  21007. };
  21008. Phaser.Touch.prototype.constructor = Phaser.Touch;
  21009. /**
  21010. * @author @karlmacklin <tacklemcclean@gmail.com>
  21011. * @copyright 2014 Photon Storm Ltd.
  21012. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  21013. */
  21014. /**
  21015. * The Gamepad class handles looking after gamepad input for your game.
  21016. * Remember to call gamepad.start(); expecting input!
  21017. *
  21018. * HTML5 GAMEPAD API SUPPORT IS AT AN EXPERIMENTAL STAGE!
  21019. * At moment of writing this (end of 2013) only Chrome supports parts of it out of the box. Firefox supports it
  21020. * via prefs flags (about:config, search gamepad). The browsers map the same controllers differently.
  21021. * This class has constants for Windows 7 Chrome mapping of XBOX 360 controller.
  21022. *
  21023. * @class Phaser.Gamepad
  21024. * @constructor
  21025. * @param {Phaser.Game} game - A reference to the currently running game.
  21026. */
  21027. Phaser.Gamepad = function (game) {
  21028. /**
  21029. * @property {Phaser.Game} game - Local reference to game.
  21030. */
  21031. this.game = game;
  21032. /**
  21033. * @property {Array<Phaser.SinglePad>} _gamepads - The four Phaser Gamepads.
  21034. * @private
  21035. */
  21036. this._gamepads = [
  21037. new Phaser.SinglePad(game, this),
  21038. new Phaser.SinglePad(game, this),
  21039. new Phaser.SinglePad(game, this),
  21040. new Phaser.SinglePad(game, this)
  21041. ];
  21042. /**
  21043. * @property {Object} _gamepadIndexMap - Maps the browsers gamepad indices to our Phaser Gamepads
  21044. * @private
  21045. */
  21046. this._gamepadIndexMap = {};
  21047. /**
  21048. * @property {Array} _rawPads - The raw state of the gamepads from the browser
  21049. * @private
  21050. */
  21051. this._rawPads = [];
  21052. /**
  21053. * @property {boolean} _active - Private flag for whether or not the API is polled
  21054. * @private
  21055. * @default
  21056. */
  21057. this._active = false;
  21058. /**
  21059. * You can disable all Gamepad Input by setting disabled to true. While true all new input related events will be ignored.
  21060. * @property {boolean} disabled - The disabled state of the Gamepad.
  21061. * @default
  21062. */
  21063. this.disabled = false;
  21064. /**
  21065. * 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.
  21066. * @property {boolean} _gamepadSupportAvailable - Are gamepads supported in this browser or not?
  21067. * @private
  21068. */
  21069. this._gamepadSupportAvailable = !!navigator.webkitGetGamepads || !!navigator.webkitGamepads || (navigator.userAgent.indexOf('Firefox/') != -1) || !!navigator.getGamepads;
  21070. /**
  21071. * Used to check for differences between earlier polls and current state of gamepads.
  21072. * @property {Array} _prevRawGamepadTypes
  21073. * @private
  21074. * @default
  21075. */
  21076. this._prevRawGamepadTypes = [];
  21077. /**
  21078. * Used to check for differences between earlier polls and current state of gamepads.
  21079. * @property {Array} _prevTimestamps
  21080. * @private
  21081. * @default
  21082. */
  21083. this._prevTimestamps = [];
  21084. /**
  21085. * @property {Object} callbackContext - The context under which the callbacks are run.
  21086. */
  21087. this.callbackContext = this;
  21088. /**
  21089. * @property {function} onConnectCallback - This callback is invoked every time any gamepad is connected
  21090. */
  21091. this.onConnectCallback = null;
  21092. /**
  21093. * @property {function} onDisconnectCallback - This callback is invoked every time any gamepad is disconnected
  21094. */
  21095. this.onDisconnectCallback = null;
  21096. /**
  21097. * @property {function} onDownCallback - This callback is invoked every time any gamepad button is pressed down.
  21098. */
  21099. this.onDownCallback = null;
  21100. /**
  21101. * @property {function} onUpCallback - This callback is invoked every time any gamepad button is released.
  21102. */
  21103. this.onUpCallback = null;
  21104. /**
  21105. * @property {function} onAxisCallback - This callback is invoked every time any gamepad axis is changed.
  21106. */
  21107. this.onAxisCallback = null;
  21108. /**
  21109. * @property {function} onFloatCallback - This callback is invoked every time any gamepad button is changed to a value where value > 0 and value < 1.
  21110. */
  21111. this.onFloatCallback = null;
  21112. /**
  21113. * @property {function} _ongamepadconnected - Private callback for Firefox gamepad connection handling
  21114. * @private
  21115. */
  21116. this._ongamepadconnected = null;
  21117. /**
  21118. * @property {function} _gamepaddisconnected - Private callback for Firefox gamepad connection handling
  21119. * @private
  21120. */
  21121. this._gamepaddisconnected = null;
  21122. };
  21123. Phaser.Gamepad.prototype = {
  21124. /**
  21125. * Add callbacks to the main Gamepad handler to handle connect/disconnect/button down/button up/axis change/float value buttons
  21126. * @method Phaser.Gamepad#addCallbacks
  21127. * @param {Object} context - The context under which the callbacks are run.
  21128. * @param {Object} callbacks - Object that takes six different callback methods:
  21129. * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback
  21130. */
  21131. addCallbacks: function (context, callbacks) {
  21132. if (typeof callbacks !== 'undefined')
  21133. {
  21134. this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback;
  21135. this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback;
  21136. this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback;
  21137. this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback;
  21138. this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback;
  21139. this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback;
  21140. }
  21141. },
  21142. /**
  21143. * Starts the Gamepad event handling.
  21144. * This MUST be called manually before Phaser will start polling the Gamepad API.
  21145. *
  21146. * @method Phaser.Gamepad#start
  21147. */
  21148. start: function () {
  21149. if (this._active)
  21150. {
  21151. // Avoid setting multiple listeners
  21152. return;
  21153. }
  21154. this._active = true;
  21155. var _this = this;
  21156. this._ongamepadconnected = function(event) {
  21157. var newPad = event.gamepad;
  21158. _this._rawPads.push(newPad);
  21159. _this._gamepads[newPad.index].connect(newPad);
  21160. };
  21161. window.addEventListener('gamepadconnected', this._ongamepadconnected, false);
  21162. this._ongamepaddisconnected = function(event) {
  21163. var removedPad = event.gamepad;
  21164. for (var i in _this._rawPads)
  21165. {
  21166. if (_this._rawPads[i].index === removedPad.index)
  21167. {
  21168. _this._rawPads.splice(i,1);
  21169. }
  21170. }
  21171. _this._gamepads[removedPad.index].disconnect();
  21172. };
  21173. window.addEventListener('gamepaddisconnected', this._ongamepaddisconnected, false);
  21174. },
  21175. /**
  21176. * Main gamepad update loop. Should not be called manually.
  21177. * @method Phaser.Gamepad#update
  21178. * @protected
  21179. */
  21180. update: function () {
  21181. this._pollGamepads();
  21182. this.pad1.pollStatus();
  21183. this.pad2.pollStatus();
  21184. this.pad3.pollStatus();
  21185. this.pad4.pollStatus();
  21186. },
  21187. /**
  21188. * Updating connected gamepads (for Google Chrome). Should not be called manually.
  21189. *
  21190. * @method Phaser.Gamepad#_pollGamepads
  21191. * @private
  21192. */
  21193. _pollGamepads: function () {
  21194. if (navigator['getGamepads'])
  21195. {
  21196. var rawGamepads = navigator.getGamepads();
  21197. }
  21198. else if (navigator['webkitGetGamepads'])
  21199. {
  21200. var rawGamepads = navigator.webkitGetGamepads();
  21201. }
  21202. else if (navigator['webkitGamepads'])
  21203. {
  21204. var rawGamepads = navigator.webkitGamepads();
  21205. }
  21206. if (rawGamepads)
  21207. {
  21208. this._rawPads = [];
  21209. var gamepadsChanged = false;
  21210. for (var i = 0; i < rawGamepads.length; i++)
  21211. {
  21212. if (typeof rawGamepads[i] !== this._prevRawGamepadTypes[i])
  21213. {
  21214. gamepadsChanged = true;
  21215. this._prevRawGamepadTypes[i] = typeof rawGamepads[i];
  21216. }
  21217. if (rawGamepads[i])
  21218. {
  21219. this._rawPads.push(rawGamepads[i]);
  21220. }
  21221. // Support max 4 pads at the moment
  21222. if (i === 3)
  21223. {
  21224. break;
  21225. }
  21226. }
  21227. if (gamepadsChanged)
  21228. {
  21229. var validConnections = { rawIndices: {}, padIndices: {} };
  21230. var singlePad;
  21231. for (var j = 0; j < this._gamepads.length; j++)
  21232. {
  21233. singlePad = this._gamepads[j];
  21234. if (singlePad.connected)
  21235. {
  21236. for (var k = 0; k < this._rawPads.length; k++)
  21237. {
  21238. if (this._rawPads[k].index === singlePad.index)
  21239. {
  21240. validConnections.rawIndices[singlePad.index] = true;
  21241. validConnections.padIndices[j] = true;
  21242. }
  21243. }
  21244. }
  21245. }
  21246. for (var l = 0; l < this._gamepads.length; l++)
  21247. {
  21248. singlePad = this._gamepads[l];
  21249. if (validConnections.padIndices[l])
  21250. {
  21251. continue;
  21252. }
  21253. if (this._rawPads.length < 1)
  21254. {
  21255. singlePad.disconnect();
  21256. }
  21257. for (var m = 0; m < this._rawPads.length; m++)
  21258. {
  21259. if (validConnections.padIndices[l])
  21260. {
  21261. break;
  21262. }
  21263. var rawPad = this._rawPads[m];
  21264. if (rawPad)
  21265. {
  21266. if (validConnections.rawIndices[rawPad.index])
  21267. {
  21268. singlePad.disconnect();
  21269. continue;
  21270. }
  21271. else
  21272. {
  21273. singlePad.connect(rawPad);
  21274. validConnections.rawIndices[rawPad.index] = true;
  21275. validConnections.padIndices[l] = true;
  21276. }
  21277. }
  21278. else
  21279. {
  21280. singlePad.disconnect();
  21281. }
  21282. }
  21283. }
  21284. }
  21285. }
  21286. },
  21287. /**
  21288. * Sets the deadZone variable for all four gamepads
  21289. * @method Phaser.Gamepad#setDeadZones
  21290. */
  21291. setDeadZones: function (value) {
  21292. for (var i = 0; i < this._gamepads.length; i++)
  21293. {
  21294. this._gamepads[i].deadZone = value;
  21295. }
  21296. },
  21297. /**
  21298. * Stops the Gamepad event handling.
  21299. *
  21300. * @method Phaser.Gamepad#stop
  21301. */
  21302. stop: function () {
  21303. this._active = false;
  21304. window.removeEventListener('gamepadconnected', this._ongamepadconnected);
  21305. window.removeEventListener('gamepaddisconnected', this._ongamepaddisconnected);
  21306. },
  21307. /**
  21308. * Reset all buttons/axes of all gamepads
  21309. * @method Phaser.Gamepad#reset
  21310. */
  21311. reset: function () {
  21312. this.update();
  21313. for (var i = 0; i < this._gamepads.length; i++)
  21314. {
  21315. this._gamepads[i].reset();
  21316. }
  21317. },
  21318. /**
  21319. * 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).
  21320. * @method Phaser.Gamepad#justPressed
  21321. * @param {number} buttonCode - The buttonCode of the button to check for.
  21322. * @param {number} [duration=250] - The duration below which the button is considered as being just pressed.
  21323. * @return {boolean} True if the button is just pressed otherwise false.
  21324. */
  21325. justPressed: function (buttonCode, duration) {
  21326. for (var i = 0; i < this._gamepads.length; i++)
  21327. {
  21328. if (this._gamepads[i].justPressed(buttonCode, duration) === true)
  21329. {
  21330. return true;
  21331. }
  21332. }
  21333. return false;
  21334. },
  21335. /**
  21336. * 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).
  21337. * @method Phaser.Gamepad#justPressed
  21338. * @param {number} buttonCode - The buttonCode of the button to check for.
  21339. * @param {number} [duration=250] - The duration below which the button is considered as being just released.
  21340. * @return {boolean} True if the button is just released otherwise false.
  21341. */
  21342. justReleased: function (buttonCode, duration) {
  21343. for (var i = 0; i < this._gamepads.length; i++)
  21344. {
  21345. if (this._gamepads[i].justReleased(buttonCode, duration) === true)
  21346. {
  21347. return true;
  21348. }
  21349. }
  21350. return false;
  21351. },
  21352. /**
  21353. * Returns true if the button is currently pressed down, on ANY gamepad.
  21354. * @method Phaser.Gamepad#isDown
  21355. * @param {number} buttonCode - The buttonCode of the button to check for.
  21356. * @return {boolean} True if a button is currently down.
  21357. */
  21358. isDown: function (buttonCode) {
  21359. for (var i = 0; i < this._gamepads.length; i++)
  21360. {
  21361. if (this._gamepads[i].isDown(buttonCode) === true)
  21362. {
  21363. return true;
  21364. }
  21365. }
  21366. return false;
  21367. }
  21368. };
  21369. Phaser.Gamepad.prototype.constructor = Phaser.Gamepad;
  21370. /**
  21371. * If the gamepad input is active or not - if not active it should not be updated from Input.js
  21372. * @name Phaser.Gamepad#active
  21373. * @property {boolean} active - If the gamepad input is active or not.
  21374. * @readonly
  21375. */
  21376. Object.defineProperty(Phaser.Gamepad.prototype, "active", {
  21377. get: function () {
  21378. return this._active;
  21379. }
  21380. });
  21381. /**
  21382. * Whether or not gamepads are supported in current browser.
  21383. * @name Phaser.Gamepad#supported
  21384. * @property {boolean} supported - Whether or not gamepads are supported in current browser.
  21385. * @readonly
  21386. */
  21387. Object.defineProperty(Phaser.Gamepad.prototype, "supported", {
  21388. get: function () {
  21389. return this._gamepadSupportAvailable;
  21390. }
  21391. });
  21392. /**
  21393. * How many live gamepads are currently connected.
  21394. * @name Phaser.Gamepad#padsConnected
  21395. * @property {boolean} padsConnected - How many live gamepads are currently connected.
  21396. * @readonly
  21397. */
  21398. Object.defineProperty(Phaser.Gamepad.prototype, "padsConnected", {
  21399. get: function () {
  21400. return this._rawPads.length;
  21401. }
  21402. });
  21403. /**
  21404. * Gamepad #1
  21405. * @name Phaser.Gamepad#pad1
  21406. * @property {boolean} pad1 - Gamepad #1;
  21407. * @readonly
  21408. */
  21409. Object.defineProperty(Phaser.Gamepad.prototype, "pad1", {
  21410. get: function () {
  21411. return this._gamepads[0];
  21412. }
  21413. });
  21414. /**
  21415. * Gamepad #2
  21416. * @name Phaser.Gamepad#pad2
  21417. * @property {boolean} pad2 - Gamepad #2
  21418. * @readonly
  21419. */
  21420. Object.defineProperty(Phaser.Gamepad.prototype, "pad2", {
  21421. get: function () {
  21422. return this._gamepads[1];
  21423. }
  21424. });
  21425. /**
  21426. * Gamepad #3
  21427. * @name Phaser.Gamepad#pad3
  21428. * @property {boolean} pad3 - Gamepad #3
  21429. * @readonly
  21430. */
  21431. Object.defineProperty(Phaser.Gamepad.prototype, "pad3", {
  21432. get: function () {
  21433. return this._gamepads[2];
  21434. }
  21435. });
  21436. /**
  21437. * Gamepad #4
  21438. * @name Phaser.Gamepad#pad4
  21439. * @property {boolean} pad4 - Gamepad #4
  21440. * @readonly
  21441. */
  21442. Object.defineProperty(Phaser.Gamepad.prototype, "pad4", {
  21443. get: function () {
  21444. return this._gamepads[3];
  21445. }
  21446. });
  21447. Phaser.Gamepad.BUTTON_0 = 0;
  21448. Phaser.Gamepad.BUTTON_1 = 1;
  21449. Phaser.Gamepad.BUTTON_2 = 2;
  21450. Phaser.Gamepad.BUTTON_3 = 3;
  21451. Phaser.Gamepad.BUTTON_4 = 4;
  21452. Phaser.Gamepad.BUTTON_5 = 5;
  21453. Phaser.Gamepad.BUTTON_6 = 6;
  21454. Phaser.Gamepad.BUTTON_7 = 7;
  21455. Phaser.Gamepad.BUTTON_8 = 8;
  21456. Phaser.Gamepad.BUTTON_9 = 9;
  21457. Phaser.Gamepad.BUTTON_10 = 10;
  21458. Phaser.Gamepad.BUTTON_11 = 11;
  21459. Phaser.Gamepad.BUTTON_12 = 12;
  21460. Phaser.Gamepad.BUTTON_13 = 13;
  21461. Phaser.Gamepad.BUTTON_14 = 14;
  21462. Phaser.Gamepad.BUTTON_15 = 15;
  21463. Phaser.Gamepad.AXIS_0 = 0;
  21464. Phaser.Gamepad.AXIS_1 = 1;
  21465. Phaser.Gamepad.AXIS_2 = 2;
  21466. Phaser.Gamepad.AXIS_3 = 3;
  21467. Phaser.Gamepad.AXIS_4 = 4;
  21468. Phaser.Gamepad.AXIS_5 = 5;
  21469. Phaser.Gamepad.AXIS_6 = 6;
  21470. Phaser.Gamepad.AXIS_7 = 7;
  21471. Phaser.Gamepad.AXIS_8 = 8;
  21472. Phaser.Gamepad.AXIS_9 = 9;
  21473. // Below mapping applies to XBOX 360 Wired and Wireless controller on Google Chrome (tested on Windows 7).
  21474. // - Firefox uses different map! Separate amount of buttons and axes. DPAD = axis and not a button.
  21475. // In other words - discrepancies when using gamepads.
  21476. Phaser.Gamepad.XBOX360_A = 0;
  21477. Phaser.Gamepad.XBOX360_B = 1;
  21478. Phaser.Gamepad.XBOX360_X = 2;
  21479. Phaser.Gamepad.XBOX360_Y = 3;
  21480. Phaser.Gamepad.XBOX360_LEFT_BUMPER = 4;
  21481. Phaser.Gamepad.XBOX360_RIGHT_BUMPER = 5;
  21482. Phaser.Gamepad.XBOX360_LEFT_TRIGGER = 6;
  21483. Phaser.Gamepad.XBOX360_RIGHT_TRIGGER = 7;
  21484. Phaser.Gamepad.XBOX360_BACK = 8;
  21485. Phaser.Gamepad.XBOX360_START = 9;
  21486. Phaser.Gamepad.XBOX360_STICK_LEFT_BUTTON = 10;
  21487. Phaser.Gamepad.XBOX360_STICK_RIGHT_BUTTON = 11;
  21488. Phaser.Gamepad.XBOX360_DPAD_LEFT = 14;
  21489. Phaser.Gamepad.XBOX360_DPAD_RIGHT = 15;
  21490. Phaser.Gamepad.XBOX360_DPAD_UP = 12;
  21491. Phaser.Gamepad.XBOX360_DPAD_DOWN = 13;
  21492. Phaser.Gamepad.XBOX360_STICK_LEFT_X = 0;
  21493. Phaser.Gamepad.XBOX360_STICK_LEFT_Y = 1;
  21494. Phaser.Gamepad.XBOX360_STICK_RIGHT_X = 2;
  21495. Phaser.Gamepad.XBOX360_STICK_RIGHT_Y = 3;
  21496. // PlayStation 3 controller (masquerading as xbox360 controller) button mappings
  21497. Phaser.Gamepad.PS3XC_X = 0;
  21498. Phaser.Gamepad.PS3XC_CIRCLE = 1;
  21499. Phaser.Gamepad.PS3XC_SQUARE = 2;
  21500. Phaser.Gamepad.PS3XC_TRIANGLE = 3;
  21501. Phaser.Gamepad.PS3XC_L1 = 4;
  21502. Phaser.Gamepad.PS3XC_R1 = 5;
  21503. Phaser.Gamepad.PS3XC_L2 = 6; // analog trigger, range 0..1
  21504. Phaser.Gamepad.PS3XC_R2 = 7; // analog trigger, range 0..1
  21505. Phaser.Gamepad.PS3XC_SELECT = 8;
  21506. Phaser.Gamepad.PS3XC_START = 9;
  21507. Phaser.Gamepad.PS3XC_STICK_LEFT_BUTTON = 10;
  21508. Phaser.Gamepad.PS3XC_STICK_RIGHT_BUTTON = 11;
  21509. Phaser.Gamepad.PS3XC_DPAD_UP = 12;
  21510. Phaser.Gamepad.PS3XC_DPAD_DOWN = 13;
  21511. Phaser.Gamepad.PS3XC_DPAD_LEFT = 14;
  21512. Phaser.Gamepad.PS3XC_DPAD_RIGHT = 15;
  21513. Phaser.Gamepad.PS3XC_STICK_LEFT_X = 0; // analog stick, range -1..1
  21514. Phaser.Gamepad.PS3XC_STICK_LEFT_Y = 1; // analog stick, range -1..1
  21515. Phaser.Gamepad.PS3XC_STICK_RIGHT_X = 2; // analog stick, range -1..1
  21516. Phaser.Gamepad.PS3XC_STICK_RIGHT_Y = 3; // analog stick, range -1..1
  21517. /**
  21518. * @author @karlmacklin <tacklemcclean@gmail.com>
  21519. * @author Richard Davey <rich@photonstorm.com>
  21520. * @copyright 2014 Photon Storm Ltd.
  21521. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  21522. */
  21523. /**
  21524. * @class Phaser.SinglePad
  21525. * @classdesc A single Phaser Gamepad
  21526. * @constructor
  21527. * @param {Phaser.Game} game - Current game instance.
  21528. * @param {Object} padParent - The parent Phaser.Gamepad object (all gamepads reside under this)
  21529. */
  21530. Phaser.SinglePad = function (game, padParent) {
  21531. /**
  21532. * @property {Phaser.Game} game - Local reference to game.
  21533. */
  21534. this.game = game;
  21535. /**
  21536. * @property {number} index - The gamepad index as per browsers data
  21537. * @readonly
  21538. */
  21539. this.index = null;
  21540. /**
  21541. * @property {boolean} connected - Whether or not this particular gamepad is connected or not.
  21542. * @readonly
  21543. */
  21544. this.connected = false;
  21545. /**
  21546. * @property {Object} callbackContext - The context under which the callbacks are run.
  21547. */
  21548. this.callbackContext = this;
  21549. /**
  21550. * @property {function} onConnectCallback - This callback is invoked every time this gamepad is connected
  21551. */
  21552. this.onConnectCallback = null;
  21553. /**
  21554. * @property {function} onDisconnectCallback - This callback is invoked every time this gamepad is disconnected
  21555. */
  21556. this.onDisconnectCallback = null;
  21557. /**
  21558. * @property {function} onDownCallback - This callback is invoked every time a button is pressed down.
  21559. */
  21560. this.onDownCallback = null;
  21561. /**
  21562. * @property {function} onUpCallback - This callback is invoked every time a gamepad button is released.
  21563. */
  21564. this.onUpCallback = null;
  21565. /**
  21566. * @property {function} onAxisCallback - This callback is invoked every time an axis is changed.
  21567. */
  21568. this.onAxisCallback = null;
  21569. /**
  21570. * @property {function} onFloatCallback - This callback is invoked every time a button is changed to a value where value > 0 and value < 1.
  21571. */
  21572. this.onFloatCallback = null;
  21573. /**
  21574. * @property {number} deadZone - Dead zone for axis feedback - within this value you won't trigger updates.
  21575. */
  21576. this.deadZone = 0.26;
  21577. /**
  21578. * @property {Phaser.Gamepad} padParent - Main Phaser Gamepad object
  21579. * @private
  21580. */
  21581. this._padParent = padParent;
  21582. /**
  21583. * @property {Object} _rawPad - The 'raw' gamepad data.
  21584. * @private
  21585. */
  21586. this._rawPad = null;
  21587. /**
  21588. * @property {number} _prevTimestamp - Used to check for differences between earlier polls and current state of gamepads.
  21589. * @private
  21590. */
  21591. this._prevTimestamp = null;
  21592. /**
  21593. * @property {Array} _buttons - Array of Phaser.GamepadButton objects. This array is populated when the gamepad is connected.
  21594. * @private
  21595. */
  21596. this._buttons = [];
  21597. /**
  21598. * @property {number} _buttonsLen - Length of the _buttons array.
  21599. * @private
  21600. */
  21601. this._buttonsLen = 0;
  21602. /**
  21603. * @property {Array} _axes - Current axes state.
  21604. * @private
  21605. */
  21606. this._axes = [];
  21607. /**
  21608. * @property {number} _axesLen - Length of the _axes array.
  21609. * @private
  21610. */
  21611. this._axesLen = 0;
  21612. };
  21613. Phaser.SinglePad.prototype = {
  21614. /**
  21615. * Add callbacks to the this Gamepad to handle connect / disconnect / button down / button up / axis change / float value buttons.
  21616. *
  21617. * @method Phaser.SinglePad#addCallbacks
  21618. * @param {Object} context - The context under which the callbacks are run.
  21619. * @param {Object} callbacks - Object that takes six different callbak methods:
  21620. * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback
  21621. */
  21622. addCallbacks: function (context, callbacks) {
  21623. if (typeof callbacks !== 'undefined')
  21624. {
  21625. this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback;
  21626. this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback;
  21627. this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback;
  21628. this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback;
  21629. this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback;
  21630. this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback;
  21631. }
  21632. },
  21633. /**
  21634. * DEPRECATED: Please see SinglePad.getButton for the same functionality.
  21635. *
  21636. * If you need more fine-grained control over a gamepad button you can create a new Phaser.GamepadButton object via this method.
  21637. * The GamepadButton object can then be polled, have events attached to it, etc.
  21638. *
  21639. * @method Phaser.SinglePad#addButton
  21640. * @param {number} buttonCode - The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON_0, Phaser.Gamepad.XBOX360_A, etc.
  21641. * @return {Phaser.GamepadButton} The GamepadButton object which you can store locally and reference directly.
  21642. */
  21643. addButton: function (buttonCode) {
  21644. return this.getButton(buttonCode);
  21645. },
  21646. /**
  21647. * Gets a GamepadButton object from this controller to be stored and referenced locally.
  21648. * The GamepadButton object can then be polled, have events attached to it, etc.
  21649. *
  21650. * @method Phaser.SinglePad#getButton
  21651. * @param {number} buttonCode - The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON_0, Phaser.Gamepad.XBOX360_A, etc.
  21652. * @return {Phaser.GamepadButton} The GamepadButton object which you can store locally and reference directly.
  21653. */
  21654. getButton: function (buttonCode) {
  21655. if (this._buttons[buttonCode])
  21656. {
  21657. return this._buttons[buttonCode];
  21658. }
  21659. else
  21660. {
  21661. return null;
  21662. }
  21663. },
  21664. /**
  21665. * Main update function, should be called by Phaser.Gamepad.
  21666. *
  21667. * @method Phaser.SinglePad#pollStatus
  21668. */
  21669. pollStatus: function () {
  21670. if (!this.connected || this.game.input.disabled || this.game.input.gamepad.disabled || (this._rawPad.timestamp && (this._rawPad.timestamp === this._prevTimestamp)))
  21671. {
  21672. return;
  21673. }
  21674. for (var i = 0; i < this._buttonsLen; i++)
  21675. {
  21676. var rawButtonVal = isNaN(this._rawPad.buttons[i]) ? this._rawPad.buttons[i].value : this._rawPad.buttons[i];
  21677. if (rawButtonVal !== this._buttons[i].value)
  21678. {
  21679. if (rawButtonVal === 1)
  21680. {
  21681. this.processButtonDown(i, rawButtonVal);
  21682. }
  21683. else if (rawButtonVal === 0)
  21684. {
  21685. this.processButtonUp(i, rawButtonVal);
  21686. }
  21687. else
  21688. {
  21689. this.processButtonFloat(i, rawButtonVal);
  21690. }
  21691. }
  21692. }
  21693. for (var j = 0; j < this._axesLen; j++)
  21694. {
  21695. var axis = this._rawPad.axes[j];
  21696. if (axis > 0 && axis > this.deadZone || axis < 0 && axis < -this.deadZone)
  21697. {
  21698. this.processAxisChange( { axis: j, value: axis } );
  21699. }
  21700. else
  21701. {
  21702. this.processAxisChange( { axis: j, value: 0 } );
  21703. }
  21704. }
  21705. this._prevTimestamp = this._rawPad.timestamp;
  21706. },
  21707. /**
  21708. * Gamepad connect function, should be called by Phaser.Gamepad.
  21709. *
  21710. * @method Phaser.SinglePad#connect
  21711. * @param {Object} rawPad - The raw gamepad object
  21712. */
  21713. connect: function (rawPad) {
  21714. var triggerCallback = !this.connected;
  21715. this.connected = true;
  21716. this.index = rawPad.index;
  21717. this._rawPad = rawPad;
  21718. this._buttons = [];
  21719. this._buttonsLen = rawPad.buttons.length;
  21720. this._axes = rawPad.axes;
  21721. this._axesLen = rawPad.axes.length;
  21722. for (var buttonCode in rawPad.buttons)
  21723. {
  21724. buttonCode = parseInt(buttonCode, 10);
  21725. this._buttons[buttonCode] = new Phaser.GamepadButton(this, buttonCode);
  21726. }
  21727. if (triggerCallback && this._padParent.onConnectCallback)
  21728. {
  21729. this._padParent.onConnectCallback.call(this._padParent.callbackContext, this.index);
  21730. }
  21731. if (triggerCallback && this.onConnectCallback)
  21732. {
  21733. this.onConnectCallback.call(this.callbackContext);
  21734. }
  21735. },
  21736. /**
  21737. * Gamepad disconnect function, should be called by Phaser.Gamepad.
  21738. *
  21739. * @method Phaser.SinglePad#disconnect
  21740. */
  21741. disconnect: function () {
  21742. var triggerCallback = this.connected;
  21743. var disconnectingIndex = this.index;
  21744. this.connected = false;
  21745. this.index = null;
  21746. this._rawPad = undefined;
  21747. for (var i = 0; i < this._buttonsLen; i++)
  21748. {
  21749. this._buttons[i].destroy();
  21750. }
  21751. this._buttons = [];
  21752. this._buttonsLen = 0;
  21753. this._axes = [];
  21754. this._axesLen = 0;
  21755. if (triggerCallback && this._padParent.onDisconnectCallback)
  21756. {
  21757. this._padParent.onDisconnectCallback.call(this._padParent.callbackContext, disconnectingIndex);
  21758. }
  21759. if (triggerCallback && this.onDisconnectCallback)
  21760. {
  21761. this.onDisconnectCallback.call(this.callbackContext);
  21762. }
  21763. },
  21764. /**
  21765. * Handles changes in axis.
  21766. *
  21767. * @method Phaser.SinglePad#processAxisChange
  21768. * @param {Object} axisState - State of the relevant axis
  21769. */
  21770. processAxisChange: function (axisState) {
  21771. if (this._axes[axisState.axis] === axisState.value)
  21772. {
  21773. return;
  21774. }
  21775. this._axes[axisState.axis] = axisState.value;
  21776. if (this._padParent.onAxisCallback)
  21777. {
  21778. this._padParent.onAxisCallback.call(this._padParent.callbackContext, axisState, this.index);
  21779. }
  21780. if (this.onAxisCallback)
  21781. {
  21782. this.onAxisCallback.call(this.callbackContext, axisState);
  21783. }
  21784. },
  21785. /**
  21786. * Handles button down press.
  21787. *
  21788. * @method Phaser.SinglePad#processButtonDown
  21789. * @param {number} buttonCode - Which buttonCode of this button
  21790. * @param {Object} value - Button value
  21791. */
  21792. processButtonDown: function (buttonCode, value) {
  21793. if (this._padParent.onDownCallback)
  21794. {
  21795. this._padParent.onDownCallback.call(this._padParent.callbackContext, buttonCode, value, this.index);
  21796. }
  21797. if (this.onDownCallback)
  21798. {
  21799. this.onDownCallback.call(this.callbackContext, buttonCode, value);
  21800. }
  21801. if (this._buttons[buttonCode])
  21802. {
  21803. this._buttons[buttonCode].processButtonDown(value);
  21804. }
  21805. },
  21806. /**
  21807. * Handles button release.
  21808. *
  21809. * @method Phaser.SinglePad#processButtonUp
  21810. * @param {number} buttonCode - Which buttonCode of this button
  21811. * @param {Object} value - Button value
  21812. */
  21813. processButtonUp: function (buttonCode, value) {
  21814. if (this._padParent.onUpCallback)
  21815. {
  21816. this._padParent.onUpCallback.call(this._padParent.callbackContext, buttonCode, value, this.index);
  21817. }
  21818. if (this.onUpCallback)
  21819. {
  21820. this.onUpCallback.call(this.callbackContext, buttonCode, value);
  21821. }
  21822. if (this._buttons[buttonCode])
  21823. {
  21824. this._buttons[buttonCode].processButtonUp(value);
  21825. }
  21826. },
  21827. /**
  21828. * Handles buttons with floating values (like analog buttons that acts almost like an axis but still registers like a button)
  21829. *
  21830. * @method Phaser.SinglePad#processButtonFloat
  21831. * @param {number} buttonCode - Which buttonCode of this button
  21832. * @param {Object} value - Button value (will range somewhere between 0 and 1, but not specifically 0 or 1.
  21833. */
  21834. processButtonFloat: function (buttonCode, value) {
  21835. if (this._padParent.onFloatCallback)
  21836. {
  21837. this._padParent.onFloatCallback.call(this._padParent.callbackContext, buttonCode, value, this.index);
  21838. }
  21839. if (this.onFloatCallback)
  21840. {
  21841. this.onFloatCallback.call(this.callbackContext, buttonCode, value);
  21842. }
  21843. if (this._buttons[buttonCode])
  21844. {
  21845. this._buttons[buttonCode].processButtonFloat(value);
  21846. }
  21847. },
  21848. /**
  21849. * Returns value of requested axis.
  21850. *
  21851. * @method Phaser.SinglePad#axis
  21852. * @param {number} axisCode - The index of the axis to check
  21853. * @return {number} Axis value if available otherwise false
  21854. */
  21855. axis: function (axisCode) {
  21856. if (this._axes[axisCode])
  21857. {
  21858. return this._axes[axisCode];
  21859. }
  21860. return false;
  21861. },
  21862. /**
  21863. * Returns true if the button is pressed down.
  21864. *
  21865. * @method Phaser.SinglePad#isDown
  21866. * @param {number} buttonCode - The buttonCode of the button to check.
  21867. * @return {boolean} True if the button is pressed down.
  21868. */
  21869. isDown: function (buttonCode) {
  21870. if (this._buttons[buttonCode])
  21871. {
  21872. return this._buttons[buttonCode].isDown;
  21873. }
  21874. return false;
  21875. },
  21876. /**
  21877. * Returns true if the button is not currently pressed.
  21878. *
  21879. * @method Phaser.SinglePad#isUp
  21880. * @param {number} buttonCode - The buttonCode of the button to check.
  21881. * @return {boolean} True if the button is not currently pressed down.
  21882. */
  21883. isUp: function (buttonCode) {
  21884. if (this._buttons[buttonCode])
  21885. {
  21886. return this._buttons[buttonCode].isUp;
  21887. }
  21888. return false;
  21889. },
  21890. /**
  21891. * 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).
  21892. *
  21893. * @method Phaser.SinglePad#justReleased
  21894. * @param {number} buttonCode - The buttonCode of the button to check for.
  21895. * @param {number} [duration=250] - The duration below which the button is considered as being just released.
  21896. * @return {boolean} True if the button is just released otherwise false.
  21897. */
  21898. justReleased: function (buttonCode, duration) {
  21899. if (this._buttons[buttonCode])
  21900. {
  21901. return this._buttons[buttonCode].justReleased(duration);
  21902. }
  21903. },
  21904. /**
  21905. * 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).
  21906. *
  21907. * @method Phaser.SinglePad#justPressed
  21908. * @param {number} buttonCode - The buttonCode of the button to check for.
  21909. * @param {number} [duration=250] - The duration below which the button is considered as being just pressed.
  21910. * @return {boolean} True if the button is just pressed otherwise false.
  21911. */
  21912. justPressed: function (buttonCode, duration) {
  21913. if (this._buttons[buttonCode])
  21914. {
  21915. return this._buttons[buttonCode].justPressed(duration);
  21916. }
  21917. },
  21918. /**
  21919. * Returns the value of a gamepad button. Intended mainly for cases when you have floating button values, for example
  21920. * analog trigger buttons on the XBOX 360 controller.
  21921. *
  21922. * @method Phaser.SinglePad#buttonValue
  21923. * @param {number} buttonCode - The buttonCode of the button to check.
  21924. * @return {number} Button value if available otherwise null. Be careful as this can incorrectly evaluate to 0.
  21925. */
  21926. buttonValue: function (buttonCode) {
  21927. if (this._buttons[buttonCode])
  21928. {
  21929. return this._buttons[buttonCode].value;
  21930. }
  21931. return null;
  21932. },
  21933. /**
  21934. * Reset all buttons/axes of this gamepad.
  21935. *
  21936. * @method Phaser.SinglePad#reset
  21937. */
  21938. reset: function () {
  21939. for (var j = 0; j < this._axes.length; j++)
  21940. {
  21941. this._axes[j] = 0;
  21942. }
  21943. }
  21944. };
  21945. Phaser.SinglePad.prototype.constructor = Phaser.SinglePad;
  21946. /**
  21947. * @author @karlmacklin <tacklemcclean@gmail.com>
  21948. * @author Richard Davey <rich@photonstorm.com>
  21949. * @copyright 2014 Photon Storm Ltd.
  21950. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  21951. */
  21952. /**
  21953. * @class Phaser.GamepadButton
  21954. * @classdesc If you need more fine-grained control over the handling of specific buttons you can create and use Phaser.GamepadButton objects.
  21955. * @constructor
  21956. * @param {Phaser.SinglePad} pad - A reference to the gamepad that owns this button.
  21957. * @param {number} buttonCode - The button code this GamepadButton is responsible for.
  21958. */
  21959. Phaser.GamepadButton = function (pad, buttonCode) {
  21960. /**
  21961. * @property {Phaser.SinglePad} pad - A reference to the gamepad that owns this button.
  21962. */
  21963. this.pad = pad;
  21964. /**
  21965. * @property {Phaser.Game} game - A reference to the currently running game.
  21966. */
  21967. this.game = pad.game;
  21968. /**
  21969. * @property {boolean} isDown - The "down" state of the button.
  21970. * @default
  21971. */
  21972. this.isDown = false;
  21973. /**
  21974. * @property {boolean} isUp - The "up" state of the button.
  21975. * @default
  21976. */
  21977. this.isUp = true;
  21978. /**
  21979. * @property {number} timeDown - The timestamp when the button was last pressed down.
  21980. * @default
  21981. */
  21982. this.timeDown = 0;
  21983. /**
  21984. * If the button is down this value holds the duration of that button press and is constantly updated.
  21985. * If the button is up it holds the duration of the previous down session.
  21986. * @property {number} duration - The number of milliseconds this button has been held down for.
  21987. * @default
  21988. */
  21989. this.duration = 0;
  21990. /**
  21991. * @property {number} timeUp - The timestamp when the button was last released.
  21992. * @default
  21993. */
  21994. this.timeUp = 0;
  21995. /**
  21996. * @property {number} repeats - If a button is held down this holds down the number of times the button has 'repeated'.
  21997. * @default
  21998. */
  21999. this.repeats = 0;
  22000. /**
  22001. * @property {number} value - Button value. Mainly useful for checking analog buttons (like shoulder triggers)
  22002. * @default
  22003. */
  22004. this.value = 0;
  22005. /**
  22006. * @property {number} buttonCode - The buttoncode of this button.
  22007. */
  22008. this.buttonCode = buttonCode;
  22009. /**
  22010. * @property {Phaser.Signal} onDown - This Signal is dispatched every time this GamepadButton is pressed down. It is only dispatched once (until the button is released again).
  22011. */
  22012. this.onDown = new Phaser.Signal();
  22013. /**
  22014. * @property {Phaser.Signal} onUp - This Signal is dispatched every time this GamepadButton is pressed down. It is only dispatched once (until the button is released again).
  22015. */
  22016. this.onUp = new Phaser.Signal();
  22017. /**
  22018. * @property {Phaser.Signal} onFloat - This Signal is dispatched every time this GamepadButton changes floating value (between (but not exactly) 0 and 1)
  22019. */
  22020. this.onFloat = new Phaser.Signal();
  22021. };
  22022. Phaser.GamepadButton.prototype = {
  22023. /**
  22024. * Called automatically by Phaser.SinglePad.
  22025. *
  22026. * @method Phaser.GamepadButton#processButtonDown
  22027. * @protected
  22028. * @param {number} value - Button value
  22029. */
  22030. processButtonDown: function (value) {
  22031. if (this.isDown)
  22032. {
  22033. this.duration = this.game.time.now - this.timeDown;
  22034. this.repeats++;
  22035. }
  22036. else
  22037. {
  22038. this.isDown = true;
  22039. this.isUp = false;
  22040. this.timeDown = this.game.time.now;
  22041. this.duration = 0;
  22042. this.repeats = 0;
  22043. this.value = value;
  22044. this.onDown.dispatch(this, value);
  22045. }
  22046. },
  22047. /**
  22048. * Called automatically by Phaser.SinglePad.
  22049. *
  22050. * @method Phaser.GamepadButton#processButtonUp
  22051. * @protected
  22052. * @param {number} value - Button value
  22053. */
  22054. processButtonUp: function (value) {
  22055. if (this.isDown)
  22056. {
  22057. this.isDown = false;
  22058. this.isUp = true;
  22059. this.timeUp = this.game.time.now;
  22060. this.value = value;
  22061. this.onUp.dispatch(this, value);
  22062. }
  22063. },
  22064. /**
  22065. * Called automatically by Phaser.SinglePad.
  22066. *
  22067. * @method Phaser.GamepadButton#processButtonFloat
  22068. * @protected
  22069. * @param {number} value - Button value
  22070. */
  22071. processButtonFloat: function (value) {
  22072. this.value = value;
  22073. this.onFloat.dispatch(this, value);
  22074. },
  22075. /**
  22076. * Returns the "just pressed" state of this button. Just pressed is considered true if the button was pressed down within the duration given (default 250ms).
  22077. *
  22078. * @method Phaser.GamepadButton#justPressed
  22079. * @param {number} [duration=250] - The duration below which the button is considered as being just pressed.
  22080. * @return {boolean} True if the button is just pressed otherwise false.
  22081. */
  22082. justPressed: function (duration) {
  22083. if (typeof duration === "undefined") { duration = 250; }
  22084. return (this.isDown && this.duration < duration);
  22085. },
  22086. /**
  22087. * Returns the "just released" state of this button. Just released is considered as being true if the button was released within the duration given (default 250ms).
  22088. *
  22089. * @method Phaser.GamepadButton#justPressed
  22090. * @param {number} [duration=250] - The duration below which the button is considered as being just released.
  22091. * @return {boolean} True if the button is just pressed otherwise false.
  22092. */
  22093. justReleased: function (duration) {
  22094. if (typeof duration === "undefined") { duration = 250; }
  22095. return (this.isDown === false && (this.game.time.now - this.timeUp < duration));
  22096. },
  22097. /**
  22098. * Resets this GamepadButton, changing it to an isUp state and resetting the duration and repeats counters.
  22099. *
  22100. * @method Phaser.GamepadButton#reset
  22101. */
  22102. reset: function () {
  22103. this.isDown = false;
  22104. this.isUp = true;
  22105. this.timeDown = this.game.time.now;
  22106. this.duration = 0;
  22107. this.repeats = 0;
  22108. },
  22109. /**
  22110. * Destroys this GamepadButton, this disposes of the onDown, onUp and onFloat signals and clears the pad and game references.
  22111. *
  22112. * @method Phaser.GamepadButton#destroy
  22113. */
  22114. destroy: function () {
  22115. this.onDown.dispose();
  22116. this.onUp.dispose();
  22117. this.onFloat.dispose();
  22118. this.pad = null;
  22119. this.game = null;
  22120. }
  22121. };
  22122. Phaser.GamepadButton.prototype.constructor = Phaser.GamepadButton;
  22123. /**
  22124. * @author Richard Davey <rich@photonstorm.com>
  22125. * @copyright 2014 Photon Storm Ltd.
  22126. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  22127. */
  22128. /**
  22129. * The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite.
  22130. * @class Phaser.InputHandler
  22131. * @constructor
  22132. * @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs.
  22133. */
  22134. Phaser.InputHandler = function (sprite) {
  22135. /**
  22136. * @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs.
  22137. */
  22138. this.sprite = sprite;
  22139. /**
  22140. * @property {Phaser.Game} game - A reference to the currently running game.
  22141. */
  22142. this.game = sprite.game;
  22143. /**
  22144. * @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity.
  22145. * @default
  22146. */
  22147. this.enabled = false;
  22148. /**
  22149. * @property {boolean} checked - A disposable flag used by the Pointer class when performing priority checks.
  22150. * @protected
  22151. */
  22152. this.checked = false;
  22153. /**
  22154. * The priorityID is used to determine which game objects should get priority when input events occur. For example if you have
  22155. * several Sprites that overlap, by default the one at the top of the display list is given priority for input events. You can
  22156. * stop this from happening by controlling the priorityID value. The higher the value, the more important they are considered to the Input events.
  22157. * @property {number} priorityID
  22158. * @default
  22159. */
  22160. this.priorityID = 0;
  22161. /**
  22162. * @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite.
  22163. * @default
  22164. */
  22165. this.useHandCursor = false;
  22166. /**
  22167. * @property {boolean} _setHandCursor - Did this Sprite trigger the hand cursor?
  22168. * @private
  22169. */
  22170. this._setHandCursor = false;
  22171. /**
  22172. * @property {boolean} isDragged - true if the Sprite is being currently dragged.
  22173. * @default
  22174. */
  22175. this.isDragged = false;
  22176. /**
  22177. * @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally.
  22178. * @default
  22179. */
  22180. this.allowHorizontalDrag = true;
  22181. /**
  22182. * @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically.
  22183. * @default
  22184. */
  22185. this.allowVerticalDrag = true;
  22186. /**
  22187. * @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.
  22188. * @default
  22189. */
  22190. this.bringToTop = false;
  22191. /**
  22192. * @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset.
  22193. * @default
  22194. */
  22195. this.snapOffset = null;
  22196. /**
  22197. * @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.
  22198. * @default
  22199. */
  22200. this.snapOnDrag = false;
  22201. /**
  22202. * @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release.
  22203. * @default
  22204. */
  22205. this.snapOnRelease = false;
  22206. /**
  22207. * @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid.
  22208. * @default
  22209. */
  22210. this.snapX = 0;
  22211. /**
  22212. * @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid.
  22213. * @default
  22214. */
  22215. this.snapY = 0;
  22216. /**
  22217. * @property {number} snapOffsetX - This defines the top-left X coordinate of the snap grid.
  22218. * @default
  22219. */
  22220. this.snapOffsetX = 0;
  22221. /**
  22222. * @property {number} snapOffsetY - This defines the top-left Y coordinate of the snap grid..
  22223. * @default
  22224. */
  22225. this.snapOffsetY = 0;
  22226. /**
  22227. * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite.
  22228. * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value.
  22229. * 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.
  22230. * @property {number} pixelPerfectOver - Use a pixel perfect check when testing for pointer over.
  22231. * @default
  22232. */
  22233. this.pixelPerfectOver = false;
  22234. /**
  22235. * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched.
  22236. * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value.
  22237. * Warning: This is expensive so only enable if you really need it.
  22238. * @property {number} pixelPerfectClick - Use a pixel perfect check when testing for clicks or touches on the Sprite.
  22239. * @default
  22240. */
  22241. this.pixelPerfectClick = false;
  22242. /**
  22243. * @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.
  22244. * @default
  22245. */
  22246. this.pixelPerfectAlpha = 255;
  22247. /**
  22248. * @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no
  22249. * @default
  22250. */
  22251. this.draggable = false;
  22252. /**
  22253. * @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag.
  22254. * @default
  22255. */
  22256. this.boundsRect = null;
  22257. /**
  22258. * @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag.
  22259. * @default
  22260. */
  22261. this.boundsSprite = null;
  22262. /**
  22263. * If this object is set to consume the pointer event then it will stop all propogation from this object on.
  22264. * For example if you had a stack of 6 sprites with the same priority IDs and one consumed the event, none of the others would receive it.
  22265. * @property {boolean} consumePointerEvent
  22266. * @default
  22267. */
  22268. this.consumePointerEvent = false;
  22269. /**
  22270. * @property {boolean} _dragPhase - Internal cache var.
  22271. * @private
  22272. */
  22273. this._dragPhase = false;
  22274. /**
  22275. * @property {boolean} _wasEnabled - Internal cache var.
  22276. * @private
  22277. */
  22278. this._wasEnabled = false;
  22279. /**
  22280. * @property {Phaser.Point} _tempPoint - Internal cache var.
  22281. * @private
  22282. */
  22283. this._tempPoint = new Phaser.Point();
  22284. /**
  22285. * @property {array} _pointerData - Internal cache var.
  22286. * @private
  22287. */
  22288. this._pointerData = [];
  22289. this._pointerData.push({
  22290. id: 0,
  22291. x: 0,
  22292. y: 0,
  22293. isDown: false,
  22294. isUp: false,
  22295. isOver: false,
  22296. isOut: false,
  22297. timeOver: 0,
  22298. timeOut: 0,
  22299. timeDown: 0,
  22300. timeUp: 0,
  22301. downDuration: 0,
  22302. isDragged: false
  22303. });
  22304. };
  22305. Phaser.InputHandler.prototype = {
  22306. /**
  22307. * 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.
  22308. * @method Phaser.InputHandler#start
  22309. * @param {number} priority - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other.
  22310. * @param {boolean} useHandCursor - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers)
  22311. * @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound.
  22312. */
  22313. start: function (priority, useHandCursor) {
  22314. priority = priority || 0;
  22315. if (typeof useHandCursor === 'undefined') { useHandCursor = false; }
  22316. // Turning on
  22317. if (this.enabled === false)
  22318. {
  22319. // Register, etc
  22320. this.game.input.interactiveItems.add(this);
  22321. this.useHandCursor = useHandCursor;
  22322. this.priorityID = priority;
  22323. for (var i = 0; i < 10; i++)
  22324. {
  22325. this._pointerData[i] = {
  22326. id: i,
  22327. x: 0,
  22328. y: 0,
  22329. isDown: false,
  22330. isUp: false,
  22331. isOver: false,
  22332. isOut: false,
  22333. timeOver: 0,
  22334. timeOut: 0,
  22335. timeDown: 0,
  22336. timeUp: 0,
  22337. downDuration: 0,
  22338. isDragged: false
  22339. };
  22340. }
  22341. this.snapOffset = new Phaser.Point();
  22342. this.enabled = true;
  22343. this._wasEnabled = true;
  22344. // Create the signals the Input component will emit
  22345. if (this.sprite.events && this.sprite.events.onInputOver === null)
  22346. {
  22347. this.sprite.events.onInputOver = new Phaser.Signal();
  22348. this.sprite.events.onInputOut = new Phaser.Signal();
  22349. this.sprite.events.onInputDown = new Phaser.Signal();
  22350. this.sprite.events.onInputUp = new Phaser.Signal();
  22351. this.sprite.events.onDragStart = new Phaser.Signal();
  22352. this.sprite.events.onDragStop = new Phaser.Signal();
  22353. }
  22354. }
  22355. this.sprite.events.onAddedToGroup.add(this.addedToGroup, this);
  22356. this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup, this);
  22357. this.flagged = false;
  22358. return this.sprite;
  22359. },
  22360. /**
  22361. * Handles when the parent Sprite is added to a new Group.
  22362. *
  22363. * @method Phaser.InputHandler#addedToGroup
  22364. * @private
  22365. */
  22366. addedToGroup: function () {
  22367. if (this._dragPhase)
  22368. {
  22369. return;
  22370. }
  22371. if (this._wasEnabled && !this.enabled)
  22372. {
  22373. this.start();
  22374. }
  22375. },
  22376. /**
  22377. * Handles when the parent Sprite is removed from a Group.
  22378. *
  22379. * @method Phaser.InputHandler#removedFromGroup
  22380. * @private
  22381. */
  22382. removedFromGroup: function () {
  22383. if (this._dragPhase)
  22384. {
  22385. return;
  22386. }
  22387. if (this.enabled)
  22388. {
  22389. this._wasEnabled = true;
  22390. this.stop();
  22391. }
  22392. else
  22393. {
  22394. this._wasEnabled = false;
  22395. }
  22396. },
  22397. /**
  22398. * Resets the Input Handler and disables it.
  22399. * @method Phaser.InputHandler#reset
  22400. */
  22401. reset: function () {
  22402. this.enabled = false;
  22403. this.flagged = false;
  22404. for (var i = 0; i < 10; i++)
  22405. {
  22406. this._pointerData[i] = {
  22407. id: i,
  22408. x: 0,
  22409. y: 0,
  22410. isDown: false,
  22411. isUp: false,
  22412. isOver: false,
  22413. isOut: false,
  22414. timeOver: 0,
  22415. timeOut: 0,
  22416. timeDown: 0,
  22417. timeUp: 0,
  22418. downDuration: 0,
  22419. isDragged: false
  22420. };
  22421. }
  22422. },
  22423. /**
  22424. * Stops the Input Handler from running.
  22425. * @method Phaser.InputHandler#stop
  22426. */
  22427. stop: function () {
  22428. // Turning off
  22429. if (this.enabled === false)
  22430. {
  22431. return;
  22432. }
  22433. else
  22434. {
  22435. // De-register, etc
  22436. this.enabled = false;
  22437. this.game.input.interactiveItems.remove(this);
  22438. }
  22439. },
  22440. /**
  22441. * Clean up memory.
  22442. * @method Phaser.InputHandler#destroy
  22443. */
  22444. destroy: function () {
  22445. if (this.sprite)
  22446. {
  22447. if (this._setHandCursor)
  22448. {
  22449. this.game.canvas.style.cursor = "default";
  22450. this._setHandCursor = false;
  22451. }
  22452. this.enabled = false;
  22453. this.game.input.interactiveItems.remove(this);
  22454. this._pointerData.length = 0;
  22455. this.boundsRect = null;
  22456. this.boundsSprite = null;
  22457. this.sprite = null;
  22458. }
  22459. },
  22460. /**
  22461. * Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event.
  22462. * This is called by Phaser.Pointer and shouldn't typically be called directly.
  22463. *
  22464. * @method Phaser.InputHandler#validForInput
  22465. * @protected
  22466. * @param {number} highestID - The highest ID currently processed by the Pointer.
  22467. * @param {number} highestRenderID - The highest Render Order ID currently processed by the Pointer.
  22468. * @param {boolean} [includePixelPerfect=true] - If this object has `pixelPerfectClick` or `pixelPerfectOver` set should it be considered as valid?
  22469. * @return {boolean} True if the object this InputHandler is bound to should be considered as valid for input detection.
  22470. */
  22471. validForInput: function (highestID, highestRenderID, includePixelPerfect) {
  22472. if (typeof includePixelPerfect === 'undefined') { includePixelPerfect = true; }
  22473. if (this.sprite.scale.x === 0 || this.sprite.scale.y === 0 || this.priorityID < this.game.input.minPriorityID)
  22474. {
  22475. return false;
  22476. }
  22477. // If we're trying to specifically IGNORE pixel perfect objects, then set includePixelPerfect to false and skip it
  22478. if (!includePixelPerfect && (this.pixelPerfectClick || this.pixelPerfectOver))
  22479. {
  22480. return false;
  22481. }
  22482. if (this.priorityID > highestID || (this.priorityID === highestID && this.sprite._cache[3] < highestRenderID))
  22483. {
  22484. return true;
  22485. }
  22486. return false;
  22487. },
  22488. /**
  22489. * Is this object using pixel perfect checking?
  22490. *
  22491. * @method Phaser.InputHandler#isPixelPerfect
  22492. * @return {boolean} True if the this InputHandler has either `pixelPerfectClick` or `pixelPerfectOver` set to `true`.
  22493. */
  22494. isPixelPerfect: function () {
  22495. return (this.pixelPerfectClick || this.pixelPerfectOver);
  22496. },
  22497. /**
  22498. * The x coordinate of the Input pointer, relative to the top-left of the parent Sprite.
  22499. * This value is only set when the pointer is over this Sprite.
  22500. * @method Phaser.InputHandler#pointerX
  22501. * @param {Phaser.Pointer} pointer
  22502. * @return {number} The x coordinate of the Input pointer.
  22503. */
  22504. pointerX: function (pointer) {
  22505. pointer = pointer || 0;
  22506. return this._pointerData[pointer].x;
  22507. },
  22508. /**
  22509. * The y coordinate of the Input pointer, relative to the top-left of the parent Sprite
  22510. * This value is only set when the pointer is over this Sprite.
  22511. * @method Phaser.InputHandler#pointerY
  22512. * @param {Phaser.Pointer} pointer
  22513. * @return {number} The y coordinate of the Input pointer.
  22514. */
  22515. pointerY: function (pointer) {
  22516. pointer = pointer || 0;
  22517. return this._pointerData[pointer].y;
  22518. },
  22519. /**
  22520. * If the Pointer is touching the touchscreen, or the mouse button is held down, isDown is set to true.
  22521. * @method Phaser.InputHandler#pointerDown
  22522. * @param {Phaser.Pointer} pointer
  22523. * @return {boolean}
  22524. */
  22525. pointerDown: function (pointer) {
  22526. pointer = pointer || 0;
  22527. return this._pointerData[pointer].isDown;
  22528. },
  22529. /**
  22530. * If the Pointer is not touching the touchscreen, or the mouse button is up, isUp is set to true
  22531. * @method Phaser.InputHandler#pointerUp
  22532. * @param {Phaser.Pointer} pointer
  22533. * @return {boolean}
  22534. */
  22535. pointerUp: function (pointer) {
  22536. pointer = pointer || 0;
  22537. return this._pointerData[pointer].isUp;
  22538. },
  22539. /**
  22540. * A timestamp representing when the Pointer first touched the touchscreen.
  22541. * @method Phaser.InputHandler#pointerTimeDown
  22542. * @param {Phaser.Pointer} pointer
  22543. * @return {number}
  22544. */
  22545. pointerTimeDown: function (pointer) {
  22546. pointer = pointer || 0;
  22547. return this._pointerData[pointer].timeDown;
  22548. },
  22549. /**
  22550. * A timestamp representing when the Pointer left the touchscreen.
  22551. * @method Phaser.InputHandler#pointerTimeUp
  22552. * @param {Phaser.Pointer} pointer
  22553. * @return {number}
  22554. */
  22555. pointerTimeUp: function (pointer) {
  22556. pointer = pointer || 0;
  22557. return this._pointerData[pointer].timeUp;
  22558. },
  22559. /**
  22560. * Is the Pointer over this Sprite?
  22561. * @method Phaser.InputHandler#pointerOver
  22562. * @param {number} [index] - The ID number of a Pointer to check. If you don't provide a number it will check all Pointers.
  22563. * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is over this object.
  22564. */
  22565. pointerOver: function (index) {
  22566. if (this.enabled)
  22567. {
  22568. if (typeof index === 'undefined')
  22569. {
  22570. for (var i = 0; i < 10; i++)
  22571. {
  22572. if (this._pointerData[i].isOver)
  22573. {
  22574. return true;
  22575. }
  22576. }
  22577. }
  22578. else
  22579. {
  22580. return this._pointerData[index].isOver;
  22581. }
  22582. }
  22583. return false;
  22584. },
  22585. /**
  22586. * Is the Pointer outside of this Sprite?
  22587. * @method Phaser.InputHandler#pointerOut
  22588. * @param {number} [index] - The ID number of a Pointer to check. If you don't provide a number it will check all Pointers.
  22589. * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object.
  22590. */
  22591. pointerOut: function (index) {
  22592. if (this.enabled)
  22593. {
  22594. if (typeof index === 'undefined')
  22595. {
  22596. for (var i = 0; i < 10; i++)
  22597. {
  22598. if (this._pointerData[i].isOut)
  22599. {
  22600. return true;
  22601. }
  22602. }
  22603. }
  22604. else
  22605. {
  22606. return this._pointerData[index].isOut;
  22607. }
  22608. }
  22609. return false;
  22610. },
  22611. /**
  22612. * A timestamp representing when the Pointer first touched the touchscreen.
  22613. * @method Phaser.InputHandler#pointerTimeOver
  22614. * @param {Phaser.Pointer} pointer
  22615. * @return {number}
  22616. */
  22617. pointerTimeOver: function (pointer) {
  22618. pointer = pointer || 0;
  22619. return this._pointerData[pointer].timeOver;
  22620. },
  22621. /**
  22622. * A timestamp representing when the Pointer left the touchscreen.
  22623. * @method Phaser.InputHandler#pointerTimeOut
  22624. * @param {Phaser.Pointer} pointer
  22625. * @return {number}
  22626. */
  22627. pointerTimeOut: function (pointer) {
  22628. pointer = pointer || 0;
  22629. return this._pointerData[pointer].timeOut;
  22630. },
  22631. /**
  22632. * Is this sprite being dragged by the mouse or not?
  22633. * @method Phaser.InputHandler#pointerDragged
  22634. * @param {Phaser.Pointer} pointer
  22635. * @return {boolean} True if the pointer is dragging an object, otherwise false.
  22636. */
  22637. pointerDragged: function (pointer) {
  22638. pointer = pointer || 0;
  22639. return this._pointerData[pointer].isDragged;
  22640. },
  22641. /**
  22642. * Checks if the given pointer is both down and over the Sprite this InputHandler belongs to.
  22643. * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`.
  22644. *
  22645. * @method Phaser.InputHandler#checkPointerDown
  22646. * @param {Phaser.Pointer} pointer
  22647. * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object?
  22648. * @return {boolean} True if the pointer is down, otherwise false.
  22649. */
  22650. checkPointerDown: function (pointer, fastTest) {
  22651. if (!pointer.isDown || !this.enabled || !this.sprite || !this.sprite.parent || !this.sprite.visible || !this.sprite.parent.visible)
  22652. {
  22653. return false;
  22654. }
  22655. // Need to pass it a temp point, in case we need it again for the pixel check
  22656. if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint))
  22657. {
  22658. if (typeof fastTest === 'undefined') { fastTest = false; }
  22659. if (!fastTest && this.pixelPerfectClick)
  22660. {
  22661. return this.checkPixel(this._tempPoint.x, this._tempPoint.y);
  22662. }
  22663. else
  22664. {
  22665. return true;
  22666. }
  22667. }
  22668. return false;
  22669. },
  22670. /**
  22671. * Checks if the given pointer is over the Sprite this InputHandler belongs to.
  22672. * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`.
  22673. *
  22674. * @method Phaser.InputHandler#checkPointerOver
  22675. * @param {Phaser.Pointer} pointer
  22676. * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object?
  22677. * @return {boolean}
  22678. */
  22679. checkPointerOver: function (pointer, fastTest) {
  22680. if (!this.enabled || !this.sprite || !this.sprite.parent || !this.sprite.visible || !this.sprite.parent.visible)
  22681. {
  22682. return false;
  22683. }
  22684. // Need to pass it a temp point, in case we need it again for the pixel check
  22685. if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint))
  22686. {
  22687. if (typeof fastTest === 'undefined') { fastTest = false; }
  22688. if (!fastTest && this.pixelPerfectOver)
  22689. {
  22690. return this.checkPixel(this._tempPoint.x, this._tempPoint.y);
  22691. }
  22692. else
  22693. {
  22694. return true;
  22695. }
  22696. }
  22697. return false;
  22698. },
  22699. /**
  22700. * Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to.
  22701. * It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true.
  22702. * @method Phaser.InputHandler#checkPixel
  22703. * @param {number} x - The x coordinate to check.
  22704. * @param {number} y - The y coordinate to check.
  22705. * @param {Phaser.Pointer} [pointer] - The pointer to get the x/y coordinate from if not passed as the first two parameters.
  22706. * @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha
  22707. */
  22708. checkPixel: function (x, y, pointer) {
  22709. // Grab a pixel from our image into the hitCanvas and then test it
  22710. if (this.sprite.texture.baseTexture.source)
  22711. {
  22712. this.game.input.hitContext.clearRect(0, 0, 1, 1);
  22713. if (x === null && y === null)
  22714. {
  22715. // Use the pointer parameter
  22716. this.game.input.getLocalPosition(this.sprite, pointer, this._tempPoint);
  22717. var x = this._tempPoint.x;
  22718. var y = this._tempPoint.y;
  22719. }
  22720. if (this.sprite.anchor.x !== 0)
  22721. {
  22722. x -= -this.sprite.texture.frame.width * this.sprite.anchor.x;
  22723. }
  22724. if (this.sprite.anchor.y !== 0)
  22725. {
  22726. y -= -this.sprite.texture.frame.height * this.sprite.anchor.y;
  22727. }
  22728. x += this.sprite.texture.frame.x;
  22729. y += this.sprite.texture.frame.y;
  22730. this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source, x, y, 1, 1, 0, 0, 1, 1);
  22731. var rgb = this.game.input.hitContext.getImageData(0, 0, 1, 1);
  22732. if (rgb.data[3] >= this.pixelPerfectAlpha)
  22733. {
  22734. return true;
  22735. }
  22736. }
  22737. return false;
  22738. },
  22739. /**
  22740. * Update.
  22741. * @method Phaser.InputHandler#update
  22742. * @protected
  22743. * @param {Phaser.Pointer} pointer
  22744. */
  22745. update: function (pointer) {
  22746. if (this.sprite === null || this.sprite.parent === undefined)
  22747. {
  22748. // Abort. We've been destroyed.
  22749. return;
  22750. }
  22751. if (!this.enabled || !this.sprite.visible || !this.sprite.parent.visible)
  22752. {
  22753. this._pointerOutHandler(pointer);
  22754. return false;
  22755. }
  22756. if (this.draggable && this._draggedPointerID == pointer.id)
  22757. {
  22758. return this.updateDrag(pointer);
  22759. }
  22760. else if (this._pointerData[pointer.id].isOver === true)
  22761. {
  22762. if (this.checkPointerOver(pointer))
  22763. {
  22764. this._pointerData[pointer.id].x = pointer.x - this.sprite.x;
  22765. this._pointerData[pointer.id].y = pointer.y - this.sprite.y;
  22766. return true;
  22767. }
  22768. else
  22769. {
  22770. this._pointerOutHandler(pointer);
  22771. return false;
  22772. }
  22773. }
  22774. },
  22775. /**
  22776. * Internal method handling the pointer over event.
  22777. * @method Phaser.InputHandler#_pointerOverHandler
  22778. * @private
  22779. * @param {Phaser.Pointer} pointer
  22780. */
  22781. _pointerOverHandler: function (pointer) {
  22782. if (this.sprite === null)
  22783. {
  22784. // Abort. We've been destroyed.
  22785. return;
  22786. }
  22787. if (this._pointerData[pointer.id].isOver === false)
  22788. {
  22789. this._pointerData[pointer.id].isOver = true;
  22790. this._pointerData[pointer.id].isOut = false;
  22791. this._pointerData[pointer.id].timeOver = this.game.time.now;
  22792. this._pointerData[pointer.id].x = pointer.x - this.sprite.x;
  22793. this._pointerData[pointer.id].y = pointer.y - this.sprite.y;
  22794. if (this.useHandCursor && this._pointerData[pointer.id].isDragged === false)
  22795. {
  22796. this.game.canvas.style.cursor = "pointer";
  22797. this._setHandCursor = true;
  22798. }
  22799. if (this.sprite && this.sprite.events)
  22800. {
  22801. this.sprite.events.onInputOver.dispatch(this.sprite, pointer);
  22802. }
  22803. }
  22804. },
  22805. /**
  22806. * Internal method handling the pointer out event.
  22807. * @method Phaser.InputHandler#_pointerOutHandler
  22808. * @private
  22809. * @param {Phaser.Pointer} pointer
  22810. */
  22811. _pointerOutHandler: function (pointer) {
  22812. if (this.sprite === null)
  22813. {
  22814. // Abort. We've been destroyed.
  22815. return;
  22816. }
  22817. this._pointerData[pointer.id].isOver = false;
  22818. this._pointerData[pointer.id].isOut = true;
  22819. this._pointerData[pointer.id].timeOut = this.game.time.now;
  22820. if (this.useHandCursor && this._pointerData[pointer.id].isDragged === false)
  22821. {
  22822. this.game.canvas.style.cursor = "default";
  22823. this._setHandCursor = false;
  22824. }
  22825. if (this.sprite && this.sprite.events)
  22826. {
  22827. this.sprite.events.onInputOut.dispatch(this.sprite, pointer);
  22828. }
  22829. },
  22830. /**
  22831. * Internal method handling the touched event.
  22832. * @method Phaser.InputHandler#_touchedHandler
  22833. * @private
  22834. * @param {Phaser.Pointer} pointer
  22835. */
  22836. _touchedHandler: function (pointer) {
  22837. if (this.sprite === null)
  22838. {
  22839. // Abort. We've been destroyed.
  22840. return;
  22841. }
  22842. if (this._pointerData[pointer.id].isDown === false && this._pointerData[pointer.id].isOver === true)
  22843. {
  22844. if (this.pixelPerfectClick && !this.checkPixel(null, null, pointer))
  22845. {
  22846. return;
  22847. }
  22848. this._pointerData[pointer.id].isDown = true;
  22849. this._pointerData[pointer.id].isUp = false;
  22850. this._pointerData[pointer.id].timeDown = this.game.time.now;
  22851. if (this.sprite && this.sprite.events)
  22852. {
  22853. this.sprite.events.onInputDown.dispatch(this.sprite, pointer);
  22854. }
  22855. // Start drag
  22856. if (this.draggable && this.isDragged === false)
  22857. {
  22858. this.startDrag(pointer);
  22859. }
  22860. if (this.bringToTop)
  22861. {
  22862. this.sprite.bringToTop();
  22863. }
  22864. }
  22865. // Consume the event?
  22866. return this.consumePointerEvent;
  22867. },
  22868. /**
  22869. * Internal method handling the pointer released event.
  22870. * @method Phaser.InputHandler#_releasedHandler
  22871. * @private
  22872. * @param {Phaser.Pointer} pointer
  22873. */
  22874. _releasedHandler: function (pointer) {
  22875. if (this.sprite === null)
  22876. {
  22877. // Abort. We've been destroyed.
  22878. return;
  22879. }
  22880. // If was previously touched by this Pointer, check if still is AND still over this item
  22881. if (this._pointerData[pointer.id].isDown && pointer.isUp)
  22882. {
  22883. this._pointerData[pointer.id].isDown = false;
  22884. this._pointerData[pointer.id].isUp = true;
  22885. this._pointerData[pointer.id].timeUp = this.game.time.now;
  22886. this._pointerData[pointer.id].downDuration = this._pointerData[pointer.id].timeUp - this._pointerData[pointer.id].timeDown;
  22887. // Only release the InputUp signal if the pointer is still over this sprite
  22888. if (this.checkPointerOver(pointer))
  22889. {
  22890. // Release the inputUp signal and provide optional parameter if pointer is still over the sprite or not
  22891. if (this.sprite && this.sprite.events)
  22892. {
  22893. this.sprite.events.onInputUp.dispatch(this.sprite, pointer, true);
  22894. }
  22895. }
  22896. else
  22897. {
  22898. // Release the inputUp signal and provide optional parameter if pointer is still over the sprite or not
  22899. if (this.sprite && this.sprite.events)
  22900. {
  22901. this.sprite.events.onInputUp.dispatch(this.sprite, pointer, false);
  22902. }
  22903. // Pointer outside the sprite? Reset the cursor
  22904. if (this.useHandCursor)
  22905. {
  22906. this.game.canvas.style.cursor = "default";
  22907. this._setHandCursor = false;
  22908. }
  22909. }
  22910. // Stop drag
  22911. if (this.draggable && this.isDragged && this._draggedPointerID === pointer.id)
  22912. {
  22913. this.stopDrag(pointer);
  22914. }
  22915. }
  22916. },
  22917. /**
  22918. * Updates the Pointer drag on this Sprite.
  22919. * @method Phaser.InputHandler#updateDrag
  22920. * @param {Phaser.Pointer} pointer
  22921. * @return {boolean}
  22922. */
  22923. updateDrag: function (pointer) {
  22924. if (pointer.isUp)
  22925. {
  22926. this.stopDrag(pointer);
  22927. return false;
  22928. }
  22929. if (this.sprite.fixedToCamera)
  22930. {
  22931. if (this.allowHorizontalDrag)
  22932. {
  22933. this.sprite.cameraOffset.x = pointer.x + this._dragPoint.x + this.dragOffset.x;
  22934. }
  22935. if (this.allowVerticalDrag)
  22936. {
  22937. this.sprite.cameraOffset.y = pointer.y + this._dragPoint.y + this.dragOffset.y;
  22938. }
  22939. if (this.boundsRect)
  22940. {
  22941. this.checkBoundsRect();
  22942. }
  22943. if (this.boundsSprite)
  22944. {
  22945. this.checkBoundsSprite();
  22946. }
  22947. if (this.snapOnDrag)
  22948. {
  22949. this.sprite.cameraOffset.x = Math.round((this.sprite.cameraOffset.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
  22950. this.sprite.cameraOffset.y = Math.round((this.sprite.cameraOffset.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
  22951. }
  22952. }
  22953. else
  22954. {
  22955. if (this.allowHorizontalDrag)
  22956. {
  22957. this.sprite.x = pointer.x + this._dragPoint.x + this.dragOffset.x;
  22958. }
  22959. if (this.allowVerticalDrag)
  22960. {
  22961. this.sprite.y = pointer.y + this._dragPoint.y + this.dragOffset.y;
  22962. }
  22963. if (this.boundsRect)
  22964. {
  22965. this.checkBoundsRect();
  22966. }
  22967. if (this.boundsSprite)
  22968. {
  22969. this.checkBoundsSprite();
  22970. }
  22971. if (this.snapOnDrag)
  22972. {
  22973. this.sprite.x = Math.round((this.sprite.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
  22974. this.sprite.y = Math.round((this.sprite.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
  22975. }
  22976. }
  22977. return true;
  22978. },
  22979. /**
  22980. * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second)
  22981. * @method Phaser.InputHandler#justOver
  22982. * @param {Phaser.Pointer} pointer
  22983. * @param {number} delay - The time below which the pointer is considered as just over.
  22984. * @return {boolean}
  22985. */
  22986. justOver: function (pointer, delay) {
  22987. pointer = pointer || 0;
  22988. delay = delay || 500;
  22989. return (this._pointerData[pointer].isOver && this.overDuration(pointer) < delay);
  22990. },
  22991. /**
  22992. * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second)
  22993. * @method Phaser.InputHandler#justOut
  22994. * @param {Phaser.Pointer} pointer
  22995. * @param {number} delay - The time below which the pointer is considered as just out.
  22996. * @return {boolean}
  22997. */
  22998. justOut: function (pointer, delay) {
  22999. pointer = pointer || 0;
  23000. delay = delay || 500;
  23001. return (this._pointerData[pointer].isOut && (this.game.time.now - this._pointerData[pointer].timeOut < delay));
  23002. },
  23003. /**
  23004. * Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second)
  23005. * @method Phaser.InputHandler#justPressed
  23006. * @param {Phaser.Pointer} pointer
  23007. * @param {number} delay - The time below which the pointer is considered as just over.
  23008. * @return {boolean}
  23009. */
  23010. justPressed: function (pointer, delay) {
  23011. pointer = pointer || 0;
  23012. delay = delay || 500;
  23013. return (this._pointerData[pointer].isDown && this.downDuration(pointer) < delay);
  23014. },
  23015. /**
  23016. * Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second)
  23017. * @method Phaser.InputHandler#justReleased
  23018. * @param {Phaser.Pointer} pointer
  23019. * @param {number} delay - The time below which the pointer is considered as just out.
  23020. * @return {boolean}
  23021. */
  23022. justReleased: function (pointer, delay) {
  23023. pointer = pointer || 0;
  23024. delay = delay || 500;
  23025. return (this._pointerData[pointer].isUp && (this.game.time.now - this._pointerData[pointer].timeUp < delay));
  23026. },
  23027. /**
  23028. * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds.
  23029. * @method Phaser.InputHandler#overDuration
  23030. * @param {Phaser.Pointer} pointer
  23031. * @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over.
  23032. */
  23033. overDuration: function (pointer) {
  23034. pointer = pointer || 0;
  23035. if (this._pointerData[pointer].isOver)
  23036. {
  23037. return this.game.time.now - this._pointerData[pointer].timeOver;
  23038. }
  23039. return -1;
  23040. },
  23041. /**
  23042. * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds.
  23043. * @method Phaser.InputHandler#downDuration
  23044. * @param {Phaser.Pointer} pointer
  23045. * @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over.
  23046. */
  23047. downDuration: function (pointer) {
  23048. pointer = pointer || 0;
  23049. if (this._pointerData[pointer].isDown)
  23050. {
  23051. return this.game.time.now - this._pointerData[pointer].timeDown;
  23052. }
  23053. return -1;
  23054. },
  23055. /**
  23056. * Make this Sprite draggable by the mouse. You can also optionally set mouseStartDragCallback and mouseStopDragCallback
  23057. * @method Phaser.InputHandler#enableDrag
  23058. * @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.
  23059. * @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group.
  23060. * @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.
  23061. * @param {boolean} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed.
  23062. * @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.
  23063. * @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.
  23064. */
  23065. enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) {
  23066. if (typeof lockCenter == 'undefined') { lockCenter = false; }
  23067. if (typeof bringToTop == 'undefined') { bringToTop = false; }
  23068. if (typeof pixelPerfect == 'undefined') { pixelPerfect = false; }
  23069. if (typeof alphaThreshold == 'undefined') { alphaThreshold = 255; }
  23070. if (typeof boundsRect == 'undefined') { boundsRect = null; }
  23071. if (typeof boundsSprite == 'undefined') { boundsSprite = null; }
  23072. this._dragPoint = new Phaser.Point();
  23073. this.draggable = true;
  23074. this.bringToTop = bringToTop;
  23075. this.dragOffset = new Phaser.Point();
  23076. this.dragFromCenter = lockCenter;
  23077. this.pixelPerfectClick = pixelPerfect;
  23078. this.pixelPerfectAlpha = alphaThreshold;
  23079. if (boundsRect)
  23080. {
  23081. this.boundsRect = boundsRect;
  23082. }
  23083. if (boundsSprite)
  23084. {
  23085. this.boundsSprite = boundsSprite;
  23086. }
  23087. },
  23088. /**
  23089. * Stops this sprite from being able to be dragged. If it is currently the target of an active drag it will be stopped immediately. Also disables any set callbacks.
  23090. * @method Phaser.InputHandler#disableDrag
  23091. */
  23092. disableDrag: function () {
  23093. if (this._pointerData)
  23094. {
  23095. for (var i = 0; i < 10; i++)
  23096. {
  23097. this._pointerData[i].isDragged = false;
  23098. }
  23099. }
  23100. this.draggable = false;
  23101. this.isDragged = false;
  23102. this._draggedPointerID = -1;
  23103. },
  23104. /**
  23105. * Called by Pointer when drag starts on this Sprite. Should not usually be called directly.
  23106. * @method Phaser.InputHandler#startDrag
  23107. * @param {Phaser.Pointer} pointer
  23108. */
  23109. startDrag: function (pointer) {
  23110. this.isDragged = true;
  23111. this._draggedPointerID = pointer.id;
  23112. this._pointerData[pointer.id].isDragged = true;
  23113. if (this.sprite.fixedToCamera)
  23114. {
  23115. if (this.dragFromCenter)
  23116. {
  23117. this.sprite.centerOn(pointer.x, pointer.y);
  23118. this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y);
  23119. }
  23120. else
  23121. {
  23122. this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y);
  23123. }
  23124. }
  23125. else
  23126. {
  23127. if (this.dragFromCenter)
  23128. {
  23129. var bounds = this.sprite.getBounds();
  23130. this.sprite.x = pointer.x + (this.sprite.x - bounds.centerX);
  23131. this.sprite.y = pointer.y + (this.sprite.y - bounds.centerY);
  23132. this._dragPoint.setTo(this.sprite.x - pointer.x, this.sprite.y - pointer.y);
  23133. }
  23134. else
  23135. {
  23136. this._dragPoint.setTo(this.sprite.x - pointer.x, this.sprite.y - pointer.y);
  23137. }
  23138. }
  23139. this.updateDrag(pointer);
  23140. if (this.bringToTop)
  23141. {
  23142. this._dragPhase = true;
  23143. this.sprite.bringToTop();
  23144. }
  23145. this.sprite.events.onDragStart.dispatch(this.sprite, pointer);
  23146. },
  23147. /**
  23148. * Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly.
  23149. * @method Phaser.InputHandler#stopDrag
  23150. * @param {Phaser.Pointer} pointer
  23151. */
  23152. stopDrag: function (pointer) {
  23153. this.isDragged = false;
  23154. this._draggedPointerID = -1;
  23155. this._pointerData[pointer.id].isDragged = false;
  23156. this._dragPhase = false;
  23157. if (this.snapOnRelease)
  23158. {
  23159. if (this.sprite.fixedToCamera)
  23160. {
  23161. this.sprite.cameraOffset.x = Math.round((this.sprite.cameraOffset.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
  23162. this.sprite.cameraOffset.y = Math.round((this.sprite.cameraOffset.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
  23163. }
  23164. else
  23165. {
  23166. this.sprite.x = Math.round((this.sprite.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
  23167. this.sprite.y = Math.round((this.sprite.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
  23168. }
  23169. }
  23170. this.sprite.events.onDragStop.dispatch(this.sprite, pointer);
  23171. if (this.checkPointerOver(pointer) === false)
  23172. {
  23173. this._pointerOutHandler(pointer);
  23174. }
  23175. },
  23176. /**
  23177. * Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move!
  23178. * @method Phaser.InputHandler#setDragLock
  23179. * @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false.
  23180. * @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false.
  23181. */
  23182. setDragLock: function (allowHorizontal, allowVertical) {
  23183. if (typeof allowHorizontal == 'undefined') { allowHorizontal = true; }
  23184. if (typeof allowVertical == 'undefined') { allowVertical = true; }
  23185. this.allowHorizontalDrag = allowHorizontal;
  23186. this.allowVerticalDrag = allowVertical;
  23187. },
  23188. /**
  23189. * Make this Sprite snap to the given grid either during drag or when it's released.
  23190. * For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels.
  23191. * @method Phaser.InputHandler#enableSnap
  23192. * @param {number} snapX - The width of the grid cell to snap to.
  23193. * @param {number} snapY - The height of the grid cell to snap to.
  23194. * @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged.
  23195. * @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released.
  23196. * @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid.
  23197. * @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid.
  23198. */
  23199. enableSnap: function (snapX, snapY, onDrag, onRelease, snapOffsetX, snapOffsetY) {
  23200. if (typeof onDrag == 'undefined') { onDrag = true; }
  23201. if (typeof onRelease == 'undefined') { onRelease = false; }
  23202. if (typeof snapOffsetX == 'undefined') { snapOffsetX = 0; }
  23203. if (typeof snapOffsetY == 'undefined') { snapOffsetY = 0; }
  23204. this.snapX = snapX;
  23205. this.snapY = snapY;
  23206. this.snapOffsetX = snapOffsetX;
  23207. this.snapOffsetY = snapOffsetY;
  23208. this.snapOnDrag = onDrag;
  23209. this.snapOnRelease = onRelease;
  23210. },
  23211. /**
  23212. * Stops the sprite from snapping to a grid during drag or release.
  23213. * @method Phaser.InputHandler#disableSnap
  23214. */
  23215. disableSnap: function () {
  23216. this.snapOnDrag = false;
  23217. this.snapOnRelease = false;
  23218. },
  23219. /**
  23220. * Bounds Rect check for the sprite drag
  23221. * @method Phaser.InputHandler#checkBoundsRect
  23222. */
  23223. checkBoundsRect: function () {
  23224. if (this.sprite.fixedToCamera)
  23225. {
  23226. if (this.sprite.cameraOffset.x < this.boundsRect.left)
  23227. {
  23228. this.sprite.cameraOffset.x = this.boundsRect.cameraOffset.x;
  23229. }
  23230. else if ((this.sprite.cameraOffset.x + this.sprite.width) > this.boundsRect.right)
  23231. {
  23232. this.sprite.cameraOffset.x = this.boundsRect.right - this.sprite.width;
  23233. }
  23234. if (this.sprite.cameraOffset.y < this.boundsRect.top)
  23235. {
  23236. this.sprite.cameraOffset.y = this.boundsRect.top;
  23237. }
  23238. else if ((this.sprite.cameraOffset.y + this.sprite.height) > this.boundsRect.bottom)
  23239. {
  23240. this.sprite.cameraOffset.y = this.boundsRect.bottom - this.sprite.height;
  23241. }
  23242. }
  23243. else
  23244. {
  23245. if (this.sprite.x < this.boundsRect.left)
  23246. {
  23247. this.sprite.x = this.boundsRect.x;
  23248. }
  23249. else if ((this.sprite.x + this.sprite.width) > this.boundsRect.right)
  23250. {
  23251. this.sprite.x = this.boundsRect.right - this.sprite.width;
  23252. }
  23253. if (this.sprite.y < this.boundsRect.top)
  23254. {
  23255. this.sprite.y = this.boundsRect.top;
  23256. }
  23257. else if ((this.sprite.y + this.sprite.height) > this.boundsRect.bottom)
  23258. {
  23259. this.sprite.y = this.boundsRect.bottom - this.sprite.height;
  23260. }
  23261. }
  23262. },
  23263. /**
  23264. * Parent Sprite Bounds check for the sprite drag.
  23265. * @method Phaser.InputHandler#checkBoundsSprite
  23266. */
  23267. checkBoundsSprite: function () {
  23268. if (this.sprite.fixedToCamera && this.boundsSprite.fixedToCamera)
  23269. {
  23270. if (this.sprite.cameraOffset.x < this.boundsSprite.camerOffset.x)
  23271. {
  23272. this.sprite.cameraOffset.x = this.boundsSprite.camerOffset.x;
  23273. }
  23274. else if ((this.sprite.cameraOffset.x + this.sprite.width) > (this.boundsSprite.camerOffset.x + this.boundsSprite.width))
  23275. {
  23276. this.sprite.cameraOffset.x = (this.boundsSprite.camerOffset.x + this.boundsSprite.width) - this.sprite.width;
  23277. }
  23278. if (this.sprite.cameraOffset.y < this.boundsSprite.camerOffset.y)
  23279. {
  23280. this.sprite.cameraOffset.y = this.boundsSprite.camerOffset.y;
  23281. }
  23282. else if ((this.sprite.cameraOffset.y + this.sprite.height) > (this.boundsSprite.camerOffset.y + this.boundsSprite.height))
  23283. {
  23284. this.sprite.cameraOffset.y = (this.boundsSprite.camerOffset.y + this.boundsSprite.height) - this.sprite.height;
  23285. }
  23286. }
  23287. else
  23288. {
  23289. if (this.sprite.x < this.boundsSprite.x)
  23290. {
  23291. this.sprite.x = this.boundsSprite.x;
  23292. }
  23293. else if ((this.sprite.x + this.sprite.width) > (this.boundsSprite.x + this.boundsSprite.width))
  23294. {
  23295. this.sprite.x = (this.boundsSprite.x + this.boundsSprite.width) - this.sprite.width;
  23296. }
  23297. if (this.sprite.y < this.boundsSprite.y)
  23298. {
  23299. this.sprite.y = this.boundsSprite.y;
  23300. }
  23301. else if ((this.sprite.y + this.sprite.height) > (this.boundsSprite.y + this.boundsSprite.height))
  23302. {
  23303. this.sprite.y = (this.boundsSprite.y + this.boundsSprite.height) - this.sprite.height;
  23304. }
  23305. }
  23306. }
  23307. };
  23308. Phaser.InputHandler.prototype.constructor = Phaser.InputHandler;
  23309. /**
  23310. * @author Richard Davey <rich@photonstorm.com>
  23311. * @copyright 2014 Photon Storm Ltd.
  23312. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  23313. */
  23314. /**
  23315. * @class Phaser.Events
  23316. *
  23317. * @classdesc The Events component is a collection of events fired by the parent game object.
  23318. *
  23319. * For example to tell when a Sprite has been added to a new group:
  23320. *
  23321. * `sprite.events.onAddedToGroup.add(yourFunction, this);`
  23322. *
  23323. * Where `yourFunction` is the function you want called when this event occurs.
  23324. *
  23325. * Note that the Input related events only exist if the Sprite has had `inputEnabled` set to `true`.
  23326. *
  23327. * @constructor
  23328. *
  23329. * @param {Phaser.Sprite} sprite - A reference to Description.
  23330. */
  23331. Phaser.Events = function (sprite) {
  23332. this.parent = sprite;
  23333. this.onAddedToGroup = new Phaser.Signal();
  23334. this.onRemovedFromGroup = new Phaser.Signal();
  23335. this.onKilled = new Phaser.Signal();
  23336. this.onRevived = new Phaser.Signal();
  23337. this.onOutOfBounds = new Phaser.Signal();
  23338. this.onEnterBounds = new Phaser.Signal();
  23339. this.onInputOver = null;
  23340. this.onInputOut = null;
  23341. this.onInputDown = null;
  23342. this.onInputUp = null;
  23343. this.onDragStart = null;
  23344. this.onDragStop = null;
  23345. this.onAnimationStart = null;
  23346. this.onAnimationComplete = null;
  23347. this.onAnimationLoop = null;
  23348. };
  23349. Phaser.Events.prototype = {
  23350. destroy: function () {
  23351. this.parent = null;
  23352. this.onAddedToGroup.dispose();
  23353. this.onRemovedFromGroup.dispose();
  23354. this.onKilled.dispose();
  23355. this.onRevived.dispose();
  23356. this.onOutOfBounds.dispose();
  23357. if (this.onInputOver)
  23358. {
  23359. this.onInputOver.dispose();
  23360. this.onInputOut.dispose();
  23361. this.onInputDown.dispose();
  23362. this.onInputUp.dispose();
  23363. this.onDragStart.dispose();
  23364. this.onDragStop.dispose();
  23365. }
  23366. if (this.onAnimationStart)
  23367. {
  23368. this.onAnimationStart.dispose();
  23369. this.onAnimationComplete.dispose();
  23370. this.onAnimationLoop.dispose();
  23371. }
  23372. }
  23373. };
  23374. Phaser.Events.prototype.constructor = Phaser.Events;
  23375. /**
  23376. * @author Richard Davey <rich@photonstorm.com>
  23377. * @copyright 2014 Photon Storm Ltd.
  23378. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  23379. */
  23380. /**
  23381. * The Game Object Factory is a quick way to create all of the different sorts of core objects that Phaser uses.
  23382. *
  23383. * @class Phaser.GameObjectFactory
  23384. * @constructor
  23385. * @param {Phaser.Game} game - A reference to the currently running game.
  23386. */
  23387. Phaser.GameObjectFactory = function (game) {
  23388. /**
  23389. * @property {Phaser.Game} game - A reference to the currently running Game.
  23390. */
  23391. this.game = game;
  23392. /**
  23393. * @property {Phaser.World} world - A reference to the game world.
  23394. */
  23395. this.world = this.game.world;
  23396. };
  23397. Phaser.GameObjectFactory.prototype = {
  23398. /**
  23399. * Adds an existing object to the game world.
  23400. * @method Phaser.GameObjectFactory#existing
  23401. * @param {*} object - An instance of Phaser.Sprite, Phaser.Button or any other display object..
  23402. * @return {*} The child that was added to the Group.
  23403. */
  23404. existing: function (object) {
  23405. return this.world.add(object);
  23406. },
  23407. /**
  23408. * Create a new `Image` object. An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
  23409. * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
  23410. *
  23411. * @method Phaser.GameObjectFactory#image
  23412. * @param {number} x - X position of the image.
  23413. * @param {number} y - Y position of the image.
  23414. * @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.
  23415. * @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.
  23416. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  23417. * @returns {Phaser.Sprite} the newly created sprite object.
  23418. */
  23419. image: function (x, y, key, frame, group) {
  23420. if (typeof group === 'undefined') { group = this.world; }
  23421. return group.add(new Phaser.Image(this.game, x, y, key, frame));
  23422. },
  23423. /**
  23424. * Create a new Sprite with specific position and sprite sheet key.
  23425. *
  23426. * @method Phaser.GameObjectFactory#sprite
  23427. * @param {number} x - X position of the new sprite.
  23428. * @param {number} y - Y position of the new sprite.
  23429. * @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.
  23430. * @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.
  23431. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  23432. * @returns {Phaser.Sprite} the newly created sprite object.
  23433. */
  23434. sprite: function (x, y, key, frame, group) {
  23435. if (typeof group === 'undefined') { group = this.world; }
  23436. return group.create(x, y, key, frame);
  23437. },
  23438. /**
  23439. * Create a tween on a specific object. The object can be any JavaScript object or Phaser object such as Sprite.
  23440. *
  23441. * @method Phaser.GameObjectFactory#tween
  23442. * @param {object} obj - Object the tween will be run on.
  23443. * @return {Phaser.Tween} The newly created Phaser.Tween object.
  23444. */
  23445. tween: function (obj) {
  23446. return this.game.tweens.create(obj);
  23447. },
  23448. /**
  23449. * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
  23450. *
  23451. * @method Phaser.GameObjectFactory#group
  23452. * @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.
  23453. * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
  23454. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  23455. * @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.
  23456. * @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.
  23457. * @return {Phaser.Group} The newly created group.
  23458. */
  23459. group: function (parent, name, addToStage, enableBody, physicsBodyType) {
  23460. return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType);
  23461. },
  23462. /**
  23463. * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
  23464. * A Physics Group is the same as an ordinary Group except that is has enableBody turned on by default, so any Sprites it creates
  23465. * are automatically given a physics body.
  23466. *
  23467. * @method Phaser.GameObjectFactory#physicsGroup
  23468. * @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.P2, Phaser.Physics.NINJA, etc.
  23469. * @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.
  23470. * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
  23471. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  23472. * @return {Phaser.Group} The newly created group.
  23473. */
  23474. physicsGroup: function (physicsBodyType, parent, name, addToStage) {
  23475. return new Phaser.Group(this.game, parent, name, addToStage, true, physicsBodyType);
  23476. },
  23477. /**
  23478. * A SpriteBatch is a really fast version of a Phaser Group built solely for speed.
  23479. * Use when you need a lot of sprites or particles all sharing the same texture.
  23480. * The speed gains are specifically for WebGL. In Canvas mode you won't see any real difference.
  23481. *
  23482. * @method Phaser.GameObjectFactory#spriteBatch
  23483. * @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.
  23484. * @param {string} [name='group'] - A name for this Sprite Batch. Not used internally but useful for debugging.
  23485. * @param {boolean} [addToStage=false] - If set to true this Sprite Batch will be added directly to the Game.Stage instead of the parent.
  23486. * @return {Phaser.Group} The newly created group.
  23487. */
  23488. spriteBatch: function (parent, name, addToStage) {
  23489. if (typeof parent === 'undefined') { parent = null; }
  23490. if (typeof name === 'undefined') { name = 'group'; }
  23491. if (typeof addToStage === 'undefined') { addToStage = false; }
  23492. return new Phaser.SpriteBatch(this.game, parent, name, addToStage);
  23493. },
  23494. /**
  23495. * Creates a new Sound object.
  23496. *
  23497. * @method Phaser.GameObjectFactory#audio
  23498. * @param {string} key - The Game.cache key of the sound that this object will use.
  23499. * @param {number} [volume=1] - The volume at which the sound will be played.
  23500. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  23501. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  23502. * @return {Phaser.Sound} The newly created text object.
  23503. */
  23504. audio: function (key, volume, loop, connect) {
  23505. return this.game.sound.add(key, volume, loop, connect);
  23506. },
  23507. /**
  23508. * Creates a new Sound object.
  23509. *
  23510. * @method Phaser.GameObjectFactory#sound
  23511. * @param {string} key - The Game.cache key of the sound that this object will use.
  23512. * @param {number} [volume=1] - The volume at which the sound will be played.
  23513. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  23514. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  23515. * @return {Phaser.Sound} The newly created text object.
  23516. */
  23517. sound: function (key, volume, loop, connect) {
  23518. return this.game.sound.add(key, volume, loop, connect);
  23519. },
  23520. /**
  23521. * Creates a new TileSprite object.
  23522. *
  23523. * @method Phaser.GameObjectFactory#tileSprite
  23524. * @param {number} x - The x coordinate (in world space) to position the TileSprite at.
  23525. * @param {number} y - The y coordinate (in world space) to position the TileSprite at.
  23526. * @param {number} width - The width of the TileSprite.
  23527. * @param {number} height - The height of the TileSprite.
  23528. * @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.
  23529. * @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.
  23530. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  23531. * @return {Phaser.TileSprite} The newly created tileSprite object.
  23532. */
  23533. tileSprite: function (x, y, width, height, key, frame, group) {
  23534. if (typeof group === 'undefined') { group = this.world; }
  23535. return group.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame));
  23536. },
  23537. /**
  23538. * Creates a new Text object.
  23539. *
  23540. * @method Phaser.GameObjectFactory#text
  23541. * @param {number} x - X position of the new text object.
  23542. * @param {number} y - Y position of the new text object.
  23543. * @param {string} text - The actual text that will be written.
  23544. * @param {object} style - The style object containing style attributes like font, font size , etc.
  23545. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  23546. * @return {Phaser.Text} The newly created text object.
  23547. */
  23548. text: function (x, y, text, style, group) {
  23549. if (typeof group === 'undefined') { group = this.world; }
  23550. return group.add(new Phaser.Text(this.game, x, y, text, style));
  23551. },
  23552. /**
  23553. * Creates a new Button object.
  23554. *
  23555. * @method Phaser.GameObjectFactory#button
  23556. * @param {number} [x] X position of the new button object.
  23557. * @param {number} [y] Y position of the new button object.
  23558. * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button.
  23559. * @param {function} [callback] The function to call when this button is pressed
  23560. * @param {object} [callbackContext] The context in which the callback will be called (usually 'this')
  23561. * @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.
  23562. * @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.
  23563. * @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.
  23564. * @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.
  23565. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  23566. * @return {Phaser.Button} The newly created button object.
  23567. */
  23568. button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) {
  23569. if (typeof group === 'undefined') { group = this.world; }
  23570. return group.add(new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame));
  23571. },
  23572. /**
  23573. * Creates a new Graphics object.
  23574. *
  23575. * @method Phaser.GameObjectFactory#graphics
  23576. * @param {number} x - X position of the new graphics object.
  23577. * @param {number} y - Y position of the new graphics object.
  23578. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  23579. * @return {Phaser.Graphics} The newly created graphics object.
  23580. */
  23581. graphics: function (x, y, group) {
  23582. if (typeof group === 'undefined') { group = this.world; }
  23583. return group.add(new Phaser.Graphics(this.game, x, y));
  23584. },
  23585. /**
  23586. * Emitter is a lightweight particle emitter. It can be used for one-time explosions or for
  23587. * continuous effects like rain and fire. All it really does is launch Particle objects out
  23588. * at set intervals, and fixes their positions and velocities accorindgly.
  23589. *
  23590. * @method Phaser.GameObjectFactory#emitter
  23591. * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
  23592. * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
  23593. * @param {number} [maxParticles=50] - The total number of particles in this emitter.
  23594. * @return {Phaser.Emitter} The newly created emitter object.
  23595. */
  23596. emitter: function (x, y, maxParticles) {
  23597. return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles));
  23598. },
  23599. /**
  23600. * Create a new RetroFont object to be used as a texture for an Image or Sprite and optionally add it to the Cache.
  23601. * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set.
  23602. * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText
  23603. * 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.
  23604. * 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,
  23605. * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects.
  23606. *
  23607. * @method Phaser.GameObjectFactory#retroFont
  23608. * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use.
  23609. * @param {number} characterWidth - The width of each character in the font set.
  23610. * @param {number} characterHeight - The height of each character in the font set.
  23611. * @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.
  23612. * @param {number} charsPerRow - The number of characters per row in the font set.
  23613. * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
  23614. * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
  23615. * @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.
  23616. * @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.
  23617. * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite.
  23618. */
  23619. retroFont: function (font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
  23620. return new Phaser.RetroFont(this.game, font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset);
  23621. },
  23622. /**
  23623. * Create a new BitmapText object.
  23624. *
  23625. * @method Phaser.GameObjectFactory#bitmapText
  23626. * @param {number} x - X position of the new bitmapText object.
  23627. * @param {number} y - Y position of the new bitmapText object.
  23628. * @param {string} font - The key of the BitmapText font as stored in Game.Cache.
  23629. * @param {string} [text] - The actual text that will be rendered. Can be set later via BitmapText.text.
  23630. * @param {number} [size] - The size the font will be rendered in, in pixels.
  23631. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  23632. * @return {Phaser.BitmapText} The newly created bitmapText object.
  23633. */
  23634. bitmapText: function (x, y, font, text, size, group) {
  23635. if (typeof group === 'undefined') { group = this.world; }
  23636. return group.add(new Phaser.BitmapText(this.game, x, y, font, text, size));
  23637. },
  23638. /**
  23639. * Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file.
  23640. * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
  23641. * When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
  23642. * 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.
  23643. * 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.
  23644. *
  23645. * @method Phaser.GameObjectFactory#tilemap
  23646. * @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`.
  23647. * @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.
  23648. * @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.
  23649. * @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.
  23650. * @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.
  23651. * @return {Phaser.Tilemap} The newly created tilemap object.
  23652. */
  23653. tilemap: function (key, tileWidth, tileHeight, width, height) {
  23654. return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height);
  23655. },
  23656. /**
  23657. * A dynamic initially blank canvas to which images can be drawn.
  23658. *
  23659. * @method Phaser.GameObjectFactory#renderTexture
  23660. * @param {number} [width=100] - the width of the RenderTexture.
  23661. * @param {number} [height=100] - the height of the RenderTexture.
  23662. * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter).
  23663. * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key)
  23664. * @return {Phaser.RenderTexture} The newly created RenderTexture object.
  23665. */
  23666. renderTexture: function (width, height, key, addToCache) {
  23667. if (typeof key === 'undefined' || key === '') { key = this.game.rnd.uuid(); }
  23668. if (typeof addToCache === 'undefined') { addToCache = false; }
  23669. var texture = new Phaser.RenderTexture(this.game, width, height, key);
  23670. if (addToCache)
  23671. {
  23672. this.game.cache.addRenderTexture(key, texture);
  23673. }
  23674. return texture;
  23675. },
  23676. /**
  23677. * A BitmapData object which can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites.
  23678. *
  23679. * @method Phaser.GameObjectFactory#bitmapData
  23680. * @param {number} [width=100] - The width of the BitmapData in pixels.
  23681. * @param {number} [height=100] - The height of the BitmapData in pixels.
  23682. * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter).
  23683. * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key)
  23684. * @return {Phaser.BitmapData} The newly created BitmapData object.
  23685. */
  23686. bitmapData: function (width, height, key, addToCache) {
  23687. if (typeof addToCache === 'undefined') { addToCache = false; }
  23688. if (typeof key === 'undefined' || key === '') { key = this.game.rnd.uuid(); }
  23689. var texture = new Phaser.BitmapData(this.game, key, width, height);
  23690. if (addToCache)
  23691. {
  23692. this.game.cache.addBitmapData(key, texture);
  23693. }
  23694. return texture;
  23695. },
  23696. /**
  23697. * A WebGL shader/filter that can be applied to Sprites.
  23698. *
  23699. * @method Phaser.GameObjectFactory#filter
  23700. * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave.
  23701. * @param {any} - Whatever parameters are needed to be passed to the filter init function.
  23702. * @return {Phaser.Filter} The newly created Phaser.Filter object.
  23703. */
  23704. filter: function (filter) {
  23705. var args = Array.prototype.splice.call(arguments, 1);
  23706. var filter = new Phaser.Filter[filter](this.game);
  23707. filter.init.apply(filter, args);
  23708. return filter;
  23709. },
  23710. /**
  23711. * Add a new Plugin into the PluginManager.
  23712. * 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.
  23713. *
  23714. * @method Phaser.GameObjectFactory#plugin
  23715. * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object.
  23716. * @param {...*} parameter - Additional parameters that will be passed to the Plugin.init method.
  23717. * @return {Phaser.Plugin} The Plugin that was added to the manager.
  23718. */
  23719. plugin: function (plugin) {
  23720. return this.game.plugins.add(plugin);
  23721. }
  23722. };
  23723. Phaser.GameObjectFactory.prototype.constructor = Phaser.GameObjectFactory;
  23724. /**
  23725. * @author Richard Davey <rich@photonstorm.com>
  23726. * @copyright 2014 Photon Storm Ltd.
  23727. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  23728. */
  23729. /**
  23730. * The Game Object Creator is a quick way to create all of the different sorts of core objects that Phaser uses, but not add them to the game world.
  23731. * Use the GameObjectFactory to create and add the objects into the world.
  23732. *
  23733. * @class Phaser.GameObjectCreator
  23734. * @constructor
  23735. * @param {Phaser.Game} game - A reference to the currently running game.
  23736. */
  23737. Phaser.GameObjectCreator = function (game) {
  23738. /**
  23739. * @property {Phaser.Game} game - A reference to the currently running Game.
  23740. */
  23741. this.game = game;
  23742. /**
  23743. * @property {Phaser.World} world - A reference to the game world.
  23744. */
  23745. this.world = this.game.world;
  23746. };
  23747. Phaser.GameObjectCreator.prototype = {
  23748. /**
  23749. * Create a new `Image` object. An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
  23750. * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
  23751. *
  23752. * @method Phaser.GameObjectCreator#image
  23753. * @param {number} x - X position of the image.
  23754. * @param {number} y - Y position of the image.
  23755. * @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.
  23756. * @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.
  23757. * @returns {Phaser.Sprite} the newly created sprite object.
  23758. */
  23759. image: function (x, y, key, frame) {
  23760. return new Phaser.Image(this.game, x, y, key, frame);
  23761. },
  23762. /**
  23763. * Create a new Sprite with specific position and sprite sheet key.
  23764. *
  23765. * @method Phaser.GameObjectCreator#sprite
  23766. * @param {number} x - X position of the new sprite.
  23767. * @param {number} y - Y position of the new sprite.
  23768. * @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.
  23769. * @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.
  23770. * @returns {Phaser.Sprite} the newly created sprite object.
  23771. */
  23772. sprite: function (x, y, key, frame) {
  23773. return new Phaser.Sprite(this.game, x, y, key, frame);
  23774. },
  23775. /**
  23776. * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite.
  23777. *
  23778. * @method Phaser.GameObjectCreator#tween
  23779. * @param {object} obj - Object the tween will be run on.
  23780. * @return {Phaser.Tween} The Tween object.
  23781. */
  23782. tween: function (obj) {
  23783. return new Phaser.Tween(obj, this.game);
  23784. },
  23785. /**
  23786. * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
  23787. *
  23788. * @method Phaser.GameObjectCreator#group
  23789. * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
  23790. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  23791. * @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.
  23792. * @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.
  23793. * @return {Phaser.Group} The newly created group.
  23794. */
  23795. group: function (parent, name, addToStage, enableBody, physicsBodyType) {
  23796. return new Phaser.Group(this.game, null, name, addToStage, enableBody, physicsBodyType);
  23797. },
  23798. /**
  23799. * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
  23800. *
  23801. * @method Phaser.GameObjectCreator#spriteBatch
  23802. * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any.
  23803. * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
  23804. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  23805. * @return {Phaser.Group} The newly created group.
  23806. */
  23807. spriteBatch: function (parent, name, addToStage) {
  23808. if (typeof name === 'undefined') { name = 'group'; }
  23809. if (typeof addToStage === 'undefined') { addToStage = false; }
  23810. return new Phaser.SpriteBatch(this.game, parent, name, addToStage);
  23811. },
  23812. /**
  23813. * Creates a new Sound object.
  23814. *
  23815. * @method Phaser.GameObjectCreator#audio
  23816. * @param {string} key - The Game.cache key of the sound that this object will use.
  23817. * @param {number} [volume=1] - The volume at which the sound will be played.
  23818. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  23819. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  23820. * @return {Phaser.Sound} The newly created text object.
  23821. */
  23822. audio: function (key, volume, loop, connect) {
  23823. return this.game.sound.add(key, volume, loop, connect);
  23824. },
  23825. /**
  23826. * Creates a new Sound object.
  23827. *
  23828. * @method Phaser.GameObjectCreator#sound
  23829. * @param {string} key - The Game.cache key of the sound that this object will use.
  23830. * @param {number} [volume=1] - The volume at which the sound will be played.
  23831. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  23832. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  23833. * @return {Phaser.Sound} The newly created text object.
  23834. */
  23835. sound: function (key, volume, loop, connect) {
  23836. return this.game.sound.add(key, volume, loop, connect);
  23837. },
  23838. /**
  23839. * Creates a new TileSprite object.
  23840. *
  23841. * @method Phaser.GameObjectCreator#tileSprite
  23842. * @param {number} x - The x coordinate (in world space) to position the TileSprite at.
  23843. * @param {number} y - The y coordinate (in world space) to position the TileSprite at.
  23844. * @param {number} width - The width of the TileSprite.
  23845. * @param {number} height - The height of the TileSprite.
  23846. * @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.
  23847. * @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.
  23848. * @return {Phaser.TileSprite} The newly created tileSprite object.
  23849. */
  23850. tileSprite: function (x, y, width, height, key, frame) {
  23851. return new Phaser.TileSprite(this.game, x, y, width, height, key, frame);
  23852. },
  23853. /**
  23854. * Creates a new Text object.
  23855. *
  23856. * @method Phaser.GameObjectCreator#text
  23857. * @param {number} x - X position of the new text object.
  23858. * @param {number} y - Y position of the new text object.
  23859. * @param {string} text - The actual text that will be written.
  23860. * @param {object} style - The style object containing style attributes like font, font size , etc.
  23861. * @return {Phaser.Text} The newly created text object.
  23862. */
  23863. text: function (x, y, text, style) {
  23864. return new Phaser.Text(this.game, x, y, text, style);
  23865. },
  23866. /**
  23867. * Creates a new Button object.
  23868. *
  23869. * @method Phaser.GameObjectCreator#button
  23870. * @param {number} [x] X position of the new button object.
  23871. * @param {number} [y] Y position of the new button object.
  23872. * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button.
  23873. * @param {function} [callback] The function to call when this button is pressed
  23874. * @param {object} [callbackContext] The context in which the callback will be called (usually 'this')
  23875. * @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.
  23876. * @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.
  23877. * @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.
  23878. * @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.
  23879. * @return {Phaser.Button} The newly created button object.
  23880. */
  23881. button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) {
  23882. return new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame);
  23883. },
  23884. /**
  23885. * Creates a new Graphics object.
  23886. *
  23887. * @method Phaser.GameObjectCreator#graphics
  23888. * @param {number} x - X position of the new graphics object.
  23889. * @param {number} y - Y position of the new graphics object.
  23890. * @return {Phaser.Graphics} The newly created graphics object.
  23891. */
  23892. graphics: function (x, y) {
  23893. return new Phaser.Graphics(this.game, x, y);
  23894. },
  23895. /**
  23896. * Emitter is a lightweight particle emitter. It can be used for one-time explosions or for
  23897. * continuous effects like rain and fire. All it really does is launch Particle objects out
  23898. * at set intervals, and fixes their positions and velocities accorindgly.
  23899. *
  23900. * @method Phaser.GameObjectCreator#emitter
  23901. * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
  23902. * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
  23903. * @param {number} [maxParticles=50] - The total number of particles in this emitter.
  23904. * @return {Phaser.Emitter} The newly created emitter object.
  23905. */
  23906. emitter: function (x, y, maxParticles) {
  23907. return new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles);
  23908. },
  23909. /**
  23910. * Create a new RetroFont object to be used as a texture for an Image or Sprite and optionally add it to the Cache.
  23911. * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set.
  23912. * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText
  23913. * 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.
  23914. * 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,
  23915. * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects.
  23916. *
  23917. * @method Phaser.GameObjectCreator#retroFont
  23918. * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use.
  23919. * @param {number} characterWidth - The width of each character in the font set.
  23920. * @param {number} characterHeight - The height of each character in the font set.
  23921. * @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.
  23922. * @param {number} charsPerRow - The number of characters per row in the font set.
  23923. * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
  23924. * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
  23925. * @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.
  23926. * @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.
  23927. * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite.
  23928. */
  23929. retroFont: function (font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
  23930. return new Phaser.RetroFont(this.game, font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset);
  23931. },
  23932. /**
  23933. * Create a new BitmapText object.
  23934. *
  23935. * @method Phaser.GameObjectCreator#bitmapText
  23936. * @param {number} x - X position of the new bitmapText object.
  23937. * @param {number} y - Y position of the new bitmapText object.
  23938. * @param {string} font - The key of the BitmapText font as stored in Game.Cache.
  23939. * @param {string} [text] - The actual text that will be rendered. Can be set later via BitmapText.text.
  23940. * @param {number} [size] - The size the font will be rendered in, in pixels.
  23941. * @return {Phaser.BitmapText} The newly created bitmapText object.
  23942. */
  23943. bitmapText: function (x, y, font, text, size) {
  23944. return new Phaser.BitmapText(this.game, x, y, font, text, size);
  23945. },
  23946. /**
  23947. * Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file.
  23948. * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
  23949. * When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
  23950. * 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.
  23951. * 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.
  23952. *
  23953. * @method Phaser.GameObjectCreator#tilemap
  23954. * @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`.
  23955. * @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.
  23956. * @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.
  23957. * @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.
  23958. * @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.
  23959. */
  23960. tilemap: function (key, tileWidth, tileHeight, width, height) {
  23961. return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height);
  23962. },
  23963. /**
  23964. * A dynamic initially blank canvas to which images can be drawn.
  23965. *
  23966. * @method Phaser.GameObjectCreator#renderTexture
  23967. * @param {number} [width=100] - the width of the RenderTexture.
  23968. * @param {number} [height=100] - the height of the RenderTexture.
  23969. * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter).
  23970. * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key)
  23971. * @return {Phaser.RenderTexture} The newly created RenderTexture object.
  23972. */
  23973. renderTexture: function (width, height, key, addToCache) {
  23974. if (typeof key === 'undefined' || key === '') { key = this.game.rnd.uuid(); }
  23975. if (typeof addToCache === 'undefined') { addToCache = false; }
  23976. var texture = new Phaser.RenderTexture(this.game, width, height, key);
  23977. if (addToCache)
  23978. {
  23979. this.game.cache.addRenderTexture(key, texture);
  23980. }
  23981. return texture;
  23982. },
  23983. /**
  23984. * A BitmapData object which can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites.
  23985. *
  23986. * @method Phaser.GameObjectCreator#bitmapData
  23987. * @param {number} [width=100] - The width of the BitmapData in pixels.
  23988. * @param {number} [height=100] - The height of the BitmapData in pixels.
  23989. * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter).
  23990. * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key)
  23991. * @return {Phaser.BitmapData} The newly created BitmapData object.
  23992. */
  23993. bitmapData: function (width, height, key, addToCache) {
  23994. if (typeof addToCache === 'undefined') { addToCache = false; }
  23995. if (typeof key === 'undefined' || key === '') { key = this.game.rnd.uuid(); }
  23996. var texture = new Phaser.BitmapData(this.game, key, width, height);
  23997. if (addToCache)
  23998. {
  23999. this.game.cache.addBitmapData(key, texture);
  24000. }
  24001. return texture;
  24002. },
  24003. /**
  24004. * A WebGL shader/filter that can be applied to Sprites.
  24005. *
  24006. * @method Phaser.GameObjectCreator#filter
  24007. * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave.
  24008. * @param {any} - Whatever parameters are needed to be passed to the filter init function.
  24009. * @return {Phaser.Filter} The newly created Phaser.Filter object.
  24010. */
  24011. filter: function (filter) {
  24012. var args = Array.prototype.splice.call(arguments, 1);
  24013. var filter = new Phaser.Filter[filter](this.game);
  24014. filter.init.apply(filter, args);
  24015. return filter;
  24016. }
  24017. };
  24018. Phaser.GameObjectCreator.prototype.constructor = Phaser.GameObjectCreator;
  24019. /**
  24020. * @author Richard Davey <rich@photonstorm.com>
  24021. * @copyright 2014 Photon Storm Ltd.
  24022. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  24023. */
  24024. /**
  24025. * Creates a new BitmapData object.
  24026. *
  24027. * @class Phaser.BitmapData
  24028. *
  24029. * @classdesc A BitmapData object contains a Canvas element to which you can draw anything you like via normal Canvas context operations.
  24030. * A single BitmapData can be used as the texture one or many Images/Sprites. So if you need to dynamically create a Sprite texture then they are a good choice.
  24031. *
  24032. * @constructor
  24033. * @param {Phaser.Game} game - A reference to the currently running game.
  24034. * @param {string} key - Internal Phaser reference key for the render texture.
  24035. * @param {number} [width=100] - The width of the BitmapData in pixels.
  24036. * @param {number} [height=100] - The height of the BitmapData in pixels.
  24037. */
  24038. Phaser.BitmapData = function (game, key, width, height) {
  24039. if (typeof width === 'undefined') { width = 100; }
  24040. if (typeof height === 'undefined') { height = 100; }
  24041. /**
  24042. * @property {Phaser.Game} game - A reference to the currently running game.
  24043. */
  24044. this.game = game;
  24045. /**
  24046. * @property {string} key - The key of the BitmapData in the Cache, if stored there.
  24047. */
  24048. this.key = key;
  24049. /**
  24050. * @property {number} width - The width of the BitmapData in pixels.
  24051. */
  24052. this.width = width;
  24053. /**
  24054. * @property {number} height - The height of the BitmapData in pixels.
  24055. */
  24056. this.height = height;
  24057. /**
  24058. * @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws.
  24059. * @default
  24060. */
  24061. this.canvas = Phaser.Canvas.create(width, height, '', true);
  24062. /**
  24063. * @property {CanvasRenderingContext2D} context - The 2d context of the canvas.
  24064. * @default
  24065. */
  24066. this.context = this.canvas.getContext('2d');
  24067. /**
  24068. * @property {CanvasRenderingContext2D} ctx - A reference to BitmapData.context.
  24069. */
  24070. this.ctx = this.context;
  24071. /**
  24072. * @property {ImageData} imageData - The context image data.
  24073. */
  24074. this.imageData = this.context.getImageData(0, 0, width, height);
  24075. /**
  24076. * @property {Uint8ClampedArray} data - A Uint8ClampedArray view into BitmapData.buffer.
  24077. */
  24078. this.data = this.imageData.data;
  24079. /**
  24080. * @property {Uint32Array} pixels - An Uint32Array view into BitmapData.buffer.
  24081. */
  24082. this.pixels = null;
  24083. /**
  24084. * @property {ArrayBuffer} buffer - An ArrayBuffer the same size as the context ImageData.
  24085. */
  24086. if (this.imageData.data.buffer)
  24087. {
  24088. this.buffer = this.imageData.data.buffer;
  24089. this.pixels = new Uint32Array(this.buffer);
  24090. }
  24091. else
  24092. {
  24093. if (window['ArrayBuffer'])
  24094. {
  24095. this.buffer = new ArrayBuffer(this.imageData.data.length);
  24096. this.pixels = new Uint32Array(this.buffer);
  24097. }
  24098. else
  24099. {
  24100. this.pixels = this.imageData.data;
  24101. }
  24102. }
  24103. /**
  24104. * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture.
  24105. * @default
  24106. */
  24107. this.baseTexture = new PIXI.BaseTexture(this.canvas);
  24108. /**
  24109. * @property {PIXI.Texture} texture - The PIXI.Texture.
  24110. * @default
  24111. */
  24112. this.texture = new PIXI.Texture(this.baseTexture);
  24113. /**
  24114. * @property {Phaser.Frame} textureFrame - The Frame this BitmapData uses for rendering.
  24115. * @default
  24116. */
  24117. this.textureFrame = new Phaser.Frame(0, 0, 0, width, height, 'bitmapData', game.rnd.uuid());
  24118. this.texture.frame = this.textureFrame;
  24119. /**
  24120. * @property {number} type - The const type of this object.
  24121. * @default
  24122. */
  24123. this.type = Phaser.BITMAPDATA;
  24124. /**
  24125. * @property {boolean} disableTextureUpload - If disableTextureUpload is true this BitmapData will never send its image data to the GPU when its dirty flag is true.
  24126. */
  24127. this.disableTextureUpload = false;
  24128. /**
  24129. * @property {boolean} dirty - If dirty this BitmapData will be re-rendered.
  24130. */
  24131. this.dirty = false;
  24132. // Aliases
  24133. this.cls = this.clear;
  24134. this.update = this.refreshBuffer;
  24135. /**
  24136. * @property {number} _tempR - Internal cache var.
  24137. * @private
  24138. */
  24139. this._tempR = 0;
  24140. /**
  24141. * @property {number} _tempG - Internal cache var.
  24142. * @private
  24143. */
  24144. this._tempG = 0;
  24145. /**
  24146. * @property {number} _tempB - Internal cache var.
  24147. * @private
  24148. */
  24149. this._tempB = 0;
  24150. };
  24151. Phaser.BitmapData.prototype = {
  24152. /**
  24153. * Updates the given objects so that they use this BitmapData as their texture. This will replace any texture they will currently have set.
  24154. *
  24155. * @method Phaser.BitmapData#add
  24156. * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images.
  24157. */
  24158. add: function (object) {
  24159. if (Array.isArray(object))
  24160. {
  24161. for (var i = 0; i < object.length; i++)
  24162. {
  24163. if (object[i]['loadTexture'])
  24164. {
  24165. object[i].loadTexture(this);
  24166. }
  24167. }
  24168. }
  24169. else
  24170. {
  24171. object.loadTexture(this);
  24172. }
  24173. },
  24174. /**
  24175. * Takes the given Game Object, resizes this BitmapData to match it and then draws it into this BitmapDatas canvas, ready for further processing.
  24176. * The source game object is not modified by this operation.
  24177. * 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 and draw.
  24178. * 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.
  24179. *
  24180. * @method Phaser.BitmapData#load
  24181. * @param {Phaser.Sprite|Phaser.Image|Phaser.BitmapData|string} source - The object that will be used to populate this BitmapData.
  24182. */
  24183. load: function (source) {
  24184. if (typeof source === 'string')
  24185. {
  24186. source = this.game.cache.getImage(source);
  24187. }
  24188. this.resize(source.width, source.height);
  24189. this.cls();
  24190. if (source instanceof Phaser.Image || source instanceof Phaser.Sprite)
  24191. {
  24192. this.drawSprite(source, 0, 0);
  24193. }
  24194. else
  24195. {
  24196. this.draw(source, 0, 0);
  24197. }
  24198. this.update();
  24199. },
  24200. /**
  24201. * Clears the BitmapData context using a clearRect.
  24202. *
  24203. * @method Phaser.BitmapData#cls
  24204. */
  24205. /**
  24206. * Clears the BitmapData context using a clearRect.
  24207. *
  24208. * @method Phaser.BitmapData#clear
  24209. */
  24210. clear: function () {
  24211. this.context.clearRect(0, 0, this.width, this.height);
  24212. this.dirty = true;
  24213. },
  24214. /**
  24215. * Fills the BitmapData with the given color.
  24216. *
  24217. * @method Phaser.BitmapData#fill
  24218. * @param {number} r - The red color value, between 0 and 0xFF (255).
  24219. * @param {number} g - The green color value, between 0 and 0xFF (255).
  24220. * @param {number} b - The blue color value, between 0 and 0xFF (255).
  24221. * @param {number} [a=1] - The alpha color value, between 0 and 1.
  24222. */
  24223. fill: function (r, g, b, a) {
  24224. if (typeof a === 'undefined') { a = 1; }
  24225. this.context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  24226. this.context.fillRect(0, 0, this.width, this.height);
  24227. this.dirty = true;
  24228. },
  24229. /**
  24230. * Resizes the BitmapData. This changes the size of the underlying canvas and refreshes the buffer.
  24231. *
  24232. * @method Phaser.BitmapData#resize
  24233. */
  24234. resize: function (width, height) {
  24235. if (width !== this.width || height !== this.height)
  24236. {
  24237. this.width = width;
  24238. this.height = height;
  24239. this.canvas.width = width;
  24240. this.canvas.height = height;
  24241. this.baseTexture.width = width;
  24242. this.baseTexture.height = height;
  24243. this.textureFrame.width = width;
  24244. this.textureFrame.height = height;
  24245. this.texture.width = width;
  24246. this.texture.height = height;
  24247. this.texture.crop.width = width;
  24248. this.texture.crop.height = height;
  24249. this.refreshBuffer();
  24250. this.dirty = true;
  24251. }
  24252. },
  24253. /**
  24254. * This re-creates the BitmapData.imageData from the current context.
  24255. * It then re-builds the ArrayBuffer, the data Uint8ClampedArray reference and the pixels Int32Array.
  24256. * If not given the dimensions defaults to the full size of the context.
  24257. *
  24258. * @method Phaser.BitmapData#update
  24259. * @param {number} [x=0] - The x coordinate of the top-left of the image data area to grab from.
  24260. * @param {number} [y=0] - The y coordinate of the top-left of the image data area to grab from.
  24261. * @param {number} [width] - The width of the image data area.
  24262. * @param {number} [height] - The height of the image data area.
  24263. */
  24264. /**
  24265. * DEPRECATED: This method will be removed in Phaser 2.1. Please use BitmapData.update instead.
  24266. *
  24267. * This re-creates the BitmapData.imageData from the current context.
  24268. * It then re-builds the ArrayBuffer, the data Uint8ClampedArray reference and the pixels Int32Array.
  24269. * If not given the dimensions defaults to the full size of the context.
  24270. *
  24271. * @method Phaser.BitmapData#refreshBuffer
  24272. * @param {number} [x=0] - The x coordinate of the top-left of the image data area to grab from.
  24273. * @param {number} [y=0] - The y coordinate of the top-left of the image data area to grab from.
  24274. * @param {number} [width] - The width of the image data area.
  24275. * @param {number} [height] - The height of the image data area.
  24276. */
  24277. refreshBuffer: function (x, y, width, height) {
  24278. if (typeof x === 'undefined') { x = 0; }
  24279. if (typeof y === 'undefined') { y = 0; }
  24280. if (typeof width === 'undefined') { width = this.width; }
  24281. if (typeof height === 'undefined') { height = this.height; }
  24282. this.imageData = this.context.getImageData(x, y, width, height);
  24283. this.data = this.imageData.data;
  24284. if (this.imageData.data.buffer)
  24285. {
  24286. this.buffer = this.imageData.data.buffer;
  24287. this.pixels = new Uint32Array(this.buffer);
  24288. }
  24289. else
  24290. {
  24291. if (window['ArrayBuffer'])
  24292. {
  24293. this.buffer = new ArrayBuffer(this.imageData.data.length);
  24294. this.pixels = new Uint32Array(this.buffer);
  24295. }
  24296. else
  24297. {
  24298. this.pixels = this.imageData.data;
  24299. }
  24300. }
  24301. },
  24302. /**
  24303. * Scans through the area specified in this BitmapData and sends a color object for every pixel to the given callback.
  24304. * The callback will be sent a color object with 6 properties: `{ r: number, g: number, b: number, a: number, color: number, rgba: string }`.
  24305. * Where r, g, b and a are integers between 0 and 255 representing the color component values for red, green, blue and alpha.
  24306. * The `color` property is an Int32 of the full color. Note the endianess of this will change per system.
  24307. * The `rgba` property is a CSS style rgba() string which can be used with context.fillStyle calls, among others.
  24308. * The callback will also be sent the pixels x and y coordinates respectively.
  24309. * The callback must return either `false`, in which case no change will be made to the pixel, or a new color object.
  24310. * If a new color object is returned the pixel will be set to the r, g, b and a color values given within it.
  24311. *
  24312. * @method Phaser.BitmapData#processPixelRGB
  24313. * @param {function} callback - The callback that will be sent each pixel color object to be processed.
  24314. * @param {object} callbackContext - The context under which the callback will be called.
  24315. * @param {number} [x=0] - The x coordinate of the top-left of the region to process from.
  24316. * @param {number} [y=0] - The y coordinate of the top-left of the region to process from.
  24317. * @param {number} [width] - The width of the region to process.
  24318. * @param {number} [height] - The height of the region to process.
  24319. */
  24320. processPixelRGB: function (callback, callbackContext, x, y, width, height) {
  24321. if (typeof x === 'undefined') { x = 0; }
  24322. if (typeof y === 'undefined') { y = 0; }
  24323. if (typeof width === 'undefined') { width = this.width; }
  24324. if (typeof height === 'undefined') { height = this.height; }
  24325. var w = x + width;
  24326. var h = y + height;
  24327. var pixel = Phaser.Color.createColor();
  24328. var result = { r: 0, g: 0, b: 0, a: 0 };
  24329. var dirty = false;
  24330. for (var ty = y; ty < h; ty++)
  24331. {
  24332. for (var tx = x; tx < w; tx++)
  24333. {
  24334. Phaser.Color.unpackPixel(this.getPixel32(tx, ty), pixel);
  24335. result = callback.call(callbackContext, pixel, tx, ty);
  24336. if (result !== false && result !== null && result !== undefined)
  24337. {
  24338. this.setPixel32(tx, ty, result.r, result.g, result.b, result.a, false);
  24339. dirty = true;
  24340. }
  24341. }
  24342. }
  24343. if (dirty)
  24344. {
  24345. this.context.putImageData(this.imageData, 0, 0);
  24346. this.dirty = true;
  24347. }
  24348. },
  24349. /**
  24350. * 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.
  24351. * 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.
  24352. * Note that the format of the color received will be different depending on if the system is big or little endian.
  24353. * It is expected that your callback will deal with endianess. If you'd rather Phaser did it then use processPixelRGB instead.
  24354. * The callback will also be sent the pixels x and y coordinates respectively.
  24355. *
  24356. * @method Phaser.BitmapData#processPixel
  24357. * @param {function} callback - The callback that will be sent each pixel color to be processed.
  24358. * @param {object} callbackContext - The context under which the callback will be called.
  24359. * @param {number} [x=0] - The x coordinate of the top-left of the region to process from.
  24360. * @param {number} [y=0] - The y coordinate of the top-left of the region to process from.
  24361. * @param {number} [width] - The width of the region to process.
  24362. * @param {number} [height] - The height of the region to process.
  24363. */
  24364. processPixel: function (callback, callbackContext, x, y, width, height) {
  24365. if (typeof x === 'undefined') { x = 0; }
  24366. if (typeof y === 'undefined') { y = 0; }
  24367. if (typeof width === 'undefined') { width = this.width; }
  24368. if (typeof height === 'undefined') { height = this.height; }
  24369. var w = x + width;
  24370. var h = y + height;
  24371. var pixel = 0;
  24372. var result = 0;
  24373. var dirty = false;
  24374. for (var ty = y; ty < h; ty++)
  24375. {
  24376. for (var tx = x; tx < w; tx++)
  24377. {
  24378. pixel = this.getPixel32(tx, ty);
  24379. result = callback.call(callbackContext, pixel, tx, ty);
  24380. if (result !== pixel)
  24381. {
  24382. this.pixels[ty * this.width + tx] = result;
  24383. dirty = true;
  24384. }
  24385. }
  24386. }
  24387. if (dirty)
  24388. {
  24389. this.context.putImageData(this.imageData, 0, 0);
  24390. this.dirty = true;
  24391. }
  24392. },
  24393. /**
  24394. * Replaces all pixels matching one color with another. The color values are given as two sets of RGBA values.
  24395. * An optional region parameter controls if the replacement happens in just a specific area of the BitmapData or the entire thing.
  24396. *
  24397. * @method Phaser.BitmapData#replaceRGB
  24398. * @param {number} r1 - The red color value to be replaced. Between 0 and 255.
  24399. * @param {number} g1 - The green color value to be replaced. Between 0 and 255.
  24400. * @param {number} b1 - The blue color value to be replaced. Between 0 and 255.
  24401. * @param {number} a1 - The alpha color value to be replaced. Between 0 and 255.
  24402. * @param {number} r2 - The red color value that is the replacement color. Between 0 and 255.
  24403. * @param {number} g2 - The green color value that is the replacement color. Between 0 and 255.
  24404. * @param {number} b2 - The blue color value that is the replacement color. Between 0 and 255.
  24405. * @param {number} a2 - The alpha color value that is the replacement color. Between 0 and 255.
  24406. * @param {Phaser.Rectangle} [region] - The area to perform the search over. If not given it will replace over the whole BitmapData.
  24407. */
  24408. replaceRGB: function (r1, g1, b1, a1, r2, g2, b2, a2, region) {
  24409. var sx = 0;
  24410. var sy = 0;
  24411. var w = this.width;
  24412. var h = this.height;
  24413. var source = Phaser.Color.packPixel(r1, g1, b1, a1);
  24414. if (region !== undefined && region instanceof Phaser.Rectangle)
  24415. {
  24416. sx = region.x;
  24417. sy = region.y;
  24418. w = region.width;
  24419. h = region.height;
  24420. }
  24421. for (var y = 0; y < h; y++)
  24422. {
  24423. for (var x = 0; x < w; x++)
  24424. {
  24425. if (this.getPixel32(sx + x, sy + y) === source)
  24426. {
  24427. this.setPixel32(sx + x, sy + y, r2, g2, b2, a2, false);
  24428. }
  24429. }
  24430. }
  24431. this.context.putImageData(this.imageData, 0, 0);
  24432. this.dirty = true;
  24433. },
  24434. /**
  24435. * Sets the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified.
  24436. *
  24437. * @method Phaser.BitmapData#setHSL
  24438. * @param {number} [h=null] - The hue, in the range 0 - 1.
  24439. * @param {number} [s=null] - The saturation, in the range 0 - 1.
  24440. * @param {number} [l=null] - The lightness, in the range 0 - 1.
  24441. * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData.
  24442. */
  24443. setHSL: function (h, s, l, region) {
  24444. if (typeof h === 'undefined' || h === null) { h = false; }
  24445. if (typeof s === 'undefined' || s === null) { s = false; }
  24446. if (typeof l === 'undefined' || l === null) { l = false; }
  24447. if (!h && !s && !l)
  24448. {
  24449. return;
  24450. }
  24451. if (typeof region === 'undefined')
  24452. {
  24453. region = new Phaser.Rectangle(0, 0, this.width, this.height);
  24454. }
  24455. var pixel = Phaser.Color.createColor();
  24456. for (var y = region.y; y < region.bottom; y++)
  24457. {
  24458. for (var x = region.x; x < region.right; x++)
  24459. {
  24460. Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true);
  24461. if (h)
  24462. {
  24463. pixel.h = h;
  24464. }
  24465. if (s)
  24466. {
  24467. pixel.s = s;
  24468. }
  24469. if (l)
  24470. {
  24471. pixel.l = l;
  24472. }
  24473. Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel);
  24474. this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false);
  24475. }
  24476. }
  24477. this.context.putImageData(this.imageData, 0, 0);
  24478. this.dirty = true;
  24479. },
  24480. /**
  24481. * 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.
  24482. * Shifting will add the given value onto the current h, s and l values, not replace them.
  24483. * The hue is wrapped to keep it within the range 0 to 1. Saturation and lightness are clamped to not exceed 1.
  24484. *
  24485. * @method Phaser.BitmapData#shiftHSL
  24486. * @param {number} [h=null] - The amount to shift the hue by.
  24487. * @param {number} [s=null] - The amount to shift the saturation by.
  24488. * @param {number} [l=null] - The amount to shift the lightness by.
  24489. * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData.
  24490. */
  24491. shiftHSL: function (h, s, l, region) {
  24492. if (typeof h === 'undefined' || h === null) { h = false; }
  24493. if (typeof s === 'undefined' || s === null) { s = false; }
  24494. if (typeof l === 'undefined' || l === null) { l = false; }
  24495. if (!h && !s && !l)
  24496. {
  24497. return;
  24498. }
  24499. if (typeof region === 'undefined')
  24500. {
  24501. region = new Phaser.Rectangle(0, 0, this.width, this.height);
  24502. }
  24503. var pixel = Phaser.Color.createColor();
  24504. for (var y = region.y; y < region.bottom; y++)
  24505. {
  24506. for (var x = region.x; x < region.right; x++)
  24507. {
  24508. Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true);
  24509. if (h)
  24510. {
  24511. pixel.h = this.game.math.wrap(pixel.h + h, 0, 1);
  24512. }
  24513. if (s)
  24514. {
  24515. pixel.s = this.game.math.limitValue(pixel.s + s, 0, 1);
  24516. }
  24517. if (l)
  24518. {
  24519. pixel.l = this.game.math.limitValue(pixel.l + l, 0, 1);
  24520. }
  24521. Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel);
  24522. this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false);
  24523. }
  24524. }
  24525. this.context.putImageData(this.imageData, 0, 0);
  24526. this.dirty = true;
  24527. },
  24528. /**
  24529. * Sets the color of the given pixel to the specified red, green, blue and alpha values.
  24530. *
  24531. * @method Phaser.BitmapData#setPixel32
  24532. * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  24533. * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  24534. * @param {number} red - The red color value, between 0 and 0xFF (255).
  24535. * @param {number} green - The green color value, between 0 and 0xFF (255).
  24536. * @param {number} blue - The blue color value, between 0 and 0xFF (255).
  24537. * @param {number} alpha - The alpha color value, between 0 and 0xFF (255).
  24538. * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set.
  24539. */
  24540. setPixel32: function (x, y, red, green, blue, alpha, immediate) {
  24541. if (typeof immediate === 'undefined') { immediate = true; }
  24542. if (x >= 0 && x <= this.width && y >= 0 && y <= this.height)
  24543. {
  24544. if (Phaser.Device.LITTLE_ENDIAN)
  24545. {
  24546. this.pixels[y * this.width + x] = (alpha << 24) | (blue << 16) | (green << 8) | red;
  24547. }
  24548. else
  24549. {
  24550. this.pixels[y * this.width + x] = (red << 24) | (green << 16) | (blue << 8) | alpha;
  24551. }
  24552. if (immediate)
  24553. {
  24554. this.context.putImageData(this.imageData, 0, 0);
  24555. this.dirty = true;
  24556. }
  24557. }
  24558. },
  24559. /**
  24560. * Sets the color of the given pixel to the specified red, green and blue values.
  24561. *
  24562. * @method Phaser.BitmapData#setPixel
  24563. * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  24564. * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  24565. * @param {number} red - The red color value, between 0 and 0xFF (255).
  24566. * @param {number} green - The green color value, between 0 and 0xFF (255).
  24567. * @param {number} blue - The blue color value, between 0 and 0xFF (255).
  24568. * @param {number} alpha - The alpha color value, between 0 and 0xFF (255).
  24569. * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set.
  24570. */
  24571. setPixel: function (x, y, red, green, blue, immediate) {
  24572. this.setPixel32(x, y, red, green, blue, 255, immediate);
  24573. },
  24574. /**
  24575. * Get the color of a specific pixel in the context into a color object.
  24576. * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer,
  24577. * 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.
  24578. *
  24579. * @method Phaser.BitmapData#getPixel
  24580. * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  24581. * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  24582. * @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.
  24583. * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties.
  24584. */
  24585. getPixel: function (x, y, out) {
  24586. if (!out)
  24587. {
  24588. out = Phaser.Color.createColor();
  24589. }
  24590. var index = ~~(x + (y * this.width));
  24591. index *= 4;
  24592. out.r = this.data[index];
  24593. out.g = this.data[++index];
  24594. out.b = this.data[++index];
  24595. out.a = this.data[++index];
  24596. return out;
  24597. },
  24598. /**
  24599. * Get the color of a specific pixel including its alpha value.
  24600. * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer,
  24601. * 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.
  24602. * Note that on little-endian systems the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA.
  24603. *
  24604. * @method Phaser.BitmapData#getPixel32
  24605. * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  24606. * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  24607. * @return {number} A native color value integer (format: 0xAARRGGBB)
  24608. */
  24609. getPixel32: function (x, y) {
  24610. if (x >= 0 && x <= this.width && y >= 0 && y <= this.height)
  24611. {
  24612. return this.pixels[y * this.width + x];
  24613. }
  24614. },
  24615. /**
  24616. * Get the color of a specific pixel including its alpha value as a color object containing r,g,b,a and rgba properties.
  24617. * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer,
  24618. * 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.
  24619. *
  24620. * @method Phaser.BitmapData#getPixelRGB
  24621. * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  24622. * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  24623. * @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.
  24624. * @param {boolean} [hsl=false] - Also convert the rgb values into hsl?
  24625. * @param {boolean} [hsv=false] - Also convert the rgb values into hsv?
  24626. * @return {object} An object with the red, green and blue values set in the r, g and b properties.
  24627. */
  24628. getPixelRGB: function (x, y, out, hsl, hsv) {
  24629. return Phaser.Color.unpackPixel(this.getPixel32(x, y), out, hsl, hsv);
  24630. },
  24631. /**
  24632. * Gets all the pixels from the region specified by the given Rectangle object.
  24633. *
  24634. * @method Phaser.BitmapData#getPixels
  24635. * @param {Phaser.Rectangle} rect - The Rectangle region to get.
  24636. * @return {ImageData} Returns a ImageData object containing a Uint8ClampedArray data property.
  24637. */
  24638. getPixels: function (rect) {
  24639. return this.context.getImageData(rect.x, rect.y, rect.width, rect.height);
  24640. },
  24641. /**
  24642. * Creates a new Phaser.Image object, assigns this BitmapData to be its texture, adds it to the world then returns it.
  24643. *
  24644. * @method Phaser.BitmapData#addToWorld
  24645. * @param {number} [x=0] - The x coordinate to place the image at.
  24646. * @param {number} [y=0] - The y coordinate to place the image at.
  24647. * @return {Phaser.Image} The newly added Image object.
  24648. */
  24649. addToWorld: function (x, y) {
  24650. return this.game.add.image(x, y, this);
  24651. },
  24652. /**
  24653. * Copies the pixels from the source image to this BitmapData based on the given area and destination.
  24654. *
  24655. * @method Phaser.BitmapData#copyPixels
  24656. * @param {Phaser.Sprite|Phaser.Image|Phaser.BitmapData|HTMLImage|string} source - The Image to copy from. If you give a string it will try and find the Image in the Game.Cache.
  24657. * @param {Phaser.Rectangle} area - The Rectangle region to copy from the source image.
  24658. * @param {number} x - The destination x coordinate to copy the image to.
  24659. * @param {number} y - The destination y coordinate to copy the image to.
  24660. */
  24661. copyPixels: function (source, area, x, y) {
  24662. if (typeof source === 'string')
  24663. {
  24664. source = this.game.cache.getImage(source);
  24665. }
  24666. var src = source;
  24667. var sx = 0;
  24668. var sy = 0;
  24669. if (source instanceof Phaser.Image || source instanceof Phaser.Sprite)
  24670. {
  24671. src = source.texture.baseTexture.source;
  24672. var frame = source.texture.frame;
  24673. sx = frame.x;
  24674. sy = frame.y;
  24675. }
  24676. else
  24677. {
  24678. if (source instanceof Phaser.BitmapData)
  24679. {
  24680. src = source.canvas;
  24681. }
  24682. }
  24683. this.context.drawImage(src, sx + area.x, sy + area.y, area.width, area.height, x, y, area.width, area.height);
  24684. this.dirty = true;
  24685. },
  24686. /**
  24687. * Draws the given image or Game Object to this BitmapData at the coordinates specified.
  24688. * You can use the optional width and height values to 'stretch' the image as it's drawn.
  24689. *
  24690. * @method Phaser.BitmapData#draw
  24691. * @param {Phaser.Sprite|Phaser.Image|Phaser.BitmapData|HTMLImage|string} source - The Image to draw. If you give a string it will try and find the Image in the Game.Cache.
  24692. * @param {number} [x=0] - The x coordinate to draw the image to.
  24693. * @param {number} [y=0] - The y coordinate to draw the image to.
  24694. * @param {number} [width] - The width when drawing the image. You can use this to optionally stretch the drawn image horizontally.
  24695. * @param {number} [height] - The height when drawing the image. You can use this to optionally stretch the drawn image vertically.
  24696. */
  24697. draw: function (source, x, y, width, height) {
  24698. if (typeof x === 'undefined') { x = 0; }
  24699. if (typeof y === 'undefined') { y = 0; }
  24700. if (typeof source === 'string')
  24701. {
  24702. source = this.game.cache.getImage(source);
  24703. }
  24704. var src = source;
  24705. var sx = 0;
  24706. var sy = 0;
  24707. var sw = 0;
  24708. var sh = 0;
  24709. if (source instanceof Phaser.Image || source instanceof Phaser.Sprite)
  24710. {
  24711. src = source.texture.baseTexture.source;
  24712. var frame = source.texture.frame;
  24713. sx = frame.x;
  24714. sy = frame.y;
  24715. sw = frame.width;
  24716. sh = frame.height;
  24717. // this.context.drawImage(sprite.texture.baseTexture.source, frame.x, frame.y, frame.width, frame.height, x, y, frame.width, frame.height);
  24718. }
  24719. else
  24720. {
  24721. if (source instanceof Phaser.BitmapData)
  24722. {
  24723. src = source.canvas;
  24724. // this.context.drawImage(source.canvas, 0, 0, source.width, source.height, x, y, source.width, source.height);
  24725. }
  24726. sw = source.width;
  24727. sh = source.height;
  24728. // this.context.drawImage(source, 0, 0, source.width, source.height, x, y, source.width, source.height);
  24729. }
  24730. if (typeof width === 'undefined') { width = sw; }
  24731. if (typeof height === 'undefined') { height = sh; }
  24732. this.context.drawImage(src, sx, sy, sw, sh, x, y, width, height);
  24733. this.dirty = true;
  24734. },
  24735. /**
  24736. * DEPRECATED: Use BitmapData.draw instead.
  24737. *
  24738. * Draws the given image to this BitmapData at the coordinates specified.
  24739. * If you need to only draw a part of the image use BitmapData.copyPixels instead.
  24740. *
  24741. * @method Phaser.BitmapData#drawSprite
  24742. * @param {Phaser.Sprite|Phaser.Image} sprite - The Sprite to draw. Must have a loaded texture and frame.
  24743. * @param {number} [x=0] - The x coordinate to draw the Sprite to.
  24744. * @param {number} [y=0] - The y coordinate to draw the Sprite to.
  24745. */
  24746. drawSprite: function (sprite, x, y) {
  24747. if (typeof x === 'undefined') { x = 0; }
  24748. if (typeof y === 'undefined') { y = 0; }
  24749. this.draw(sprite, x, y);
  24750. },
  24751. /**
  24752. * Draws the given image onto this BitmapData using an image as an alpha mask.
  24753. *
  24754. * @method Phaser.BitmapData#alphaMask
  24755. * @param {Phaser.Sprite|Phaser.Image|Phaser.BitmapData|HTMLImage|string} source - The Image to draw. If you give a key it will try and find the Image in the Game.Cache.
  24756. * @param {Phaser.Sprite|Phaser.Image|Phaser.BitmapData|HTMLImage|string|null} [mask] - The Image to use as the alpha mask. If you give a key it will try and find the Image in the Game.Cache. If you pass nothing or null it will use itself.
  24757. * @param {Phaser.Rectangle} [sourceRect] - A Rectangle where x/y define the coordinates to draw the Source image to and width/height define the size.
  24758. * @param {Phaser.Rectangle} [maskRect] - A Rectangle where x/y define the coordinates to draw the Mask image to and width/height define the size.
  24759. */
  24760. alphaMask: function (source, mask, sourceRect, maskRect) {
  24761. if (typeof mask === 'undefined' || mask === null) { mask = this; }
  24762. var temp = this.context.globalCompositeOperation;
  24763. if (typeof maskRect === 'undefined' || maskRect === null)
  24764. {
  24765. this.draw(mask);
  24766. }
  24767. else
  24768. {
  24769. this.draw(mask, maskRect.x, maskRect.y, maskRect.width, maskRect.height);
  24770. }
  24771. this.context.globalCompositeOperation = 'source-atop';
  24772. if (typeof sourceRect === 'undefined' || sourceRect === null)
  24773. {
  24774. this.draw(source);
  24775. }
  24776. else
  24777. {
  24778. this.draw(source, sourceRect.x, sourceRect.y, sourceRect.width, sourceRect.height);
  24779. }
  24780. this.context.globalCompositeOperation = temp;
  24781. this.update();
  24782. this.dirty = true;
  24783. },
  24784. /**
  24785. * Scans this BitmapData for all pixels matching the given r,g,b values and then draws them into the given destination BitmapData.
  24786. * The original BitmapData remains unchanged.
  24787. * The destination BitmapData must be large enough to receive all of the pixels that are scanned unless the 'resize' parameter is true.
  24788. * Although the destination BitmapData is returned from this method, it's actually modified directly in place, meaning this call is perfectly valid:
  24789. * `picture.extract(mask, r, g, b)`
  24790. * 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.
  24791. * 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
  24792. * the color during extraction.
  24793. *
  24794. * @method Phaser.BitmapData#extract
  24795. * @param {Phaser.BitmapData} destination - The BitmapData that the extracts pixels will be drawn to.
  24796. * @param {number} r - The red color component, in the range 0 - 255.
  24797. * @param {number} g - The green color component, in the range 0 - 255.
  24798. * @param {number} b - The blue color component, in the range 0 - 255.
  24799. * @param {number} [a=255] - The alpha color component, in the range 0 - 255 that the new pixel will be drawn at.
  24800. * @param {boolean} [resize=false] - Should the destination BitmapData be resized to match this one before the pixels are copied?
  24801. * @param {number} [r2] - An alternative red color component to be written to the destination, in the range 0 - 255.
  24802. * @param {number} [g2] - An alternative green color component to be written to the destination, in the range 0 - 255.
  24803. * @param {number} [b2] - An alternative blue color component to be written to the destination, in the range 0 - 255.
  24804. * @returns {Phaser.BitmapData} The BitmapData that the extract pixels were drawn on.
  24805. */
  24806. extract: function (destination, r, g, b, a, resize, r2, g2, b2) {
  24807. if (typeof a === 'undefined') { a = 255; }
  24808. if (typeof resize === 'undefined') { resize = false; }
  24809. if (typeof r2 === 'undefined') { r2 = r; }
  24810. if (typeof g2 === 'undefined') { g2 = g; }
  24811. if (typeof b2 === 'undefined') { b2 = b; }
  24812. if (resize)
  24813. {
  24814. destination.resize(this.width, this.height);
  24815. }
  24816. this.processPixelRGB(
  24817. function (pixel, x, y)
  24818. {
  24819. if (pixel.r === r && pixel.g === g && pixel.b === b)
  24820. {
  24821. destination.setPixel32(x, y, r2, g2, b2, a, false);
  24822. }
  24823. return false;
  24824. },
  24825. this);
  24826. destination.context.putImageData(destination.imageData, 0, 0);
  24827. destination.dirty = true;
  24828. return destination;
  24829. },
  24830. /**
  24831. * Draws a filled Rectangle to the BitmapData at the given x, y coordinates and width / height in size.
  24832. *
  24833. * @method Phaser.BitmapData#rect
  24834. * @param {number} x - The x coordinate of the top-left of the Rectangle.
  24835. * @param {number} y - The y coordinate of the top-left of the Rectangle.
  24836. * @param {number} width - The width of the Rectangle.
  24837. * @param {number} height - The height of the Rectangle.
  24838. * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the rect is drawn.
  24839. */
  24840. rect: function (x, y, width, height, fillStyle) {
  24841. if (typeof fillStyle !== 'undefined')
  24842. {
  24843. this.context.fillStyle = fillStyle;
  24844. }
  24845. this.context.fillRect(x, y, width, height);
  24846. },
  24847. /**
  24848. * Draws a filled Circle to the BitmapData at the given x, y coordinates and radius in size.
  24849. *
  24850. * @method Phaser.BitmapData#circle
  24851. * @param {number} x - The x coordinate to draw the Circle at. This is the center of the circle.
  24852. * @param {number} y - The y coordinate to draw the Circle at. This is the center of the circle.
  24853. * @param {number} radius - The radius of the Circle in pixels. The radius is half the diameter.
  24854. * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the circle is drawn.
  24855. */
  24856. circle: function (x, y, radius, fillStyle) {
  24857. if (typeof fillStyle !== 'undefined')
  24858. {
  24859. this.context.fillStyle = fillStyle;
  24860. }
  24861. this.context.beginPath();
  24862. this.context.arc(x, y, radius, 0, Math.PI * 2, false);
  24863. this.context.closePath();
  24864. this.context.fill();
  24865. },
  24866. /**
  24867. * If the game is running in WebGL this will push the texture up to the GPU if it's dirty.
  24868. * 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.
  24869. * If you wish to suppress this functionality set BitmapData.disableTextureUpload to `true`.
  24870. *
  24871. * @method Phaser.BitmapData#render
  24872. */
  24873. render: function () {
  24874. if (!this.disableTextureUpload && this.game.renderType === Phaser.WEBGL && this.dirty)
  24875. {
  24876. // Only needed if running in WebGL, otherwise this array will never get cleared down
  24877. // should use the rendersession
  24878. PIXI.updateWebGLTexture(this.baseTexture, this.game.renderer.gl);
  24879. this.dirty = false;
  24880. }
  24881. }
  24882. };
  24883. Phaser.BitmapData.prototype.constructor = Phaser.BitmapData;
  24884. /**
  24885. * @author Richard Davey <rich@photonstorm.com>
  24886. * @copyright 2014 Photon Storm Ltd.
  24887. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  24888. */
  24889. /**
  24890. * @class Phaser.Sprite
  24891. *
  24892. * @classdesc Create a new `Sprite` object. Sprites are the lifeblood of your game, used for nearly everything visual.
  24893. *
  24894. * At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas.
  24895. * They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input),
  24896. * events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases.
  24897. *
  24898. * @constructor
  24899. * @extends PIXI.Sprite
  24900. * @param {Phaser.Game} game - A reference to the currently running game.
  24901. * @param {number} x - The x coordinate (in world space) to position the Sprite at.
  24902. * @param {number} y - The y coordinate (in world space) to position the Sprite at.
  24903. * @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.
  24904. * @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.
  24905. */
  24906. Phaser.Sprite = function (game, x, y, key, frame) {
  24907. x = x || 0;
  24908. y = y || 0;
  24909. key = key || null;
  24910. frame = frame || null;
  24911. /**
  24912. * @property {Phaser.Game} game - A reference to the currently running Game.
  24913. */
  24914. this.game = game;
  24915. /**
  24916. * @property {string} name - The user defined name given to this Sprite.
  24917. * @default
  24918. */
  24919. this.name = '';
  24920. /**
  24921. * @property {number} type - The const type of this object.
  24922. * @readonly
  24923. */
  24924. this.type = Phaser.SPRITE;
  24925. /**
  24926. * @property {number} z - The z-depth value of this object within its Group (remember the World is a Group as well). No two objects in a Group can have the same z value.
  24927. */
  24928. this.z = 0;
  24929. /**
  24930. * @property {Phaser.Events} events - The Events you can subscribe to that are dispatched when certain things happen on this Sprite or its components.
  24931. */
  24932. this.events = new Phaser.Events(this);
  24933. /**
  24934. * @property {Phaser.AnimationManager} animations - This manages animations of the sprite. You can modify animations through it (see Phaser.AnimationManager)
  24935. */
  24936. this.animations = new Phaser.AnimationManager(this);
  24937. /**
  24938. * @property {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, BitmapData or PIXI.Texture.
  24939. */
  24940. this.key = key;
  24941. PIXI.Sprite.call(this, PIXI.TextureCache['__default']);
  24942. this.position.set(x, y);
  24943. /**
  24944. * @property {Phaser.Point} world - The world coordinates of this Sprite. This differs from the x/y coordinates which are relative to the Sprites container.
  24945. */
  24946. this.world = new Phaser.Point(x, y);
  24947. /**
  24948. * Should this Sprite be automatically culled if out of range of the camera?
  24949. * A culled sprite has its renderable property set to 'false'.
  24950. * Be advised this is quite an expensive operation, as it has to calculate the bounds of the object every frame, so only enable it if you really need it.
  24951. *
  24952. * @property {boolean} autoCull - A flag indicating if the Sprite should be automatically camera culled or not.
  24953. * @default
  24954. */
  24955. this.autoCull = false;
  24956. /**
  24957. * @property {Phaser.InputHandler|null} input - The Input Handler for this object. Needs to be enabled with image.inputEnabled = true before you can use it.
  24958. */
  24959. this.input = null;
  24960. /**
  24961. * By default Sprites won't add themselves to any physics system and their physics body will be `null`.
  24962. * To enable them for physics you need to call `game.physics.enable(sprite, system)` where `sprite` is this object
  24963. * and `system` is the Physics system you want to use to manage this body. Once enabled you can access all physics related properties via `Sprite.body`.
  24964. *
  24965. * Important: Enabling a Sprite for P2 or Ninja physics will automatically set `Sprite.anchor` to 0.5 so the physics body is centered on the Sprite.
  24966. * If you need a different result then adjust or re-create the Body shape offsets manually, and/or reset the anchor after enabling physics.
  24967. *
  24968. * @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body
  24969. * @default
  24970. */
  24971. this.body = null;
  24972. /**
  24973. * @property {boolean} alive - A useful boolean to control if the Sprite is alive or dead (in terms of your gameplay, it doesn't effect rendering). Also linked to Sprite.health and Sprite.damage.
  24974. * @default
  24975. */
  24976. this.alive = true;
  24977. /**
  24978. * @property {number} health - Health value. Used in combination with damage() to allow for quick killing of Sprites.
  24979. */
  24980. this.health = 1;
  24981. /**
  24982. * If you would like the Sprite to have a lifespan once 'born' you can set this to a positive value. Handy for particles, bullets, etc.
  24983. * The lifespan is decremented by game.time.elapsed each update, once it reaches zero the kill() function is called.
  24984. * @property {number} lifespan - The lifespan of the Sprite (in ms) before it will be killed.
  24985. * @default
  24986. */
  24987. this.lifespan = 0;
  24988. /**
  24989. * If true the Sprite checks if it is still within the world each frame, when it leaves the world it dispatches Sprite.events.onOutOfBounds
  24990. * and optionally kills the sprite (if Sprite.outOfBoundsKill is true). By default this is disabled because the Sprite has to calculate its
  24991. * bounds every frame to support it, and not all games need it. Enable it by setting the value to true.
  24992. * @property {boolean} checkWorldBounds
  24993. * @default
  24994. */
  24995. this.checkWorldBounds = false;
  24996. /**
  24997. * @property {boolean} outOfBoundsKill - If true Sprite.kill is called as soon as Sprite.inWorld returns false, as long as Sprite.checkWorldBounds is true.
  24998. * @default
  24999. */
  25000. this.outOfBoundsKill = false;
  25001. /**
  25002. * @property {boolean} debug - Handy flag to use with Game.enableStep
  25003. * @default
  25004. */
  25005. this.debug = false;
  25006. /**
  25007. * @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
  25008. */
  25009. this.cameraOffset = new Phaser.Point();
  25010. /**
  25011. * @property {Phaser.Rectangle} cropRect - The Rectangle used to crop the texture. Set this via Sprite.crop. Any time you modify this property directly you must call Sprite.updateCrop.
  25012. * @default
  25013. */
  25014. this.cropRect = null;
  25015. /**
  25016. * A small internal cache:
  25017. *
  25018. * 0 = previous position.x
  25019. * 1 = previous position.y
  25020. * 2 = previous rotation
  25021. * 3 = renderID
  25022. * 4 = fresh? (0 = no, 1 = yes)
  25023. * 5 = outOfBoundsFired (0 = no, 1 = yes)
  25024. * 6 = exists (0 = no, 1 = yes)
  25025. * 7 = fixed to camera (0 = no, 1 = yes)
  25026. * 8 = destroy phase? (0 = no, 1 = yes)
  25027. * @property {Array} _cache
  25028. * @private
  25029. */
  25030. this._cache = [ 0, 0, 0, 0, 1, 0, 1, 0 ];
  25031. /**
  25032. * @property {Phaser.Rectangle} _crop - Internal cache var.
  25033. * @private
  25034. */
  25035. this._crop = null;
  25036. /**
  25037. * @property {Phaser.Rectangle} _frame - Internal cache var.
  25038. * @private
  25039. */
  25040. this._frame = null;
  25041. /**
  25042. * @property {Phaser.Rectangle} _bounds - Internal cache var.
  25043. * @private
  25044. */
  25045. this._bounds = new Phaser.Rectangle();
  25046. this.loadTexture(key, frame);
  25047. };
  25048. Phaser.Sprite.prototype = Object.create(PIXI.Sprite.prototype);
  25049. Phaser.Sprite.prototype.constructor = Phaser.Sprite;
  25050. /**
  25051. * Automatically called by World.preUpdate.
  25052. *
  25053. * @method Phaser.Sprite#preUpdate
  25054. * @memberof Phaser.Sprite
  25055. * @return {boolean} True if the Sprite was rendered, otherwise false.
  25056. */
  25057. Phaser.Sprite.prototype.preUpdate = function() {
  25058. if (this._cache[4] === 1 && this.exists)
  25059. {
  25060. this.world.setTo(this.parent.position.x + this.position.x, this.parent.position.y + this.position.y);
  25061. this.worldTransform.tx = this.world.x;
  25062. this.worldTransform.ty = this.world.y;
  25063. this._cache[0] = this.world.x;
  25064. this._cache[1] = this.world.y;
  25065. this._cache[2] = this.rotation;
  25066. if (this.body)
  25067. {
  25068. this.body.preUpdate();
  25069. }
  25070. this._cache[4] = 0;
  25071. return false;
  25072. }
  25073. this._cache[0] = this.world.x;
  25074. this._cache[1] = this.world.y;
  25075. this._cache[2] = this.rotation;
  25076. if (!this.exists || !this.parent.exists)
  25077. {
  25078. // Reset the renderOrderID
  25079. this._cache[3] = -1;
  25080. return false;
  25081. }
  25082. if (this.lifespan > 0)
  25083. {
  25084. this.lifespan -= this.game.time.elapsed;
  25085. if (this.lifespan <= 0)
  25086. {
  25087. this.kill();
  25088. return false;
  25089. }
  25090. }
  25091. // Cache the bounds if we need it
  25092. if (this.autoCull || this.checkWorldBounds)
  25093. {
  25094. this._bounds.copyFrom(this.getBounds());
  25095. }
  25096. if (this.autoCull)
  25097. {
  25098. // Won't get rendered but will still get its transform updated
  25099. this.renderable = this.game.world.camera.screenView.intersects(this._bounds);
  25100. }
  25101. if (this.checkWorldBounds)
  25102. {
  25103. // The Sprite is already out of the world bounds, so let's check to see if it has come back again
  25104. if (this._cache[5] === 1 && this.game.world.bounds.intersects(this._bounds))
  25105. {
  25106. this._cache[5] = 0;
  25107. this.events.onEnterBounds.dispatch(this);
  25108. }
  25109. else if (this._cache[5] === 0 && !this.game.world.bounds.intersects(this._bounds))
  25110. {
  25111. // The Sprite WAS in the screen, but has now left.
  25112. this._cache[5] = 1;
  25113. this.events.onOutOfBounds.dispatch(this);
  25114. if (this.outOfBoundsKill)
  25115. {
  25116. this.kill();
  25117. return false;
  25118. }
  25119. }
  25120. }
  25121. this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty);
  25122. if (this.visible)
  25123. {
  25124. this._cache[3] = this.game.stage.currentRenderOrderID++;
  25125. }
  25126. this.animations.update();
  25127. if (this.body)
  25128. {
  25129. this.body.preUpdate();
  25130. }
  25131. // Update any Children
  25132. for (var i = 0, len = this.children.length; i < len; i++)
  25133. {
  25134. this.children[i].preUpdate();
  25135. }
  25136. return true;
  25137. };
  25138. /**
  25139. * Override and use this function in your own custom objects to handle any update requirements you may have.
  25140. * Remember if this Sprite has any children you should call update on them too.
  25141. *
  25142. * @method Phaser.Sprite#update
  25143. * @memberof Phaser.Sprite
  25144. */
  25145. Phaser.Sprite.prototype.update = function() {
  25146. };
  25147. /**
  25148. * Internal function called by the World postUpdate cycle.
  25149. *
  25150. * @method Phaser.Sprite#postUpdate
  25151. * @memberof Phaser.Sprite
  25152. */
  25153. Phaser.Sprite.prototype.postUpdate = function() {
  25154. if (this.key instanceof Phaser.BitmapData)
  25155. {
  25156. this.key.render();
  25157. }
  25158. if (this.exists && this.body)
  25159. {
  25160. this.body.postUpdate();
  25161. }
  25162. // Fixed to Camera?
  25163. if (this._cache[7] === 1)
  25164. {
  25165. this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
  25166. this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
  25167. }
  25168. // Update any Children
  25169. for (var i = 0, len = this.children.length; i < len; i++)
  25170. {
  25171. this.children[i].postUpdate();
  25172. }
  25173. };
  25174. /**
  25175. * Changes the Texture the Sprite is using entirely. The old texture is removed and the new one is referenced or fetched from the Cache.
  25176. * This causes a WebGL texture update, so use sparingly or in low-intensity portions of your game.
  25177. *
  25178. * @method Phaser.Sprite#loadTexture
  25179. * @memberof Phaser.Sprite
  25180. * @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, BitmapData or PIXI.Texture.
  25181. * @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.
  25182. * @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.
  25183. */
  25184. Phaser.Sprite.prototype.loadTexture = function (key, frame, stopAnimation) {
  25185. frame = frame || 0;
  25186. if (stopAnimation || typeof stopAnimation === 'undefined')
  25187. {
  25188. this.animations.stop();
  25189. }
  25190. this.key = key;
  25191. var setFrame = true;
  25192. var smoothed = this.smoothed;
  25193. if (key instanceof Phaser.RenderTexture)
  25194. {
  25195. this.key = key.key;
  25196. this.setTexture(key);
  25197. }
  25198. else if (key instanceof Phaser.BitmapData)
  25199. {
  25200. this.setTexture(key.texture);
  25201. }
  25202. else if (key instanceof PIXI.Texture)
  25203. {
  25204. this.setTexture(key);
  25205. }
  25206. else
  25207. {
  25208. if (key === null || typeof key === 'undefined')
  25209. {
  25210. this.key = '__default';
  25211. this.setTexture(PIXI.TextureCache[this.key]);
  25212. }
  25213. else if (typeof key === 'string' && !this.game.cache.checkImageKey(key))
  25214. {
  25215. console.warn("Texture with key '" + key + "' not found.");
  25216. this.key = '__missing';
  25217. this.setTexture(PIXI.TextureCache[this.key]);
  25218. }
  25219. else
  25220. {
  25221. this.setTexture(new PIXI.Texture(PIXI.BaseTextureCache[key]));
  25222. setFrame = !this.animations.loadFrameData(this.game.cache.getFrameData(key), frame);
  25223. }
  25224. }
  25225. if (setFrame)
  25226. {
  25227. this._frame = Phaser.Rectangle.clone(this.texture.frame);
  25228. }
  25229. if (!smoothed)
  25230. {
  25231. this.smoothed = false;
  25232. }
  25233. };
  25234. /**
  25235. * Sets the Texture frame the Sprite uses for rendering.
  25236. * This is primarily an internal method used by Sprite.loadTexture, although you may call it directly.
  25237. *
  25238. * @method Phaser.Sprite#setFrame
  25239. * @memberof Phaser.Sprite
  25240. * @param {Phaser.Frame} frame - The Frame to be used by the Sprite texture.
  25241. */
  25242. Phaser.Sprite.prototype.setFrame = function(frame) {
  25243. this._frame = frame;
  25244. this.texture.frame.x = frame.x;
  25245. this.texture.frame.y = frame.y;
  25246. this.texture.frame.width = frame.width;
  25247. this.texture.frame.height = frame.height;
  25248. this.texture.crop.x = frame.x;
  25249. this.texture.crop.y = frame.y;
  25250. this.texture.crop.width = frame.width;
  25251. this.texture.crop.height = frame.height;
  25252. if (frame.trimmed)
  25253. {
  25254. if (this.texture.trim)
  25255. {
  25256. this.texture.trim.x = frame.spriteSourceSizeX;
  25257. this.texture.trim.y = frame.spriteSourceSizeY;
  25258. this.texture.trim.width = frame.sourceSizeW;
  25259. this.texture.trim.height = frame.sourceSizeH;
  25260. }
  25261. else
  25262. {
  25263. this.texture.trim = { x: frame.spriteSourceSizeX, y: frame.spriteSourceSizeY, width: frame.sourceSizeW, height: frame.sourceSizeH };
  25264. }
  25265. this.texture.width = frame.sourceSizeW;
  25266. this.texture.height = frame.sourceSizeH;
  25267. this.texture.frame.width = frame.sourceSizeW;
  25268. this.texture.frame.height = frame.sourceSizeH;
  25269. }
  25270. if (this.cropRect)
  25271. {
  25272. this.updateCrop();
  25273. }
  25274. else
  25275. {
  25276. if (this.game.renderType === Phaser.WEBGL)
  25277. {
  25278. PIXI.WebGLRenderer.updateTextureFrame(this.texture);
  25279. }
  25280. }
  25281. };
  25282. /**
  25283. * Resets the Texture frame dimensions that the Sprite uses for rendering.
  25284. *
  25285. * @method Phaser.Sprite#resetFrame
  25286. * @memberof Phaser.Sprite
  25287. */
  25288. Phaser.Sprite.prototype.resetFrame = function() {
  25289. if (this._frame)
  25290. {
  25291. this.setFrame(this._frame);
  25292. }
  25293. };
  25294. /**
  25295. * Crop allows you to crop the texture used to display this Sprite.
  25296. * This modifies the core Sprite texture frame, so the Sprite width/height properties will adjust accordingly.
  25297. *
  25298. * Cropping takes place from the top-left of the Sprite and can be modified in real-time by either providing an updated rectangle object to Sprite.crop,
  25299. * or by modifying Sprite.cropRect (or a reference to it) and then calling Sprite.updateCrop.
  25300. *
  25301. * The rectangle object given to this method can be either a Phaser.Rectangle or any object so long as it has public x, y, width and height properties.
  25302. * A reference to the rectangle is stored in Sprite.cropRect unless the `copy` parameter is `true` in which case the values are duplicated to a local object.
  25303. *
  25304. * @method Phaser.Sprite#crop
  25305. * @memberof Phaser.Sprite
  25306. * @param {Phaser.Rectangle} rect - The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle.
  25307. * @param {boolean} [copy=false] - If false Sprite.cropRect will be a reference to the given rect. If true it will copy the rect values into a local Sprite.cropRect object.
  25308. */
  25309. Phaser.Sprite.prototype.crop = function(rect, copy) {
  25310. if (typeof copy === 'undefined') { copy = false; }
  25311. if (rect)
  25312. {
  25313. if (copy && this.cropRect !== null)
  25314. {
  25315. this.cropRect.setTo(rect.x, rect.y, rect.width, rect.height);
  25316. }
  25317. else if (copy && this.cropRect === null)
  25318. {
  25319. this.cropRect = new Phaser.Rectangle(rect.x, rect.y, rect.width, rect.height);
  25320. }
  25321. else
  25322. {
  25323. this.cropRect = rect;
  25324. }
  25325. this.updateCrop();
  25326. }
  25327. else
  25328. {
  25329. this._crop = null;
  25330. this.cropRect = null;
  25331. this.resetFrame();
  25332. }
  25333. };
  25334. /**
  25335. * If you have set a crop rectangle on this Sprite via Sprite.crop and since modified the Sprite.cropRect property (or the rectangle it references)
  25336. * then you need to update the crop frame by calling this method.
  25337. *
  25338. * @method Phaser.Sprite#updateCrop
  25339. * @memberof Phaser.Sprite
  25340. */
  25341. Phaser.Sprite.prototype.updateCrop = function() {
  25342. if (!this.cropRect)
  25343. {
  25344. return;
  25345. }
  25346. this._crop = Phaser.Rectangle.clone(this.cropRect, this._crop);
  25347. this._crop.x += this._frame.x;
  25348. this._crop.y += this._frame.y;
  25349. var cx = Math.max(this._frame.x, this._crop.x);
  25350. var cy = Math.max(this._frame.y, this._crop.y);
  25351. var cw = Math.min(this._frame.right, this._crop.right) - cx;
  25352. var ch = Math.min(this._frame.bottom, this._crop.bottom) - cy;
  25353. this.texture.crop.x = cx;
  25354. this.texture.crop.y = cy;
  25355. this.texture.crop.width = cw;
  25356. this.texture.crop.height = ch;
  25357. this.texture.frame.width = Math.min(cw, this.cropRect.width);
  25358. this.texture.frame.height = Math.min(ch, this.cropRect.height);
  25359. this.texture.width = this.texture.frame.width;
  25360. this.texture.height = this.texture.frame.height;
  25361. if (this.game.renderType === Phaser.WEBGL)
  25362. {
  25363. PIXI.WebGLRenderer.updateTextureFrame(this.texture);
  25364. }
  25365. };
  25366. /**
  25367. * Brings a 'dead' Sprite back to life, optionally giving it the health value specified.
  25368. * A resurrected Sprite has its alive, exists and visible properties all set to true.
  25369. * It will dispatch the onRevived event, you can listen to Sprite.events.onRevived for the signal.
  25370. *
  25371. * @method Phaser.Sprite#revive
  25372. * @memberof Phaser.Sprite
  25373. * @param {number} [health=1] - The health to give the Sprite.
  25374. * @return (Phaser.Sprite) This instance.
  25375. */
  25376. Phaser.Sprite.prototype.revive = function(health) {
  25377. if (typeof health === 'undefined') { health = 1; }
  25378. this.alive = true;
  25379. this.exists = true;
  25380. this.visible = true;
  25381. this.health = health;
  25382. if (this.events)
  25383. {
  25384. this.events.onRevived.dispatch(this);
  25385. }
  25386. return this;
  25387. };
  25388. /**
  25389. * Kills a Sprite. A killed Sprite has its alive, exists and visible properties all set to false.
  25390. * It will dispatch the onKilled event, you can listen to Sprite.events.onKilled for the signal.
  25391. * Note that killing a Sprite is a way for you to quickly recycle it in a Sprite pool, it doesn't free it up from memory.
  25392. * If you don't need this Sprite any more you should call Sprite.destroy instead.
  25393. *
  25394. * @method Phaser.Sprite#kill
  25395. * @memberof Phaser.Sprite
  25396. * @return (Phaser.Sprite) This instance.
  25397. */
  25398. Phaser.Sprite.prototype.kill = function() {
  25399. this.alive = false;
  25400. this.exists = false;
  25401. this.visible = false;
  25402. if (this.events)
  25403. {
  25404. this.events.onKilled.dispatch(this);
  25405. }
  25406. return this;
  25407. };
  25408. /**
  25409. * Destroys the Sprite. This removes it from its parent group, destroys the input, event and animation handlers if present
  25410. * and nulls its reference to game, freeing it up for garbage collection.
  25411. *
  25412. * @method Phaser.Sprite#destroy
  25413. * @memberof Phaser.Sprite
  25414. * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
  25415. */
  25416. Phaser.Sprite.prototype.destroy = function(destroyChildren) {
  25417. if (this.game === null || this._cache[8] === 1) { return; }
  25418. if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
  25419. this._cache[8] = 1;
  25420. if (this.parent)
  25421. {
  25422. if (this.parent instanceof Phaser.Group)
  25423. {
  25424. this.parent.remove(this);
  25425. }
  25426. else
  25427. {
  25428. this.parent.removeChild(this);
  25429. }
  25430. }
  25431. if (this.input)
  25432. {
  25433. this.input.destroy();
  25434. }
  25435. if (this.animations)
  25436. {
  25437. this.animations.destroy();
  25438. }
  25439. if (this.body)
  25440. {
  25441. this.body.destroy();
  25442. }
  25443. if (this.events)
  25444. {
  25445. this.events.destroy();
  25446. }
  25447. var i = this.children.length;
  25448. if (destroyChildren)
  25449. {
  25450. while (i--)
  25451. {
  25452. this.children[i].destroy(destroyChildren);
  25453. }
  25454. }
  25455. else
  25456. {
  25457. while (i--)
  25458. {
  25459. this.removeChild(this.children[i]);
  25460. }
  25461. }
  25462. if (this._crop)
  25463. {
  25464. this._crop = null;
  25465. }
  25466. if (this._frame)
  25467. {
  25468. this._frame = null;
  25469. }
  25470. this.alive = false;
  25471. this.exists = false;
  25472. this.visible = false;
  25473. this.filters = null;
  25474. this.mask = null;
  25475. this.game = null;
  25476. this._cache[8] = 0;
  25477. };
  25478. /**
  25479. * Damages the Sprite, this removes the given amount from the Sprites health property.
  25480. * If health is then taken below or is equal to zero `Sprite.kill` is called.
  25481. *
  25482. * @method Phaser.Sprite#damage
  25483. * @memberof Phaser.Sprite
  25484. * @param {number} amount - The amount to subtract from the Sprite.health value.
  25485. * @return (Phaser.Sprite) This instance.
  25486. */
  25487. Phaser.Sprite.prototype.damage = function(amount) {
  25488. if (this.alive)
  25489. {
  25490. this.health -= amount;
  25491. if (this.health <= 0)
  25492. {
  25493. this.kill();
  25494. }
  25495. }
  25496. return this;
  25497. };
  25498. /**
  25499. * Resets the Sprite. This places the Sprite at the given x/y world coordinates and then
  25500. * sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values.
  25501. * If the Sprite has a physics body that too is reset.
  25502. *
  25503. * @method Phaser.Sprite#reset
  25504. * @memberof Phaser.Sprite
  25505. * @param {number} x - The x coordinate (in world space) to position the Sprite at.
  25506. * @param {number} y - The y coordinate (in world space) to position the Sprite at.
  25507. * @param {number} [health=1] - The health to give the Sprite.
  25508. * @return (Phaser.Sprite) This instance.
  25509. */
  25510. Phaser.Sprite.prototype.reset = function(x, y, health) {
  25511. if (typeof health === 'undefined') { health = 1; }
  25512. this.world.setTo(x, y);
  25513. this.position.x = x;
  25514. this.position.y = y;
  25515. this.alive = true;
  25516. this.exists = true;
  25517. this.visible = true;
  25518. this.renderable = true;
  25519. this._outOfBoundsFired = false;
  25520. this.health = health;
  25521. if (this.body)
  25522. {
  25523. this.body.reset(x, y, false, false);
  25524. }
  25525. this._cache[4] = 1;
  25526. return this;
  25527. };
  25528. /**
  25529. * Brings the Sprite to the top of the display list it is a child of. Sprites that are members of a Phaser.Group are only
  25530. * bought to the top of that Group, not the entire display list.
  25531. *
  25532. * @method Phaser.Sprite#bringToTop
  25533. * @memberof Phaser.Sprite
  25534. * @return (Phaser.Sprite) This instance.
  25535. */
  25536. Phaser.Sprite.prototype.bringToTop = function() {
  25537. if (this.parent)
  25538. {
  25539. this.parent.bringToTop(this);
  25540. }
  25541. return this;
  25542. };
  25543. /**
  25544. * Play an animation based on the given key. The animation should previously have been added via sprite.animations.add()
  25545. * If the requested animation is already playing this request will be ignored. If you need to reset an already running animation do so directly on the Animation object itself.
  25546. *
  25547. * @method Phaser.Sprite#play
  25548. * @memberof Phaser.Sprite
  25549. * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump".
  25550. * @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.
  25551. * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
  25552. * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
  25553. * @return {Phaser.Animation} A reference to playing Animation instance.
  25554. */
  25555. Phaser.Sprite.prototype.play = function (name, frameRate, loop, killOnComplete) {
  25556. if (this.animations)
  25557. {
  25558. return this.animations.play(name, frameRate, loop, killOnComplete);
  25559. }
  25560. };
  25561. /**
  25562. * Checks to see if the bounds of this Sprite overlaps with the bounds of the given Display Object, which can be a Sprite, Image, TileSprite or anything that extends those such as a Button.
  25563. * This check ignores the Sprites hitArea property and runs a Sprite.getBounds comparison on both objects to determine the result.
  25564. * Therefore it's relatively expensive to use in large quantities (i.e. with lots of Sprites at a high frequency), but should be fine for low-volume testing where physics isn't required.
  25565. *
  25566. * @method Phaser.Sprite#overlap
  25567. * @memberof Phaser.Sprite
  25568. * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Button|PIXI.DisplayObject} displayObject - The display object to check against.
  25569. * @return {boolean} True if the bounds of this Sprite intersects at any point with the bounds of the given display object.
  25570. */
  25571. Phaser.Sprite.prototype.overlap = function (displayObject) {
  25572. return Phaser.Rectangle.intersects(this.getBounds(), displayObject.getBounds());
  25573. };
  25574. /**
  25575. * Indicates the rotation of the Sprite, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
  25576. * Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
  25577. * If you wish to work in radians instead of degrees use the property Sprite.rotation instead. Working in radians is also a little faster as it doesn't have to convert the angle.
  25578. *
  25579. * @name Phaser.Sprite#angle
  25580. * @property {number} angle - The angle of this Sprite in degrees.
  25581. */
  25582. Object.defineProperty(Phaser.Sprite.prototype, "angle", {
  25583. get: function() {
  25584. return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation));
  25585. },
  25586. set: function(value) {
  25587. this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value));
  25588. }
  25589. });
  25590. /**
  25591. * Returns the delta x value. The difference between world.x now and in the previous step.
  25592. *
  25593. * @name Phaser.Sprite#deltaX
  25594. * @property {number} deltaX - The delta value. Positive if the motion was to the right, negative if to the left.
  25595. * @readonly
  25596. */
  25597. Object.defineProperty(Phaser.Sprite.prototype, "deltaX", {
  25598. get: function() {
  25599. return this.world.x - this._cache[0];
  25600. }
  25601. });
  25602. /**
  25603. * Returns the delta y value. The difference between world.y now and in the previous step.
  25604. *
  25605. * @name Phaser.Sprite#deltaY
  25606. * @property {number} deltaY - The delta value. Positive if the motion was downwards, negative if upwards.
  25607. * @readonly
  25608. */
  25609. Object.defineProperty(Phaser.Sprite.prototype, "deltaY", {
  25610. get: function() {
  25611. return this.world.y - this._cache[1];
  25612. }
  25613. });
  25614. /**
  25615. * Returns the delta z value. The difference between rotation now and in the previous step.
  25616. *
  25617. * @name Phaser.Sprite#deltaZ
  25618. * @property {number} deltaZ - The delta value.
  25619. * @readonly
  25620. */
  25621. Object.defineProperty(Phaser.Sprite.prototype, "deltaZ", {
  25622. get: function() {
  25623. return this.rotation - this._cache[2];
  25624. }
  25625. });
  25626. /**
  25627. * Checks if the Sprite bounds are within the game world, otherwise false if fully outside of it.
  25628. *
  25629. * @name Phaser.Sprite#inWorld
  25630. * @property {boolean} inWorld - True if the Sprite bounds is within the game world, even if only partially. Otherwise false if fully outside of it.
  25631. * @readonly
  25632. */
  25633. Object.defineProperty(Phaser.Sprite.prototype, "inWorld", {
  25634. get: function() {
  25635. return this.game.world.bounds.intersects(this.getBounds());
  25636. }
  25637. });
  25638. /**
  25639. * Checks if the Sprite bounds are within the game camera, otherwise false if fully outside of it.
  25640. *
  25641. * @name Phaser.Sprite#inCamera
  25642. * @property {boolean} inCamera - True if the Sprite bounds is within the game camera, even if only partially. Otherwise false if fully outside of it.
  25643. * @readonly
  25644. */
  25645. Object.defineProperty(Phaser.Sprite.prototype, "inCamera", {
  25646. get: function() {
  25647. return this.game.world.camera.screenView.intersects(this.getBounds());
  25648. }
  25649. });
  25650. /**
  25651. * @name Phaser.Sprite#frame
  25652. * @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
  25653. */
  25654. Object.defineProperty(Phaser.Sprite.prototype, "frame", {
  25655. get: function () {
  25656. return this.animations.frame;
  25657. },
  25658. set: function (value) {
  25659. this.animations.frame = value;
  25660. }
  25661. });
  25662. /**
  25663. * @name Phaser.Sprite#frameName
  25664. * @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display.
  25665. */
  25666. Object.defineProperty(Phaser.Sprite.prototype, "frameName", {
  25667. get: function () {
  25668. return this.animations.frameName;
  25669. },
  25670. set: function (value) {
  25671. this.animations.frameName = value;
  25672. }
  25673. });
  25674. /**
  25675. * @name Phaser.Sprite#renderOrderID
  25676. * @property {number} renderOrderID - The render order ID, reset every frame.
  25677. * @readonly
  25678. */
  25679. Object.defineProperty(Phaser.Sprite.prototype, "renderOrderID", {
  25680. get: function() {
  25681. return this._cache[3];
  25682. }
  25683. });
  25684. /**
  25685. * By default a Sprite won't process any input events at all. By setting inputEnabled to true the Phaser.InputHandler is
  25686. * activated for this object and it will then start to process click/touch events and more.
  25687. *
  25688. * @name Phaser.Sprite#inputEnabled
  25689. * @property {boolean} inputEnabled - Set to true to allow this object to receive input events.
  25690. */
  25691. Object.defineProperty(Phaser.Sprite.prototype, "inputEnabled", {
  25692. get: function () {
  25693. return (this.input && this.input.enabled);
  25694. },
  25695. set: function (value) {
  25696. if (value)
  25697. {
  25698. if (this.input === null)
  25699. {
  25700. this.input = new Phaser.InputHandler(this);
  25701. this.input.start();
  25702. }
  25703. else if (this.input && !this.input.enabled)
  25704. {
  25705. this.input.start();
  25706. }
  25707. }
  25708. else
  25709. {
  25710. if (this.input && this.input.enabled)
  25711. {
  25712. this.input.stop();
  25713. }
  25714. }
  25715. }
  25716. });
  25717. /**
  25718. * Sprite.exists controls if the core game loop and physics update this Sprite or not.
  25719. * When you set Sprite.exists to false it will remove its Body from the physics world (if it has one) and also set Sprite.visible to false.
  25720. * Setting Sprite.exists to true will re-add the Body to the physics world (if it has a body) and set Sprite.visible to true.
  25721. *
  25722. * @name Phaser.Sprite#exists
  25723. * @property {boolean} exists - If the Sprite is processed by the core game update and physics.
  25724. */
  25725. Object.defineProperty(Phaser.Sprite.prototype, "exists", {
  25726. get: function () {
  25727. return !!this._cache[6];
  25728. },
  25729. set: function (value) {
  25730. if (value)
  25731. {
  25732. // exists = true
  25733. this._cache[6] = 1;
  25734. if (this.body && this.body.type === Phaser.Physics.P2JS)
  25735. {
  25736. this.body.addToWorld();
  25737. }
  25738. this.visible = true;
  25739. }
  25740. else
  25741. {
  25742. // exists = false
  25743. this._cache[6] = 0;
  25744. if (this.body && this.body.type === Phaser.Physics.P2JS)
  25745. {
  25746. this.body.removeFromWorld();
  25747. }
  25748. this.visible = false;
  25749. }
  25750. }
  25751. });
  25752. /**
  25753. * An Sprite that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Sprite.cameraOffset.
  25754. * Note that the cameraOffset values are in addition to any parent in the display list.
  25755. * So if this Sprite was in a Group that has x: 200, then this will be added to the cameraOffset.x
  25756. *
  25757. * @name Phaser.Sprite#fixedToCamera
  25758. * @property {boolean} fixedToCamera - Set to true to fix this Sprite to the Camera at its current world coordinates.
  25759. */
  25760. Object.defineProperty(Phaser.Sprite.prototype, "fixedToCamera", {
  25761. get: function () {
  25762. return !!this._cache[7];
  25763. },
  25764. set: function (value) {
  25765. if (value)
  25766. {
  25767. this._cache[7] = 1;
  25768. this.cameraOffset.set(this.x, this.y);
  25769. }
  25770. else
  25771. {
  25772. this._cache[7] = 0;
  25773. }
  25774. }
  25775. });
  25776. /**
  25777. * Enable or disable texture smoothing for this Sprite. Only works for bitmap/image textures. Smoothing is enabled by default.
  25778. *
  25779. * @name Phaser.Sprite#smoothed
  25780. * @property {boolean} smoothed - Set to true to smooth the texture of this Sprite, or false to disable smoothing (great for pixel art)
  25781. */
  25782. Object.defineProperty(Phaser.Sprite.prototype, "smoothed", {
  25783. get: function () {
  25784. return !this.texture.baseTexture.scaleMode;
  25785. },
  25786. set: function (value) {
  25787. if (value)
  25788. {
  25789. if (this.texture)
  25790. {
  25791. this.texture.baseTexture.scaleMode = 0;
  25792. }
  25793. }
  25794. else
  25795. {
  25796. if (this.texture)
  25797. {
  25798. this.texture.baseTexture.scaleMode = 1;
  25799. }
  25800. }
  25801. }
  25802. });
  25803. /**
  25804. * The position of the Sprite on the x axis relative to the local coordinates of the parent.
  25805. *
  25806. * @name Phaser.Sprite#x
  25807. * @property {number} x - The position of the Sprite on the x axis relative to the local coordinates of the parent.
  25808. */
  25809. Object.defineProperty(Phaser.Sprite.prototype, "x", {
  25810. get: function () {
  25811. return this.position.x;
  25812. },
  25813. set: function (value) {
  25814. this.position.x = value;
  25815. if (this.body && this.body.type === Phaser.Physics.ARCADE && this.body.phase === 2)
  25816. {
  25817. this.body._reset = 1;
  25818. }
  25819. }
  25820. });
  25821. /**
  25822. * The position of the Sprite on the y axis relative to the local coordinates of the parent.
  25823. *
  25824. * @name Phaser.Sprite#y
  25825. * @property {number} y - The position of the Sprite on the y axis relative to the local coordinates of the parent.
  25826. */
  25827. Object.defineProperty(Phaser.Sprite.prototype, "y", {
  25828. get: function () {
  25829. return this.position.y;
  25830. },
  25831. set: function (value) {
  25832. this.position.y = value;
  25833. if (this.body && this.body.type === Phaser.Physics.ARCADE && this.body.phase === 2)
  25834. {
  25835. this.body._reset = 1;
  25836. }
  25837. }
  25838. });
  25839. /**
  25840. * @name Phaser.Sprite#destroyPhase
  25841. * @property {boolean} destroyPhase - True if this object is currently being destroyed.
  25842. */
  25843. Object.defineProperty(Phaser.Sprite.prototype, "destroyPhase", {
  25844. get: function () {
  25845. return !!this._cache[8];
  25846. }
  25847. });
  25848. /**
  25849. * @author Richard Davey <rich@photonstorm.com>
  25850. * @copyright 2014 Photon Storm Ltd.
  25851. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  25852. */
  25853. /**
  25854. * @class Phaser.Image
  25855. *
  25856. * @classdesc Create a new `Image` object. An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
  25857. * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
  25858. *
  25859. * @constructor
  25860. * @param {Phaser.Game} game - A reference to the currently running game.
  25861. * @param {number} x - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
  25862. * @param {number} y - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
  25863. * @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.
  25864. * @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.
  25865. */
  25866. Phaser.Image = function (game, x, y, key, frame) {
  25867. x = x || 0;
  25868. y = y || 0;
  25869. key = key || null;
  25870. frame = frame || null;
  25871. /**
  25872. * @property {Phaser.Game} game - A reference to the currently running Game.
  25873. */
  25874. this.game = game;
  25875. /**
  25876. * @property {boolean} exists - If exists = false then the Image isn't updated by the core game loop.
  25877. * @default
  25878. */
  25879. this.exists = true;
  25880. /**
  25881. * @property {string} name - The user defined name given to this Image.
  25882. * @default
  25883. */
  25884. this.name = '';
  25885. /**
  25886. * @property {number} type - The const type of this object.
  25887. * @readonly
  25888. */
  25889. this.type = Phaser.IMAGE;
  25890. /**
  25891. * @property {number} z - The z-depth value of this object within its Group (remember the World is a Group as well). No two objects in a Group can have the same z value.
  25892. */
  25893. this.z = 0;
  25894. /**
  25895. * @property {Phaser.Events} events - The Events you can subscribe to that are dispatched when certain things happen on this Image or its components.
  25896. */
  25897. this.events = new Phaser.Events(this);
  25898. /**
  25899. * @property {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or 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.
  25900. */
  25901. this.key = key;
  25902. /**
  25903. * @property {number} _frame - Internal cache var.
  25904. * @private
  25905. */
  25906. this._frame = 0;
  25907. /**
  25908. * @property {string} _frameName - Internal cache var.
  25909. * @private
  25910. */
  25911. this._frameName = '';
  25912. PIXI.Sprite.call(this, PIXI.TextureCache['__default']);
  25913. this.loadTexture(key, frame);
  25914. this.position.set(x, y);
  25915. /**
  25916. * @property {Phaser.Point} world - The world coordinates of this Image. This differs from the x/y coordinates which are relative to the Images container.
  25917. */
  25918. this.world = new Phaser.Point(x, y);
  25919. /**
  25920. * Should this Image be automatically culled if out of range of the camera?
  25921. * A culled sprite has its renderable property set to 'false'.
  25922. * Be advised this is quite an expensive operation, as it has to calculate the bounds of the object every frame, so only enable it if you really need it.
  25923. *
  25924. * @property {boolean} autoCull - A flag indicating if the Image should be automatically camera culled or not.
  25925. * @default
  25926. */
  25927. this.autoCull = false;
  25928. /**
  25929. * @property {Phaser.InputHandler|null} input - The Input Handler for this object. Needs to be enabled with image.inputEnabled = true before you can use it.
  25930. */
  25931. this.input = null;
  25932. /**
  25933. * @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
  25934. */
  25935. this.cameraOffset = new Phaser.Point();
  25936. /**
  25937. * A small internal cache:
  25938. * 0 = previous position.x
  25939. * 1 = previous position.y
  25940. * 2 = previous rotation
  25941. * 3 = renderID
  25942. * 4 = fresh? (0 = no, 1 = yes)
  25943. * 5 = outOfBoundsFired (0 = no, 1 = yes)
  25944. * 6 = exists (0 = no, 1 = yes)
  25945. * 7 = fixed to camera (0 = no, 1 = yes)
  25946. * 8 = destroy phase? (0 = no, 1 = yes)
  25947. * @property {Array} _cache
  25948. * @private
  25949. */
  25950. this._cache = [ 0, 0, 0, 0, 1, 0, 1, 0, 0 ];
  25951. };
  25952. Phaser.Image.prototype = Object.create(PIXI.Sprite.prototype);
  25953. Phaser.Image.prototype.constructor = Phaser.Image;
  25954. /**
  25955. * Automatically called by World.preUpdate.
  25956. *
  25957. * @method Phaser.Image#preUpdate
  25958. * @memberof Phaser.Image
  25959. */
  25960. Phaser.Image.prototype.preUpdate = function() {
  25961. this._cache[0] = this.world.x;
  25962. this._cache[1] = this.world.y;
  25963. this._cache[2] = this.rotation;
  25964. if (!this.exists || !this.parent.exists)
  25965. {
  25966. this._cache[3] = -1;
  25967. return false;
  25968. }
  25969. if (this.autoCull)
  25970. {
  25971. // Won't get rendered but will still get its transform updated
  25972. this.renderable = this.game.world.camera.screenView.intersects(this.getBounds());
  25973. }
  25974. this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty);
  25975. if (this.visible)
  25976. {
  25977. this._cache[3] = this.game.stage.currentRenderOrderID++;
  25978. }
  25979. // Update any Children
  25980. for (var i = 0, len = this.children.length; i < len; i++)
  25981. {
  25982. this.children[i].preUpdate();
  25983. }
  25984. return true;
  25985. };
  25986. /**
  25987. * Override and use this function in your own custom objects to handle any update requirements you may have.
  25988. *
  25989. * @method Phaser.Image#update
  25990. * @memberof Phaser.Image
  25991. */
  25992. Phaser.Image.prototype.update = function() {
  25993. };
  25994. /**
  25995. * Internal function called by the World postUpdate cycle.
  25996. *
  25997. * @method Phaser.Image#postUpdate
  25998. * @memberof Phaser.Image
  25999. */
  26000. Phaser.Image.prototype.postUpdate = function() {
  26001. if (this.key instanceof Phaser.BitmapData)
  26002. {
  26003. this.key.render();
  26004. }
  26005. // Fixed to Camera?
  26006. if (this._cache[7] === 1)
  26007. {
  26008. this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
  26009. this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
  26010. }
  26011. // Update any Children
  26012. for (var i = 0, len = this.children.length; i < len; i++)
  26013. {
  26014. this.children[i].postUpdate();
  26015. }
  26016. };
  26017. /**
  26018. * Changes the Texture the Image is using entirely. The old texture is removed and the new one is referenced or fetched from the Cache.
  26019. * This causes a WebGL texture update, so use sparingly or in low-intensity portions of your game.
  26020. *
  26021. * @method Phaser.Image#loadTexture
  26022. * @memberof Phaser.Image
  26023. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or 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.
  26024. * @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.
  26025. */
  26026. Phaser.Image.prototype.loadTexture = function (key, frame) {
  26027. frame = frame || 0;
  26028. if (key instanceof Phaser.RenderTexture)
  26029. {
  26030. this.key = key.key;
  26031. this.setTexture(key);
  26032. return;
  26033. }
  26034. else if (key instanceof Phaser.BitmapData)
  26035. {
  26036. this.key = key;
  26037. this.setTexture(key.texture);
  26038. return;
  26039. }
  26040. else if (key instanceof PIXI.Texture)
  26041. {
  26042. this.key = key;
  26043. this.setTexture(key);
  26044. return;
  26045. }
  26046. else
  26047. {
  26048. if (key === null || typeof key === 'undefined')
  26049. {
  26050. this.key = '__default';
  26051. this.setTexture(PIXI.TextureCache[this.key]);
  26052. return;
  26053. }
  26054. else if (typeof key === 'string' && !this.game.cache.checkImageKey(key))
  26055. {
  26056. this.key = '__missing';
  26057. this.setTexture(PIXI.TextureCache[this.key]);
  26058. return;
  26059. }
  26060. if (this.game.cache.isSpriteSheet(key))
  26061. {
  26062. this.key = key;
  26063. var frameData = this.game.cache.getFrameData(key);
  26064. if (typeof frame === 'string')
  26065. {
  26066. this._frame = 0;
  26067. this._frameName = frame;
  26068. this.setTexture(PIXI.TextureCache[frameData.getFrameByName(frame).uuid]);
  26069. return;
  26070. }
  26071. else
  26072. {
  26073. this._frame = frame;
  26074. this._frameName = '';
  26075. this.setTexture(PIXI.TextureCache[frameData.getFrame(frame).uuid]);
  26076. return;
  26077. }
  26078. }
  26079. else
  26080. {
  26081. this.key = key;
  26082. this.setTexture(PIXI.TextureCache[key]);
  26083. return;
  26084. }
  26085. }
  26086. };
  26087. /**
  26088. * Crop allows you to crop the texture used to display this Image.
  26089. * Cropping takes place from the top-left of the Image and can be modified in real-time by providing an updated rectangle object.
  26090. * The rectangle object given to this method can be either a Phaser.Rectangle or any object so long as it has public x, y, width and height properties.
  26091. * Please note that the rectangle object given is not duplicated by this method, but rather the Image uses a reference to the rectangle.
  26092. * Keep this in mind if assigning a rectangle in a for-loop, or when cleaning up for garbage collection.
  26093. *
  26094. * @method Phaser.Image#crop
  26095. * @memberof Phaser.Image
  26096. * @param {Phaser.Rectangle|object} rect - The Rectangle to crop the Image to. Pass null or no parameters to clear a previously set crop rectangle.
  26097. */
  26098. Phaser.Image.prototype.crop = function(rect) {
  26099. if (typeof rect === 'undefined' || rect === null)
  26100. {
  26101. // Clear any crop that may be set
  26102. if (this.texture.hasOwnProperty('sourceWidth'))
  26103. {
  26104. this.texture.setFrame(new Phaser.Rectangle(0, 0, this.texture.sourceWidth, this.texture.sourceHeight));
  26105. }
  26106. }
  26107. else
  26108. {
  26109. // Do we need to clone the PIXI.Texture object?
  26110. if (this.texture instanceof PIXI.Texture)
  26111. {
  26112. // Yup, let's rock it ...
  26113. var local = {};
  26114. Phaser.Utils.extend(true, local, this.texture);
  26115. local.sourceWidth = local.width;
  26116. local.sourceHeight = local.height;
  26117. local.frame = rect;
  26118. local.width = rect.width;
  26119. local.height = rect.height;
  26120. this.texture = local;
  26121. this.texture.updateFrame = true;
  26122. PIXI.Texture.frameUpdates.push(this.texture);
  26123. }
  26124. else
  26125. {
  26126. this.texture.setFrame(rect);
  26127. }
  26128. }
  26129. };
  26130. /**
  26131. * Brings a 'dead' Image back to life, optionally giving it the health value specified.
  26132. * A resurrected Image has its alive, exists and visible properties all set to true.
  26133. * It will dispatch the onRevived event, you can listen to Image.events.onRevived for the signal.
  26134. *
  26135. * @method Phaser.Image#revive
  26136. * @memberof Phaser.Image
  26137. * @return {Phaser.Image} This instance.
  26138. */
  26139. Phaser.Image.prototype.revive = function() {
  26140. this.alive = true;
  26141. this.exists = true;
  26142. this.visible = true;
  26143. if (this.events)
  26144. {
  26145. this.events.onRevived.dispatch(this);
  26146. }
  26147. return this;
  26148. };
  26149. /**
  26150. * Kills a Image. A killed Image has its alive, exists and visible properties all set to false.
  26151. * It will dispatch the onKilled event, you can listen to Image.events.onKilled for the signal.
  26152. * Note that killing a Image is a way for you to quickly recycle it in a Image pool, it doesn't free it up from memory.
  26153. * If you don't need this Image any more you should call Image.destroy instead.
  26154. *
  26155. * @method Phaser.Image#kill
  26156. * @memberof Phaser.Image
  26157. * @return {Phaser.Image} This instance.
  26158. */
  26159. Phaser.Image.prototype.kill = function() {
  26160. this.alive = false;
  26161. this.exists = false;
  26162. this.visible = false;
  26163. if (this.events)
  26164. {
  26165. this.events.onKilled.dispatch(this);
  26166. }
  26167. return this;
  26168. };
  26169. /**
  26170. * Destroys the Image. This removes it from its parent group, destroys the input, event and animation handlers if present
  26171. * and nulls its reference to game, freeing it up for garbage collection.
  26172. *
  26173. * @method Phaser.Image#destroy
  26174. * @memberof Phaser.Image
  26175. * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
  26176. */
  26177. Phaser.Image.prototype.destroy = function(destroyChildren) {
  26178. if (this.game === null || this.destroyPhase) { return; }
  26179. if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
  26180. this._cache[8] = 1;
  26181. if (this.parent)
  26182. {
  26183. if (this.parent instanceof Phaser.Group)
  26184. {
  26185. this.parent.remove(this);
  26186. }
  26187. else
  26188. {
  26189. this.parent.removeChild(this);
  26190. }
  26191. }
  26192. if (this.events)
  26193. {
  26194. this.events.destroy();
  26195. }
  26196. if (this.input)
  26197. {
  26198. this.input.destroy();
  26199. }
  26200. var i = this.children.length;
  26201. if (destroyChildren)
  26202. {
  26203. while (i--)
  26204. {
  26205. this.children[i].destroy(destroyChildren);
  26206. }
  26207. }
  26208. else
  26209. {
  26210. while (i--)
  26211. {
  26212. this.removeChild(this.children[i]);
  26213. }
  26214. }
  26215. this.alive = false;
  26216. this.exists = false;
  26217. this.visible = false;
  26218. this.filters = null;
  26219. this.mask = null;
  26220. this.game = null;
  26221. this._cache[8] = 0;
  26222. };
  26223. /**
  26224. * Resets the Image. This places the Image at the given x/y world coordinates and then sets alive, exists, visible and renderable all to true.
  26225. *
  26226. * @method Phaser.Image#reset
  26227. * @memberof Phaser.Image
  26228. * @param {number} x - The x coordinate (in world space) to position the Image at.
  26229. * @param {number} y - The y coordinate (in world space) to position the Image at.
  26230. * @return {Phaser.Image} This instance.
  26231. */
  26232. Phaser.Image.prototype.reset = function(x, y) {
  26233. this.world.setTo(x, y);
  26234. this.position.x = x;
  26235. this.position.y = y;
  26236. this.alive = true;
  26237. this.exists = true;
  26238. this.visible = true;
  26239. this.renderable = true;
  26240. return this;
  26241. };
  26242. /**
  26243. * Brings the Image to the top of the display list it is a child of. Images that are members of a Phaser.Group are only
  26244. * bought to the top of that Group, not the entire display list.
  26245. *
  26246. * @method Phaser.Image#bringToTop
  26247. * @memberof Phaser.Image
  26248. * @return {Phaser.Image} This instance.
  26249. */
  26250. Phaser.Image.prototype.bringToTop = function() {
  26251. if (this.parent)
  26252. {
  26253. this.parent.bringToTop(this);
  26254. }
  26255. return this;
  26256. };
  26257. /**
  26258. * Indicates the rotation of the Image, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
  26259. * Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
  26260. * If you wish to work in radians instead of degrees use the property Image.rotation instead. Working in radians is also a little faster as it doesn't have to convert the angle.
  26261. *
  26262. * @name Phaser.Image#angle
  26263. * @property {number} angle - The angle of this Image in degrees.
  26264. */
  26265. Object.defineProperty(Phaser.Image.prototype, "angle", {
  26266. get: function() {
  26267. return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation));
  26268. },
  26269. set: function(value) {
  26270. this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value));
  26271. }
  26272. });
  26273. /**
  26274. * Returns the delta x value. The difference between world.x now and in the previous step.
  26275. *
  26276. * @name Phaser.Image#deltaX
  26277. * @property {number} deltaX - The delta value. Positive if the motion was to the right, negative if to the left.
  26278. * @readonly
  26279. */
  26280. Object.defineProperty(Phaser.Image.prototype, "deltaX", {
  26281. get: function() {
  26282. return this.world.x - this._cache[0];
  26283. }
  26284. });
  26285. /**
  26286. * Returns the delta y value. The difference between world.y now and in the previous step.
  26287. *
  26288. * @name Phaser.Image#deltaY
  26289. * @property {number} deltaY - The delta value. Positive if the motion was downwards, negative if upwards.
  26290. * @readonly
  26291. */
  26292. Object.defineProperty(Phaser.Image.prototype, "deltaY", {
  26293. get: function() {
  26294. return this.world.y - this._cache[1];
  26295. }
  26296. });
  26297. /**
  26298. * Returns the delta z value. The difference between rotation now and in the previous step.
  26299. *
  26300. * @name Phaser.Image#deltaZ
  26301. * @property {number} deltaZ - The delta value.
  26302. * @readonly
  26303. */
  26304. Object.defineProperty(Phaser.Image.prototype, "deltaZ", {
  26305. get: function() {
  26306. return this.rotation - this._cache[2];
  26307. }
  26308. });
  26309. /**
  26310. * Checks if the Image bounds are within the game world, otherwise false if fully outside of it.
  26311. *
  26312. * @name Phaser.Image#inWorld
  26313. * @property {boolean} inWorld - True if the Image bounds is within the game world, even if only partially. Otherwise false if fully outside of it.
  26314. * @readonly
  26315. */
  26316. Object.defineProperty(Phaser.Image.prototype, "inWorld", {
  26317. get: function() {
  26318. return this.game.world.bounds.intersects(this.getBounds());
  26319. }
  26320. });
  26321. /**
  26322. * Checks if the Image bounds are within the game camera, otherwise false if fully outside of it.
  26323. *
  26324. * @name Phaser.Image#inCamera
  26325. * @property {boolean} inCamera - True if the Image bounds is within the game camera, even if only partially. Otherwise false if fully outside of it.
  26326. * @readonly
  26327. */
  26328. Object.defineProperty(Phaser.Image.prototype, "inCamera", {
  26329. get: function() {
  26330. return this.game.world.camera.screenView.intersects(this.getBounds());
  26331. }
  26332. });
  26333. /**
  26334. * @name Phaser.Image#frame
  26335. * @property {number} frame - Gets or sets the current frame index and updates the Texture for display.
  26336. */
  26337. Object.defineProperty(Phaser.Image.prototype, "frame", {
  26338. get: function() {
  26339. return this._frame;
  26340. },
  26341. set: function(value) {
  26342. if (value !== this.frame && this.game.cache.isSpriteSheet(this.key))
  26343. {
  26344. var frameData = this.game.cache.getFrameData(this.key);
  26345. if (frameData && value < frameData.total && frameData.getFrame(value))
  26346. {
  26347. this.setTexture(PIXI.TextureCache[frameData.getFrame(value).uuid]);
  26348. this._frame = value;
  26349. }
  26350. }
  26351. }
  26352. });
  26353. /**
  26354. * @name Phaser.Image#frameName
  26355. * @property {string} frameName - Gets or sets the current frame by name and updates the Texture for display.
  26356. */
  26357. Object.defineProperty(Phaser.Image.prototype, "frameName", {
  26358. get: function() {
  26359. return this._frameName;
  26360. },
  26361. set: function(value) {
  26362. if (value !== this.frameName && this.game.cache.isSpriteSheet(this.key))
  26363. {
  26364. var frameData = this.game.cache.getFrameData(this.key);
  26365. if (frameData && frameData.getFrameByName(value))
  26366. {
  26367. this.setTexture(PIXI.TextureCache[frameData.getFrameByName(value).uuid]);
  26368. this._frameName = value;
  26369. }
  26370. }
  26371. }
  26372. });
  26373. /**
  26374. * @name Phaser.Image#renderOrderID
  26375. * @property {number} renderOrderID - The render order ID, reset every frame.
  26376. * @readonly
  26377. */
  26378. Object.defineProperty(Phaser.Image.prototype, "renderOrderID", {
  26379. get: function() {
  26380. return this._cache[3];
  26381. }
  26382. });
  26383. /**
  26384. * By default an Image won't process any input events at all. By setting inputEnabled to true the Phaser.InputHandler is
  26385. * activated for this object and it will then start to process click/touch events and more.
  26386. *
  26387. * @name Phaser.Image#inputEnabled
  26388. * @property {boolean} inputEnabled - Set to true to allow this object to receive input events.
  26389. */
  26390. Object.defineProperty(Phaser.Image.prototype, "inputEnabled", {
  26391. get: function () {
  26392. return (this.input && this.input.enabled);
  26393. },
  26394. set: function (value) {
  26395. if (value)
  26396. {
  26397. if (this.input === null)
  26398. {
  26399. this.input = new Phaser.InputHandler(this);
  26400. this.input.start();
  26401. }
  26402. else if (this.input && !this.input.enabled)
  26403. {
  26404. this.input.start();
  26405. }
  26406. }
  26407. else
  26408. {
  26409. if (this.input && this.input.enabled)
  26410. {
  26411. this.input.stop();
  26412. }
  26413. }
  26414. }
  26415. });
  26416. /**
  26417. * An Image that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Image.cameraOffset.
  26418. * Note that the cameraOffset values are in addition to any parent in the display list.
  26419. * So if this Image was in a Group that has x: 200, then this will be added to the cameraOffset.x
  26420. *
  26421. * @name Phaser.Image#fixedToCamera
  26422. * @property {boolean} fixedToCamera - Set to true to fix this Image to the Camera at its current world coordinates.
  26423. */
  26424. Object.defineProperty(Phaser.Image.prototype, "fixedToCamera", {
  26425. get: function () {
  26426. return !!this._cache[7];
  26427. },
  26428. set: function (value) {
  26429. if (value)
  26430. {
  26431. this._cache[7] = 1;
  26432. this.cameraOffset.set(this.x, this.y);
  26433. }
  26434. else
  26435. {
  26436. this._cache[7] = 0;
  26437. }
  26438. }
  26439. });
  26440. /**
  26441. * Enable or disable texture smoothing for this Image. Only works for bitmap/image textures. Smoothing is enabled by default.
  26442. *
  26443. * @name Phaser.Image#smoothed
  26444. * @property {boolean} smoothed - Set to true to smooth the texture of this Image, or false to disable smoothing (great for pixel art)
  26445. */
  26446. Object.defineProperty(Phaser.Image.prototype, "smoothed", {
  26447. get: function () {
  26448. return !this.texture.baseTexture.scaleMode;
  26449. },
  26450. set: function (value) {
  26451. if (value)
  26452. {
  26453. if (this.texture)
  26454. {
  26455. this.texture.baseTexture.scaleMode = 0;
  26456. }
  26457. }
  26458. else
  26459. {
  26460. if (this.texture)
  26461. {
  26462. this.texture.baseTexture.scaleMode = 1;
  26463. }
  26464. }
  26465. }
  26466. });
  26467. /**
  26468. * @name Phaser.Image#destroyPhase
  26469. * @property {boolean} destroyPhase - True if this object is currently being destroyed.
  26470. */
  26471. Object.defineProperty(Phaser.Image.prototype, "destroyPhase", {
  26472. get: function () {
  26473. return !!this._cache[8];
  26474. }
  26475. });
  26476. /**
  26477. * @author Richard Davey <rich@photonstorm.com>
  26478. * @copyright 2014 Photon Storm Ltd.
  26479. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  26480. */
  26481. /**
  26482. * A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled and will automatically wrap on the edges as it does so.
  26483. * Please note that TileSprites, as with normal Sprites, have no input handler or physics bodies by default. Both need enabling.
  26484. *
  26485. * @class Phaser.TileSprite
  26486. * @constructor
  26487. * @param {Phaser.Game} game - A reference to the currently running game.
  26488. * @param {number} x - The x coordinate (in world space) to position the TileSprite at.
  26489. * @param {number} y - The y coordinate (in world space) to position the TileSprite at.
  26490. * @param {number} width - The width of the TileSprite.
  26491. * @param {number} height - The height of the TileSprite.
  26492. * @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.
  26493. * @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.
  26494. */
  26495. Phaser.TileSprite = function (game, x, y, width, height, key, frame) {
  26496. x = x || 0;
  26497. y = y || 0;
  26498. width = width || 256;
  26499. height = height || 256;
  26500. key = key || null;
  26501. frame = frame || null;
  26502. /**
  26503. * @property {Phaser.Game} game - A reference to the currently running Game.
  26504. */
  26505. this.game = game;
  26506. /**
  26507. * @property {string} name - The user defined name given to this Sprite.
  26508. * @default
  26509. */
  26510. this.name = '';
  26511. /**
  26512. * @property {number} type - The const type of this object.
  26513. * @readonly
  26514. */
  26515. this.type = Phaser.TILESPRITE;
  26516. /**
  26517. * @property {number} z - The z-depth value of this object within its Group (remember the World is a Group as well). No two objects in a Group can have the same z value.
  26518. */
  26519. this.z = 0;
  26520. /**
  26521. * @property {Phaser.Events} events - The Events you can subscribe to that are dispatched when certain things happen on this Sprite or its components.
  26522. */
  26523. this.events = new Phaser.Events(this);
  26524. /**
  26525. * @property {Phaser.AnimationManager} animations - This manages animations of the sprite. You can modify animations through it (see Phaser.AnimationManager)
  26526. */
  26527. this.animations = new Phaser.AnimationManager(this);
  26528. /**
  26529. * @property {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, BitmapData or PIXI.Texture.
  26530. */
  26531. this.key = key;
  26532. /**
  26533. * @property {number} _frame - Internal cache var.
  26534. * @private
  26535. */
  26536. this._frame = 0;
  26537. /**
  26538. * @property {string} _frameName - Internal cache var.
  26539. * @private
  26540. */
  26541. this._frameName = '';
  26542. /**
  26543. * @property {Phaser.Point} _scroll - Internal cache var.
  26544. * @private
  26545. */
  26546. this._scroll = new Phaser.Point();
  26547. PIXI.TilingSprite.call(this, PIXI.TextureCache['__default'], width, height);
  26548. this.position.set(x, y);
  26549. /**
  26550. * @property {Phaser.InputHandler|null} input - The Input Handler for this object. Needs to be enabled with image.inputEnabled = true before you can use it.
  26551. */
  26552. this.input = null;
  26553. /**
  26554. * @property {Phaser.Point} world - The world coordinates of this Sprite. This differs from the x/y coordinates which are relative to the Sprites container.
  26555. */
  26556. this.world = new Phaser.Point(x, y);
  26557. /**
  26558. * Should this Sprite be automatically culled if out of range of the camera?
  26559. * A culled sprite has its renderable property set to 'false'.
  26560. * Be advised this is quite an expensive operation, as it has to calculate the bounds of the object every frame, so only enable it if you really need it.
  26561. *
  26562. * @property {boolean} autoCull - A flag indicating if the Sprite should be automatically camera culled or not.
  26563. * @default
  26564. */
  26565. this.autoCull = false;
  26566. /**
  26567. * If true the Sprite checks if it is still within the world each frame, when it leaves the world it dispatches Sprite.events.onOutOfBounds
  26568. * and optionally kills the sprite (if Sprite.outOfBoundsKill is true). By default this is disabled because the Sprite has to calculate its
  26569. * bounds every frame to support it, and not all games need it. Enable it by setting the value to true.
  26570. * @property {boolean} checkWorldBounds
  26571. * @default
  26572. */
  26573. this.checkWorldBounds = false;
  26574. /**
  26575. * @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
  26576. */
  26577. this.cameraOffset = new Phaser.Point();
  26578. /**
  26579. * By default Sprites won't add themselves to any physics system and their physics body will be `null`.
  26580. * To enable them for physics you need to call `game.physics.enable(sprite, system)` where `sprite` is this object
  26581. * and `system` is the Physics system you want to use to manage this body. Once enabled you can access all physics related properties via `Sprite.body`.
  26582. *
  26583. * Important: Enabling a Sprite for P2 or Ninja physics will automatically set `Sprite.anchor` to 0.5 so the physics body is centered on the Sprite.
  26584. * If you need a different result then adjust or re-create the Body shape offsets manually, and/or reset the anchor after enabling physics.
  26585. *
  26586. * @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body
  26587. * @default
  26588. */
  26589. this.body = null;
  26590. /**
  26591. * A small internal cache:
  26592. * 0 = previous position.x
  26593. * 1 = previous position.y
  26594. * 2 = previous rotation
  26595. * 3 = renderID
  26596. * 4 = fresh? (0 = no, 1 = yes)
  26597. * 5 = outOfBoundsFired (0 = no, 1 = yes)
  26598. * 6 = exists (0 = no, 1 = yes)
  26599. * 7 = fixed to camera (0 = no, 1 = yes)
  26600. * 8 = destroy phase? (0 = no, 1 = yes)
  26601. * @property {Array} _cache
  26602. * @private
  26603. */
  26604. this._cache = [ 0, 0, 0, 0, 1, 0, 1, 0, 0 ];
  26605. this.loadTexture(key, frame);
  26606. };
  26607. Phaser.TileSprite.prototype = Object.create(PIXI.TilingSprite.prototype);
  26608. Phaser.TileSprite.prototype.constructor = Phaser.TileSprite;
  26609. /**
  26610. * Automatically called by World.preUpdate.
  26611. *
  26612. * @method Phaser.TileSprite#preUpdate
  26613. * @memberof Phaser.TileSprite
  26614. */
  26615. Phaser.TileSprite.prototype.preUpdate = function() {
  26616. if (this._cache[4] === 1 && this.exists)
  26617. {
  26618. this.world.setTo(this.parent.position.x + this.position.x, this.parent.position.y + this.position.y);
  26619. this.worldTransform.tx = this.world.x;
  26620. this.worldTransform.ty = this.world.y;
  26621. this._cache[0] = this.world.x;
  26622. this._cache[1] = this.world.y;
  26623. this._cache[2] = this.rotation;
  26624. if (this.body)
  26625. {
  26626. this.body.preUpdate();
  26627. }
  26628. this._cache[4] = 0;
  26629. return false;
  26630. }
  26631. this._cache[0] = this.world.x;
  26632. this._cache[1] = this.world.y;
  26633. this._cache[2] = this.rotation;
  26634. if (!this.exists || !this.parent.exists)
  26635. {
  26636. // Reset the renderOrderID
  26637. this._cache[3] = -1;
  26638. return false;
  26639. }
  26640. // Cache the bounds if we need it
  26641. if (this.autoCull || this.checkWorldBounds)
  26642. {
  26643. this._bounds.copyFrom(this.getBounds());
  26644. }
  26645. if (this.autoCull)
  26646. {
  26647. // Won't get rendered but will still get its transform updated
  26648. this.renderable = this.game.world.camera.screenView.intersects(this._bounds);
  26649. }
  26650. if (this.checkWorldBounds)
  26651. {
  26652. // The Sprite is already out of the world bounds, so let's check to see if it has come back again
  26653. if (this._cache[5] === 1 && this.game.world.bounds.intersects(this._bounds))
  26654. {
  26655. this._cache[5] = 0;
  26656. this.events.onEnterBounds.dispatch(this);
  26657. }
  26658. else if (this._cache[5] === 0 && !this.game.world.bounds.intersects(this._bounds))
  26659. {
  26660. // The Sprite WAS in the screen, but has now left.
  26661. this._cache[5] = 1;
  26662. this.events.onOutOfBounds.dispatch(this);
  26663. }
  26664. }
  26665. this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty);
  26666. if (this.visible)
  26667. {
  26668. this._cache[3] = this.game.stage.currentRenderOrderID++;
  26669. }
  26670. this.animations.update();
  26671. if (this._scroll.x !== 0)
  26672. {
  26673. this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed;
  26674. }
  26675. if (this._scroll.y !== 0)
  26676. {
  26677. this.tilePosition.y += this._scroll.y * this.game.time.physicsElapsed;
  26678. }
  26679. if (this.body)
  26680. {
  26681. this.body.preUpdate();
  26682. }
  26683. // Update any Children
  26684. for (var i = 0, len = this.children.length; i < len; i++)
  26685. {
  26686. this.children[i].preUpdate();
  26687. }
  26688. return true;
  26689. };
  26690. /**
  26691. * Override and use this function in your own custom objects to handle any update requirements you may have.
  26692. *
  26693. * @method Phaser.TileSprite#update
  26694. * @memberof Phaser.TileSprite
  26695. */
  26696. Phaser.TileSprite.prototype.update = function() {
  26697. };
  26698. /**
  26699. * Internal function called by the World postUpdate cycle.
  26700. *
  26701. * @method Phaser.TileSprite#postUpdate
  26702. * @memberof Phaser.TileSprite
  26703. */
  26704. Phaser.TileSprite.prototype.postUpdate = function() {
  26705. if (this.exists && this.body)
  26706. {
  26707. this.body.postUpdate();
  26708. }
  26709. // Fixed to Camera?
  26710. if (this._cache[7] === 1)
  26711. {
  26712. this.position.x = this.game.camera.view.x + this.cameraOffset.x;
  26713. this.position.y = this.game.camera.view.y + this.cameraOffset.y;
  26714. }
  26715. // Update any Children
  26716. for (var i = 0, len = this.children.length; i < len; i++)
  26717. {
  26718. this.children[i].postUpdate();
  26719. }
  26720. };
  26721. /**
  26722. * Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll().
  26723. * The scroll speed is specified in pixels per second.
  26724. * A negative x value will scroll to the left. A positive x value will scroll to the right.
  26725. * A negative y value will scroll up. A positive y value will scroll down.
  26726. *
  26727. * @method Phaser.TileSprite#autoScroll
  26728. * @memberof Phaser.TileSprite
  26729. */
  26730. Phaser.TileSprite.prototype.autoScroll = function(x, y) {
  26731. this._scroll.set(x, y);
  26732. };
  26733. /**
  26734. * Stops an automatically scrolling TileSprite.
  26735. *
  26736. * @method Phaser.TileSprite#stopScroll
  26737. * @memberof Phaser.TileSprite
  26738. */
  26739. Phaser.TileSprite.prototype.stopScroll = function() {
  26740. this._scroll.set(0, 0);
  26741. };
  26742. /**
  26743. * Changes the Texture the TileSprite is using entirely. The old texture is removed and the new one is referenced or fetched from the Cache.
  26744. * This causes a WebGL texture update, so use sparingly or in low-intensity portions of your game.
  26745. *
  26746. * @method Phaser.TileSprite#loadTexture
  26747. * @memberof Phaser.TileSprite
  26748. * @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, BitmapData or PIXI.Texture.
  26749. * @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.
  26750. */
  26751. Phaser.TileSprite.prototype.loadTexture = function (key, frame) {
  26752. frame = frame || 0;
  26753. this.key = key;
  26754. if (key instanceof Phaser.RenderTexture)
  26755. {
  26756. this.key = key.key;
  26757. this.setTexture(key);
  26758. }
  26759. else if (key instanceof Phaser.BitmapData)
  26760. {
  26761. this.setTexture(key.texture);
  26762. }
  26763. else if (key instanceof PIXI.Texture)
  26764. {
  26765. this.setTexture(key);
  26766. }
  26767. else
  26768. {
  26769. if (key === null || typeof key === 'undefined')
  26770. {
  26771. this.key = '__default';
  26772. this.setTexture(PIXI.TextureCache[this.key]);
  26773. }
  26774. else if (typeof key === 'string' && !this.game.cache.checkImageKey(key))
  26775. {
  26776. console.warn("Texture with key '" + key + "' not found.");
  26777. this.key = '__missing';
  26778. this.setTexture(PIXI.TextureCache[this.key]);
  26779. }
  26780. else
  26781. {
  26782. this.setTexture(new PIXI.Texture(PIXI.BaseTextureCache[key]));
  26783. this.animations.loadFrameData(this.game.cache.getFrameData(key), frame);
  26784. }
  26785. }
  26786. };
  26787. /**
  26788. * Sets the Texture frame the TileSprite uses for rendering.
  26789. * This is primarily an internal method used by TileSprite.loadTexture, although you may call it directly.
  26790. *
  26791. * @method Phaser.TileSprite#setFrame
  26792. * @memberof Phaser.TileSprite
  26793. * @param {Phaser.Frame} frame - The Frame to be used by the TileSprite texture.
  26794. */
  26795. Phaser.TileSprite.prototype.setFrame = function(frame) {
  26796. this.texture.frame.x = frame.x;
  26797. this.texture.frame.y = frame.y;
  26798. this.texture.frame.width = frame.width;
  26799. this.texture.frame.height = frame.height;
  26800. this.texture.crop.x = frame.x;
  26801. this.texture.crop.y = frame.y;
  26802. this.texture.crop.width = frame.width;
  26803. this.texture.crop.height = frame.height;
  26804. if (frame.trimmed)
  26805. {
  26806. if (this.texture.trim)
  26807. {
  26808. this.texture.trim.x = frame.spriteSourceSizeX;
  26809. this.texture.trim.y = frame.spriteSourceSizeY;
  26810. this.texture.trim.width = frame.sourceSizeW;
  26811. this.texture.trim.height = frame.sourceSizeH;
  26812. }
  26813. else
  26814. {
  26815. this.texture.trim = { x: frame.spriteSourceSizeX, y: frame.spriteSourceSizeY, width: frame.sourceSizeW, height: frame.sourceSizeH };
  26816. }
  26817. this.texture.width = frame.sourceSizeW;
  26818. this.texture.height = frame.sourceSizeH;
  26819. this.texture.frame.width = frame.sourceSizeW;
  26820. this.texture.frame.height = frame.sourceSizeH;
  26821. }
  26822. if (this.game.renderType === Phaser.WEBGL)
  26823. {
  26824. PIXI.WebGLRenderer.updateTextureFrame(this.texture);
  26825. }
  26826. };
  26827. /**
  26828. * Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present
  26829. * and nulls its reference to game, freeing it up for garbage collection.
  26830. *
  26831. * @method Phaser.TileSprite#destroy
  26832. * @memberof Phaser.TileSprite
  26833. * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
  26834. */
  26835. Phaser.TileSprite.prototype.destroy = function(destroyChildren) {
  26836. if (this.game === null || this.destroyPhase) { return; }
  26837. if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
  26838. this._cache[8] = 1;
  26839. if (this.filters)
  26840. {
  26841. this.filters = null;
  26842. }
  26843. if (this.parent)
  26844. {
  26845. if (this.parent instanceof Phaser.Group)
  26846. {
  26847. this.parent.remove(this);
  26848. }
  26849. else
  26850. {
  26851. this.parent.removeChild(this);
  26852. }
  26853. }
  26854. this.animations.destroy();
  26855. this.events.destroy();
  26856. var i = this.children.length;
  26857. if (destroyChildren)
  26858. {
  26859. while (i--)
  26860. {
  26861. this.children[i].destroy(destroyChildren);
  26862. }
  26863. }
  26864. else
  26865. {
  26866. while (i--)
  26867. {
  26868. this.removeChild(this.children[i]);
  26869. }
  26870. }
  26871. this.exists = false;
  26872. this.visible = false;
  26873. this.filters = null;
  26874. this.mask = null;
  26875. this.game = null;
  26876. this._cache[8] = 0;
  26877. };
  26878. /**
  26879. * Play an animation based on the given key. The animation should previously have been added via sprite.animations.add()
  26880. * If the requested animation is already playing this request will be ignored. If you need to reset an already running animation do so directly on the Animation object itself.
  26881. *
  26882. * @method Phaser.TileSprite#play
  26883. * @memberof Phaser.TileSprite
  26884. * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump".
  26885. * @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.
  26886. * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
  26887. * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
  26888. * @return {Phaser.Animation} A reference to playing Animation instance.
  26889. */
  26890. Phaser.TileSprite.prototype.play = function (name, frameRate, loop, killOnComplete) {
  26891. return this.animations.play(name, frameRate, loop, killOnComplete);
  26892. };
  26893. /**
  26894. * Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then
  26895. * sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state.
  26896. * If the TileSprite has a physics body that too is reset.
  26897. *
  26898. * @method Phaser.TileSprite#reset
  26899. * @memberof Phaser.TileSprite
  26900. * @param {number} x - The x coordinate (in world space) to position the Sprite at.
  26901. * @param {number} y - The y coordinate (in world space) to position the Sprite at.
  26902. * @return (Phaser.TileSprite) This instance.
  26903. */
  26904. Phaser.TileSprite.prototype.reset = function(x, y) {
  26905. this.world.setTo(x, y);
  26906. this.position.x = x;
  26907. this.position.y = y;
  26908. this.alive = true;
  26909. this.exists = true;
  26910. this.visible = true;
  26911. this.renderable = true;
  26912. this._outOfBoundsFired = false;
  26913. this.tilePosition.x = 0;
  26914. this.tilePosition.y = 0;
  26915. if (this.body)
  26916. {
  26917. this.body.reset(x, y, false, false);
  26918. }
  26919. this._cache[4] = 1;
  26920. return this;
  26921. };
  26922. /**
  26923. * Indicates the rotation of the Sprite, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
  26924. * Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
  26925. * If you wish to work in radians instead of degrees use the property Sprite.rotation instead. Working in radians is also a little faster as it doesn't have to convert the angle.
  26926. *
  26927. * @name Phaser.TileSprite#angle
  26928. * @property {number} angle - The angle of this Sprite in degrees.
  26929. */
  26930. Object.defineProperty(Phaser.TileSprite.prototype, "angle", {
  26931. get: function() {
  26932. return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation));
  26933. },
  26934. set: function(value) {
  26935. this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value));
  26936. }
  26937. });
  26938. /**
  26939. * @name Phaser.TileSprite#frame
  26940. * @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
  26941. */
  26942. Object.defineProperty(Phaser.TileSprite.prototype, "frame", {
  26943. get: function () {
  26944. return this.animations.frame;
  26945. },
  26946. set: function (value) {
  26947. if (value !== this.animations.frame)
  26948. {
  26949. this.animations.frame = value;
  26950. }
  26951. }
  26952. });
  26953. /**
  26954. * @name Phaser.TileSprite#frameName
  26955. * @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display.
  26956. */
  26957. Object.defineProperty(Phaser.TileSprite.prototype, "frameName", {
  26958. get: function () {
  26959. return this.animations.frameName;
  26960. },
  26961. set: function (value) {
  26962. if (value !== this.animations.frameName)
  26963. {
  26964. this.animations.frameName = value;
  26965. }
  26966. }
  26967. });
  26968. /**
  26969. * An TileSprite that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in TileSprite.cameraOffset.
  26970. * Note that the cameraOffset values are in addition to any parent in the display list.
  26971. * So if this TileSprite was in a Group that has x: 200, then this will be added to the cameraOffset.x
  26972. *
  26973. * @name Phaser.TileSprite#fixedToCamera
  26974. * @property {boolean} fixedToCamera - Set to true to fix this TileSprite to the Camera at its current world coordinates.
  26975. */
  26976. Object.defineProperty(Phaser.TileSprite.prototype, "fixedToCamera", {
  26977. get: function () {
  26978. return !!this._cache[7];
  26979. },
  26980. set: function (value) {
  26981. if (value)
  26982. {
  26983. this._cache[7] = 1;
  26984. this.cameraOffset.set(this.x, this.y);
  26985. }
  26986. else
  26987. {
  26988. this._cache[7] = 0;
  26989. }
  26990. }
  26991. });
  26992. /**
  26993. * TileSprite.exists controls if the core game loop and physics update this TileSprite or not.
  26994. * When you set TileSprite.exists to false it will remove its Body from the physics world (if it has one) and also set TileSprite.visible to false.
  26995. * Setting TileSprite.exists to true will re-add the Body to the physics world (if it has a body) and set TileSprite.visible to true.
  26996. *
  26997. * @name Phaser.TileSprite#exists
  26998. * @property {boolean} exists - If the TileSprite is processed by the core game update and physics.
  26999. */
  27000. Object.defineProperty(Phaser.TileSprite.prototype, "exists", {
  27001. get: function () {
  27002. return !!this._cache[6];
  27003. },
  27004. set: function (value) {
  27005. if (value)
  27006. {
  27007. // exists = true
  27008. this._cache[6] = 1;
  27009. if (this.body && this.body.type === Phaser.Physics.P2JS)
  27010. {
  27011. this.body.addToWorld();
  27012. }
  27013. this.visible = true;
  27014. }
  27015. else
  27016. {
  27017. // exists = false
  27018. this._cache[6] = 0;
  27019. if (this.body && this.body.type === Phaser.Physics.P2JS)
  27020. {
  27021. this.body.safeRemove = true;
  27022. }
  27023. this.visible = false;
  27024. }
  27025. }
  27026. });
  27027. /**
  27028. * By default a TileSprite won't process any input events at all. By setting inputEnabled to true the Phaser.InputHandler is
  27029. * activated for this object and it will then start to process click/touch events and more.
  27030. *
  27031. * @name Phaser.TileSprite#inputEnabled
  27032. * @property {boolean} inputEnabled - Set to true to allow this object to receive input events.
  27033. */
  27034. Object.defineProperty(Phaser.TileSprite.prototype, "inputEnabled", {
  27035. get: function () {
  27036. return (this.input && this.input.enabled);
  27037. },
  27038. set: function (value) {
  27039. if (value)
  27040. {
  27041. if (this.input === null)
  27042. {
  27043. this.input = new Phaser.InputHandler(this);
  27044. this.input.start();
  27045. }
  27046. else if (this.input && !this.input.enabled)
  27047. {
  27048. this.input.start();
  27049. }
  27050. }
  27051. else
  27052. {
  27053. if (this.input && this.input.enabled)
  27054. {
  27055. this.input.stop();
  27056. }
  27057. }
  27058. }
  27059. });
  27060. /**
  27061. * The position of the TileSprite on the x axis relative to the local coordinates of the parent.
  27062. *
  27063. * @name Phaser.TileSprite#x
  27064. * @property {number} x - The position of the TileSprite on the x axis relative to the local coordinates of the parent.
  27065. */
  27066. Object.defineProperty(Phaser.TileSprite.prototype, "x", {
  27067. get: function () {
  27068. return this.position.x;
  27069. },
  27070. set: function (value) {
  27071. this.position.x = value;
  27072. if (this.body && this.body.type === Phaser.Physics.ARCADE && this.body.phase === 2)
  27073. {
  27074. this.body._reset = 1;
  27075. }
  27076. }
  27077. });
  27078. /**
  27079. * The position of the TileSprite on the y axis relative to the local coordinates of the parent.
  27080. *
  27081. * @name Phaser.TileSprite#y
  27082. * @property {number} y - The position of the TileSprite on the y axis relative to the local coordinates of the parent.
  27083. */
  27084. Object.defineProperty(Phaser.TileSprite.prototype, "y", {
  27085. get: function () {
  27086. return this.position.y;
  27087. },
  27088. set: function (value) {
  27089. this.position.y = value;
  27090. if (this.body && this.body.type === Phaser.Physics.ARCADE && this.body.phase === 2)
  27091. {
  27092. this.body._reset = 1;
  27093. }
  27094. }
  27095. });
  27096. /**
  27097. * @name Phaser.TileSprite#destroyPhase
  27098. * @property {boolean} destroyPhase - True if this object is currently being destroyed.
  27099. */
  27100. Object.defineProperty(Phaser.TileSprite.prototype, "destroyPhase", {
  27101. get: function () {
  27102. return !!this._cache[8];
  27103. }
  27104. });
  27105. /**
  27106. * @author Richard Davey <rich@photonstorm.com>
  27107. * @copyright 2014 Photon Storm Ltd.
  27108. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  27109. */
  27110. /**
  27111. * Create a new `Text` object. This uses a local hidden Canvas object and renders the type into it. It then makes a texture from this for renderning to the view.
  27112. * Because of this you can only display fonts that are currently loaded and available to the browser. It won't load the fonts for you.
  27113. * Here is a compatibility table showing the available default fonts across different mobile browsers: http://www.jordanm.co.uk/tinytype
  27114. *
  27115. * @class Phaser.Text
  27116. * @extends PIXI.Text
  27117. * @constructor
  27118. * @param {Phaser.Game} game - Current game instance.
  27119. * @param {number} x - X position of the new text object.
  27120. * @param {number} y - Y position of the new text object.
  27121. * @param {string} text - The actual text that will be written.
  27122. * @param {object} style - The style object containing style attributes like font, font size ,
  27123. */
  27124. Phaser.Text = function (game, x, y, text, style) {
  27125. x = x || 0;
  27126. y = y || 0;
  27127. text = text || ' ';
  27128. style = style || {};
  27129. if (text.length === 0)
  27130. {
  27131. text = ' ';
  27132. }
  27133. else
  27134. {
  27135. text = text.toString();
  27136. }
  27137. /**
  27138. * @property {Phaser.Game} game - A reference to the currently running Game.
  27139. */
  27140. this.game = game;
  27141. /**
  27142. * @property {boolean} exists - If exists = false then the Text isn't updated by the core game loop.
  27143. * @default
  27144. */
  27145. this.exists = true;
  27146. /**
  27147. * @property {string} name - The user defined name given to this object.
  27148. * @default
  27149. */
  27150. this.name = '';
  27151. /**
  27152. * @property {number} type - The const type of this object.
  27153. * @default
  27154. */
  27155. this.type = Phaser.TEXT;
  27156. /**
  27157. * @property {number} z - The z-depth value of this object within its Group (remember the World is a Group as well). No two objects in a Group can have the same z value.
  27158. */
  27159. this.z = 0;
  27160. /**
  27161. * @property {Phaser.Point} world - The world coordinates of this Sprite. This differs from the x/y coordinates which are relative to the Sprites container.
  27162. */
  27163. this.world = new Phaser.Point(x, y);
  27164. /**
  27165. * @property {string} _text - Internal cache var.
  27166. * @private
  27167. */
  27168. this._text = text;
  27169. /**
  27170. * @property {string} _font - Internal cache var.
  27171. * @private
  27172. */
  27173. this._font = '';
  27174. /**
  27175. * @property {number} _fontSize - Internal cache var.
  27176. * @private
  27177. */
  27178. this._fontSize = 32;
  27179. /**
  27180. * @property {string} _fontWeight - Internal cache var.
  27181. * @private
  27182. */
  27183. this._fontWeight = 'normal';
  27184. /**
  27185. * @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line.
  27186. * @private
  27187. */
  27188. this._lineSpacing = 0;
  27189. /**
  27190. * @property {Phaser.Events} events - The Events you can subscribe to that are dispatched when certain things happen on this Sprite or its components.
  27191. */
  27192. this.events = new Phaser.Events(this);
  27193. /**
  27194. * @property {Phaser.InputHandler|null} input - The Input Handler for this object. Needs to be enabled with image.inputEnabled = true before you can use it.
  27195. */
  27196. this.input = null;
  27197. /**
  27198. * @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
  27199. */
  27200. this.cameraOffset = new Phaser.Point();
  27201. this.setStyle(style);
  27202. PIXI.Text.call(this, text, this.style);
  27203. this.position.set(x, y);
  27204. /**
  27205. * A small internal cache:
  27206. * 0 = previous position.x
  27207. * 1 = previous position.y
  27208. * 2 = previous rotation
  27209. * 3 = renderID
  27210. * 4 = fresh? (0 = no, 1 = yes)
  27211. * 5 = outOfBoundsFired (0 = no, 1 = yes)
  27212. * 6 = exists (0 = no, 1 = yes)
  27213. * 7 = fixed to camera (0 = no, 1 = yes)
  27214. * 8 = destroy phase? (0 = no, 1 = yes)
  27215. * @property {Array} _cache
  27216. * @private
  27217. */
  27218. this._cache = [ 0, 0, 0, 0, 1, 0, 1, 0, 0 ];
  27219. };
  27220. Phaser.Text.prototype = Object.create(PIXI.Text.prototype);
  27221. Phaser.Text.prototype.constructor = Phaser.Text;
  27222. /**
  27223. * Automatically called by World.preUpdate.
  27224. * @method Phaser.Text.prototype.preUpdate
  27225. */
  27226. Phaser.Text.prototype.preUpdate = function () {
  27227. this._cache[0] = this.world.x;
  27228. this._cache[1] = this.world.y;
  27229. this._cache[2] = this.rotation;
  27230. if (!this.exists || !this.parent.exists)
  27231. {
  27232. this.renderOrderID = -1;
  27233. return false;
  27234. }
  27235. if (this.autoCull)
  27236. {
  27237. // Won't get rendered but will still get its transform updated
  27238. this.renderable = this.game.world.camera.screenView.intersects(this.getBounds());
  27239. }
  27240. this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty);
  27241. if (this.visible)
  27242. {
  27243. this._cache[3] = this.game.stage.currentRenderOrderID++;
  27244. }
  27245. // Update any Children
  27246. for (var i = 0, len = this.children.length; i < len; i++)
  27247. {
  27248. this.children[i].preUpdate();
  27249. }
  27250. return true;
  27251. };
  27252. /**
  27253. * Override and use this function in your own custom objects to handle any update requirements you may have.
  27254. *
  27255. * @method Phaser.Text#update
  27256. * @memberof Phaser.Text
  27257. */
  27258. Phaser.Text.prototype.update = function() {
  27259. };
  27260. /**
  27261. * Automatically called by World.postUpdate.
  27262. * @method Phaser.Text.prototype.postUpdate
  27263. */
  27264. Phaser.Text.prototype.postUpdate = function () {
  27265. if (this._cache[7] === 1)
  27266. {
  27267. this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
  27268. this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
  27269. }
  27270. // Update any Children
  27271. for (var i = 0, len = this.children.length; i < len; i++)
  27272. {
  27273. this.children[i].postUpdate();
  27274. }
  27275. };
  27276. /**
  27277. * @method Phaser.Text.prototype.destroy
  27278. * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
  27279. */
  27280. Phaser.Text.prototype.destroy = function (destroyChildren) {
  27281. if (this.game === null || this.destroyPhase) { return; }
  27282. if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
  27283. this._cache[8] = 1;
  27284. if (this.parent)
  27285. {
  27286. if (this.parent instanceof Phaser.Group)
  27287. {
  27288. this.parent.remove(this);
  27289. }
  27290. else
  27291. {
  27292. this.parent.removeChild(this);
  27293. }
  27294. }
  27295. this.texture.destroy();
  27296. if (this.canvas.parentNode)
  27297. {
  27298. this.canvas.parentNode.removeChild(this.canvas);
  27299. }
  27300. else
  27301. {
  27302. this.canvas = null;
  27303. this.context = null;
  27304. }
  27305. var i = this.children.length;
  27306. if (destroyChildren)
  27307. {
  27308. while (i--)
  27309. {
  27310. this.children[i].destroy(destroyChildren);
  27311. }
  27312. }
  27313. else
  27314. {
  27315. while (i--)
  27316. {
  27317. this.removeChild(this.children[i]);
  27318. }
  27319. }
  27320. this.exists = false;
  27321. this.visible = false;
  27322. this.filters = null;
  27323. this.mask = null;
  27324. this.game = null;
  27325. this._cache[8] = 0;
  27326. };
  27327. /**
  27328. * @method Phaser.Text.prototype.setShadow
  27329. * @param {number} [x=0] - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be.
  27330. * @param {number} [y=0] - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be.
  27331. * @param {string} [color='rgba(0,0,0,0)'] - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow.
  27332. * @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).
  27333. */
  27334. Phaser.Text.prototype.setShadow = function (x, y, color, blur) {
  27335. this.style.shadowOffsetX = x || 0;
  27336. this.style.shadowOffsetY = y || 0;
  27337. this.style.shadowColor = color || 'rgba(0,0,0,0)';
  27338. this.style.shadowBlur = blur || 0;
  27339. this.dirty = true;
  27340. };
  27341. /**
  27342. * Set the style of the text by passing a single style object to it.
  27343. *
  27344. * @method Phaser.Text.prototype.setStyle
  27345. * @param [style] {Object} The style parameters
  27346. * @param [style.font='bold 20pt Arial'] {String} The style and size of the font
  27347. * @param [style.fill='black'] {Object} A canvas fillstyle that will be used on the text eg 'red', '#00FF00'
  27348. * @param [style.align='left'] {String} Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text
  27349. * @param [style.stroke='black'] {String} A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'
  27350. * @param [style.strokeThickness=0] {Number} A number that represents the thickness of the stroke. Default is 0 (no stroke)
  27351. * @param [style.wordWrap=false] {Boolean} Indicates if word wrap should be used
  27352. * @param [style.wordWrapWidth=100] {Number} The width at which text will wrap
  27353. */
  27354. Phaser.Text.prototype.setStyle = function (style) {
  27355. style = style || {};
  27356. style.font = style.font || 'bold 20pt Arial';
  27357. style.fill = style.fill || 'black';
  27358. style.align = style.align || 'left';
  27359. style.stroke = style.stroke || 'black'; //provide a default, see: https://github.com/GoodBoyDigital/pixi.js/issues/136
  27360. style.strokeThickness = style.strokeThickness || 0;
  27361. style.wordWrap = style.wordWrap || false;
  27362. style.wordWrapWidth = style.wordWrapWidth || 100;
  27363. style.shadowOffsetX = style.shadowOffsetX || 0;
  27364. style.shadowOffsetY = style.shadowOffsetY || 0;
  27365. style.shadowColor = style.shadowColor || 'rgba(0,0,0,0)';
  27366. style.shadowBlur = style.shadowBlur || 0;
  27367. this.style = style;
  27368. this.dirty = true;
  27369. };
  27370. /**
  27371. * Renders text. This replaces the Pixi.Text.updateText function as we need a few extra bits in here.
  27372. *
  27373. * @method Phaser.Text.prototype.updateText
  27374. * @private
  27375. */
  27376. Phaser.Text.prototype.updateText = function () {
  27377. this.context.font = this.style.font;
  27378. var outputText = this.text;
  27379. // word wrap
  27380. // preserve original text
  27381. if (this.style.wordWrap)
  27382. {
  27383. outputText = this.runWordWrap(this.text);
  27384. }
  27385. //split text into lines
  27386. var lines = outputText.split(/(?:\r\n|\r|\n)/);
  27387. //calculate text width
  27388. var lineWidths = [];
  27389. var maxLineWidth = 0;
  27390. for (var i = 0; i < lines.length; i++)
  27391. {
  27392. var lineWidth = this.context.measureText(lines[i]).width;
  27393. lineWidths[i] = lineWidth;
  27394. maxLineWidth = Math.max(maxLineWidth, lineWidth);
  27395. }
  27396. this.canvas.width = maxLineWidth + this.style.strokeThickness;
  27397. //calculate text height
  27398. var lineHeight = this.determineFontHeight('font: ' + this.style.font + ';') + this.style.strokeThickness + this._lineSpacing + this.style.shadowOffsetY;
  27399. this.canvas.height = lineHeight * lines.length;
  27400. if (navigator.isCocoonJS)
  27401. {
  27402. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  27403. }
  27404. //set canvas text styles
  27405. this.context.fillStyle = this.style.fill;
  27406. this.context.font = this.style.font;
  27407. this.context.strokeStyle = this.style.stroke;
  27408. this.context.lineWidth = this.style.strokeThickness;
  27409. this.context.shadowOffsetX = this.style.shadowOffsetX;
  27410. this.context.shadowOffsetY = this.style.shadowOffsetY;
  27411. this.context.shadowColor = this.style.shadowColor;
  27412. this.context.shadowBlur = this.style.shadowBlur;
  27413. this.context.textBaseline = 'top';
  27414. this.context.lineCap = 'round';
  27415. this.context.lineJoin = 'round';
  27416. //draw lines line by line
  27417. for (i = 0; i < lines.length; i++)
  27418. {
  27419. var linePosition = new PIXI.Point(this.style.strokeThickness / 2, this.style.strokeThickness / 2 + i * lineHeight);
  27420. if (this.style.align === 'right')
  27421. {
  27422. linePosition.x += maxLineWidth - lineWidths[i];
  27423. }
  27424. else if (this.style.align === 'center')
  27425. {
  27426. linePosition.x += (maxLineWidth - lineWidths[i]) / 2;
  27427. }
  27428. linePosition.y += this._lineSpacing;
  27429. if (this.style.stroke && this.style.strokeThickness)
  27430. {
  27431. this.context.strokeText(lines[i], linePosition.x, linePosition.y);
  27432. }
  27433. if (this.style.fill)
  27434. {
  27435. this.context.fillText(lines[i], linePosition.x, linePosition.y);
  27436. }
  27437. }
  27438. this.updateTexture();
  27439. };
  27440. /**
  27441. * Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds.
  27442. *
  27443. * @method Phaser.Text.prototype.runWordWrap
  27444. * @private
  27445. */
  27446. Phaser.Text.prototype.runWordWrap = function (text) {
  27447. var result = '';
  27448. var lines = text.split('\n');
  27449. for (var i = 0; i < lines.length; i++)
  27450. {
  27451. var spaceLeft = this.style.wordWrapWidth;
  27452. var words = lines[i].split(' ');
  27453. for (var j = 0; j < words.length; j++)
  27454. {
  27455. var wordWidth = this.context.measureText(words[j]).width;
  27456. var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width;
  27457. if (wordWidthWithSpace > spaceLeft)
  27458. {
  27459. // Skip printing the newline if it's the first word of the line that is greater than the word wrap width.
  27460. if (j > 0)
  27461. {
  27462. result += '\n';
  27463. }
  27464. result += words[j] + ' ';
  27465. spaceLeft = this.style.wordWrapWidth - wordWidth;
  27466. }
  27467. else
  27468. {
  27469. spaceLeft -= wordWidthWithSpace;
  27470. result += words[j] + ' ';
  27471. }
  27472. }
  27473. if (i < lines.length-1)
  27474. {
  27475. result += '\n';
  27476. }
  27477. }
  27478. return result;
  27479. };
  27480. /**
  27481. * Indicates the rotation of the Text, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
  27482. * Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
  27483. * If you wish to work in radians instead of degrees use the property Sprite.rotation instead.
  27484. * @name Phaser.Text#angle
  27485. * @property {number} angle - Gets or sets the angle of rotation in degrees.
  27486. */
  27487. Object.defineProperty(Phaser.Text.prototype, 'angle', {
  27488. get: function() {
  27489. return Phaser.Math.radToDeg(this.rotation);
  27490. },
  27491. set: function(value) {
  27492. this.rotation = Phaser.Math.degToRad(value);
  27493. }
  27494. });
  27495. /**
  27496. * The text string to be displayed by this Text object, taking into account the style settings.
  27497. * @name Phaser.Text#text
  27498. * @property {string} text - The text string to be displayed by this Text object, taking into account the style settings.
  27499. */
  27500. Object.defineProperty(Phaser.Text.prototype, 'text', {
  27501. get: function() {
  27502. return this._text;
  27503. },
  27504. set: function(value) {
  27505. if (value !== this._text)
  27506. {
  27507. this._text = value.toString() || ' ';
  27508. this.dirty = true;
  27509. this.updateTransform();
  27510. }
  27511. }
  27512. });
  27513. /**
  27514. * @name Phaser.Text#font
  27515. * @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use.
  27516. */
  27517. Object.defineProperty(Phaser.Text.prototype, 'font', {
  27518. get: function() {
  27519. return this._font;
  27520. },
  27521. set: function(value) {
  27522. if (value !== this._font)
  27523. {
  27524. this._font = value.trim();
  27525. this.style.font = this._fontWeight + ' ' + this._fontSize + "px '" + this._font + "'";
  27526. this.dirty = true;
  27527. this.updateTransform();
  27528. }
  27529. }
  27530. });
  27531. /**
  27532. * @name Phaser.Text#fontSize
  27533. * @property {number} fontSize - The size of the font in pixels.
  27534. */
  27535. Object.defineProperty(Phaser.Text.prototype, 'fontSize', {
  27536. get: function() {
  27537. return this._fontSize;
  27538. },
  27539. set: function(value) {
  27540. value = parseInt(value, 10);
  27541. if (value !== this._fontSize)
  27542. {
  27543. this._fontSize = value;
  27544. this.style.font = this._fontWeight + ' ' + this._fontSize + "px '" + this._font + "'";
  27545. this.dirty = true;
  27546. this.updateTransform();
  27547. }
  27548. }
  27549. });
  27550. /**
  27551. * @name Phaser.Text#fontWeight
  27552. * @property {number} fontWeight - The weight of the font: 'normal', 'bold', 'italic'. You can combine settings too, such as 'bold italic'.
  27553. */
  27554. Object.defineProperty(Phaser.Text.prototype, 'fontWeight', {
  27555. get: function() {
  27556. return this._fontWeight;
  27557. },
  27558. set: function(value) {
  27559. if (value !== this._fontWeight)
  27560. {
  27561. this._fontWeight = value;
  27562. this.style.font = this._fontWeight + ' ' + this._fontSize + "px '" + this._font + "'";
  27563. this.dirty = true;
  27564. this.updateTransform();
  27565. }
  27566. }
  27567. });
  27568. /**
  27569. * @name Phaser.Text#fill
  27570. * @property {object} fill - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'.
  27571. */
  27572. Object.defineProperty(Phaser.Text.prototype, 'fill', {
  27573. get: function() {
  27574. return this.style.fill;
  27575. },
  27576. set: function(value) {
  27577. if (value !== this.style.fill)
  27578. {
  27579. this.style.fill = value;
  27580. this.dirty = true;
  27581. }
  27582. }
  27583. });
  27584. /**
  27585. * @name Phaser.Text#align
  27586. * @property {string} align - Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text.
  27587. */
  27588. Object.defineProperty(Phaser.Text.prototype, 'align', {
  27589. get: function() {
  27590. return this.style.align;
  27591. },
  27592. set: function(value) {
  27593. if (value !== this.style.align)
  27594. {
  27595. this.style.align = value;
  27596. this.dirty = true;
  27597. }
  27598. }
  27599. });
  27600. /**
  27601. * @name Phaser.Text#stroke
  27602. * @property {string} stroke - A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'.
  27603. */
  27604. Object.defineProperty(Phaser.Text.prototype, 'stroke', {
  27605. get: function() {
  27606. return this.style.stroke;
  27607. },
  27608. set: function(value) {
  27609. if (value !== this.style.stroke)
  27610. {
  27611. this.style.stroke = value;
  27612. this.dirty = true;
  27613. }
  27614. }
  27615. });
  27616. /**
  27617. * @name Phaser.Text#strokeThickness
  27618. * @property {number} strokeThickness - A number that represents the thickness of the stroke. Default is 0 (no stroke)
  27619. */
  27620. Object.defineProperty(Phaser.Text.prototype, 'strokeThickness', {
  27621. get: function() {
  27622. return this.style.strokeThickness;
  27623. },
  27624. set: function(value) {
  27625. if (value !== this.style.strokeThickness)
  27626. {
  27627. this.style.strokeThickness = value;
  27628. this.dirty = true;
  27629. }
  27630. }
  27631. });
  27632. /**
  27633. * @name Phaser.Text#wordWrap
  27634. * @property {boolean} wordWrap - Indicates if word wrap should be used.
  27635. */
  27636. Object.defineProperty(Phaser.Text.prototype, 'wordWrap', {
  27637. get: function() {
  27638. return this.style.wordWrap;
  27639. },
  27640. set: function(value) {
  27641. if (value !== this.style.wordWrap)
  27642. {
  27643. this.style.wordWrap = value;
  27644. this.dirty = true;
  27645. }
  27646. }
  27647. });
  27648. /**
  27649. * @name Phaser.Text#wordWrapWidth
  27650. * @property {number} wordWrapWidth - The width at which text will wrap.
  27651. */
  27652. Object.defineProperty(Phaser.Text.prototype, 'wordWrapWidth', {
  27653. get: function() {
  27654. return this.style.wordWrapWidth;
  27655. },
  27656. set: function(value) {
  27657. if (value !== this.style.wordWrapWidth)
  27658. {
  27659. this.style.wordWrapWidth = value;
  27660. this.dirty = true;
  27661. }
  27662. }
  27663. });
  27664. /**
  27665. * @name Phaser.Text#lineSpacing
  27666. * @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line.
  27667. */
  27668. Object.defineProperty(Phaser.Text.prototype, 'lineSpacing', {
  27669. get: function() {
  27670. return this._lineSpacing;
  27671. },
  27672. set: function(value) {
  27673. if (value !== this._lineSpacing)
  27674. {
  27675. this._lineSpacing = parseFloat(value);
  27676. this.dirty = true;
  27677. this.updateTransform();
  27678. }
  27679. }
  27680. });
  27681. /**
  27682. * @name Phaser.Text#shadowOffsetX
  27683. * @property {number} shadowOffsetX - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be.
  27684. */
  27685. Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetX', {
  27686. get: function() {
  27687. return this.style.shadowOffsetX;
  27688. },
  27689. set: function(value) {
  27690. if (value !== this.style.shadowOffsetX)
  27691. {
  27692. this.style.shadowOffsetX = value;
  27693. this.dirty = true;
  27694. }
  27695. }
  27696. });
  27697. /**
  27698. * @name Phaser.Text#shadowOffsetY
  27699. * @property {number} shadowOffsetY - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be.
  27700. */
  27701. Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetY', {
  27702. get: function() {
  27703. return this.style.shadowOffsetY;
  27704. },
  27705. set: function(value) {
  27706. if (value !== this.style.shadowOffsetY)
  27707. {
  27708. this.style.shadowOffsetY = value;
  27709. this.dirty = true;
  27710. }
  27711. }
  27712. });
  27713. /**
  27714. * @name Phaser.Text#shadowColor
  27715. * @property {string} shadowColor - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow.
  27716. */
  27717. Object.defineProperty(Phaser.Text.prototype, 'shadowColor', {
  27718. get: function() {
  27719. return this.style.shadowColor;
  27720. },
  27721. set: function(value) {
  27722. if (value !== this.style.shadowColor)
  27723. {
  27724. this.style.shadowColor = value;
  27725. this.dirty = true;
  27726. }
  27727. }
  27728. });
  27729. /**
  27730. * @name Phaser.Text#shadowBlur
  27731. * @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).
  27732. */
  27733. Object.defineProperty(Phaser.Text.prototype, 'shadowBlur', {
  27734. get: function() {
  27735. return this.style.shadowBlur;
  27736. },
  27737. set: function(value) {
  27738. if (value !== this.style.shadowBlur)
  27739. {
  27740. this.style.shadowBlur = value;
  27741. this.dirty = true;
  27742. }
  27743. }
  27744. });
  27745. /**
  27746. * By default a Text object won't process any input events at all. By setting inputEnabled to true the Phaser.InputHandler is
  27747. * activated for this object and it will then start to process click/touch events and more.
  27748. *
  27749. * @name Phaser.Text#inputEnabled
  27750. * @property {boolean} inputEnabled - Set to true to allow this object to receive input events.
  27751. */
  27752. Object.defineProperty(Phaser.Text.prototype, "inputEnabled", {
  27753. get: function () {
  27754. return (this.input && this.input.enabled);
  27755. },
  27756. set: function (value) {
  27757. if (value)
  27758. {
  27759. if (this.input === null)
  27760. {
  27761. this.input = new Phaser.InputHandler(this);
  27762. this.input.start();
  27763. }
  27764. else if (this.input && !this.input.enabled)
  27765. {
  27766. this.input.start();
  27767. }
  27768. }
  27769. else
  27770. {
  27771. if (this.input && this.input.enabled)
  27772. {
  27773. this.input.stop();
  27774. }
  27775. }
  27776. }
  27777. });
  27778. /**
  27779. * An Text that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Text.cameraOffset.
  27780. * Note that the cameraOffset values are in addition to any parent in the display list.
  27781. * So if this Text was in a Group that has x: 200, then this will be added to the cameraOffset.x
  27782. *
  27783. * @name Phaser.Text#fixedToCamera
  27784. * @property {boolean} fixedToCamera - Set to true to fix this Text to the Camera at its current world coordinates.
  27785. */
  27786. Object.defineProperty(Phaser.Text.prototype, "fixedToCamera", {
  27787. get: function () {
  27788. return !!this._cache[7];
  27789. },
  27790. set: function (value) {
  27791. if (value)
  27792. {
  27793. this._cache[7] = 1;
  27794. this.cameraOffset.set(this.x, this.y);
  27795. }
  27796. else
  27797. {
  27798. this._cache[7] = 0;
  27799. }
  27800. }
  27801. });
  27802. /**
  27803. * @name Phaser.Text#destroyPhase
  27804. * @property {boolean} destroyPhase - True if this object is currently being destroyed.
  27805. */
  27806. Object.defineProperty(Phaser.Text.prototype, "destroyPhase", {
  27807. get: function () {
  27808. return !!this._cache[8];
  27809. }
  27810. });
  27811. /**
  27812. * @author Richard Davey <rich@photonstorm.com>
  27813. * @copyright 2014 Photon Storm Ltd.
  27814. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  27815. */
  27816. /**
  27817. * Creates a new BitmapText object.
  27818. *
  27819. * @class Phaser.BitmapText
  27820. *
  27821. * @classdesc BitmapText objects work by taking a texture file and an XML file that describes the font layout.
  27822. *
  27823. * On Windows you can use the free app BMFont: http://www.angelcode.com/products/bmfont/
  27824. * On OS X we recommend Glyph Designer: http://www.71squared.com/en/glyphdesigner
  27825. * For Web there is the great Littera: http://kvazars.com/littera/
  27826. *
  27827. * @constructor
  27828. * @param {Phaser.Game} game - A reference to the currently running game.
  27829. * @param {number} x - X position of the new bitmapText object.
  27830. * @param {number} y - Y position of the new bitmapText object.
  27831. * @param {string} font - The key of the BitmapFont as stored in Game.Cache.
  27832. * @param {string} [text=''] - The actual text that will be rendered. Can be set later via BitmapText.text.
  27833. * @param {number} [size=32] - The size the font will be rendered in, in pixels.
  27834. */
  27835. Phaser.BitmapText = function (game, x, y, font, text, size) {
  27836. x = x || 0;
  27837. y = y || 0;
  27838. font = font || '';
  27839. text = text || '';
  27840. size = size || 32;
  27841. /**
  27842. * @property {Phaser.Game} game - A reference to the currently running Game.
  27843. */
  27844. this.game = game;
  27845. /**
  27846. * @property {boolean} exists - If exists = false then the Sprite isn't updated by the core game loop or physics subsystem at all.
  27847. * @default
  27848. */
  27849. this.exists = true;
  27850. /**
  27851. * @property {string} name - The user defined name given to this BitmapText.
  27852. * @default
  27853. */
  27854. this.name = '';
  27855. /**
  27856. * @property {number} type - The const type of this object.
  27857. * @readonly
  27858. */
  27859. this.type = Phaser.BITMAPTEXT;
  27860. /**
  27861. * @property {number} z - The z-depth value of this object within its Group (remember the World is a Group as well). No two objects in a Group can have the same z value.
  27862. */
  27863. this.z = 0;
  27864. /**
  27865. * @property {Phaser.Point} world - The world coordinates of this Sprite. This differs from the x/y coordinates which are relative to the Sprites container.
  27866. */
  27867. this.world = new Phaser.Point(x, y);
  27868. /**
  27869. * @property {string} _text - Internal cache var.
  27870. * @private
  27871. */
  27872. this._text = text;
  27873. /**
  27874. * @property {string} _font - Internal cache var.
  27875. * @private
  27876. */
  27877. this._font = font;
  27878. /**
  27879. * @property {number} _fontSize - Internal cache var.
  27880. * @private
  27881. */
  27882. this._fontSize = size;
  27883. /**
  27884. * @property {string} _align - Internal cache var.
  27885. * @private
  27886. */
  27887. this._align = 'left';
  27888. /**
  27889. * @property {number} _tint - Internal cache var.
  27890. * @private
  27891. */
  27892. this._tint = 0xFFFFFF;
  27893. /**
  27894. * @property {Phaser.Events} events - The Events you can subscribe to that are dispatched when certain things happen on this Sprite or its components.
  27895. */
  27896. this.events = new Phaser.Events(this);
  27897. /**
  27898. * @property {Phaser.InputHandler|null} input - The Input Handler for this object. Needs to be enabled with image.inputEnabled = true before you can use it.
  27899. */
  27900. this.input = null;
  27901. /**
  27902. * @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
  27903. */
  27904. this.cameraOffset = new Phaser.Point();
  27905. PIXI.BitmapText.call(this, text);
  27906. this.position.set(x, y);
  27907. /**
  27908. * A small internal cache:
  27909. * 0 = previous position.x
  27910. * 1 = previous position.y
  27911. * 2 = previous rotation
  27912. * 3 = renderID
  27913. * 4 = fresh? (0 = no, 1 = yes)
  27914. * 5 = outOfBoundsFired (0 = no, 1 = yes)
  27915. * 6 = exists (0 = no, 1 = yes)
  27916. * 7 = fixed to camera (0 = no, 1 = yes)
  27917. * 8 = destroy phase? (0 = no, 1 = yes)
  27918. * @property {Array} _cache
  27919. * @private
  27920. */
  27921. this._cache = [0, 0, 0, 0, 1, 0, 1, 0, 0];
  27922. };
  27923. Phaser.BitmapText.prototype = Object.create(PIXI.BitmapText.prototype);
  27924. Phaser.BitmapText.prototype.constructor = Phaser.BitmapText;
  27925. /**
  27926. * @method Phaser.BitmapText.prototype.setStyle
  27927. * @private
  27928. */
  27929. Phaser.BitmapText.prototype.setStyle = function() {
  27930. this.style = { align: this._align };
  27931. this.fontName = this._font;
  27932. this.fontSize = this._fontSize;
  27933. this.dirty = true;
  27934. };
  27935. /**
  27936. * Automatically called by World.preUpdate.
  27937. * @method Phaser.BitmapText.prototype.preUpdate
  27938. */
  27939. Phaser.BitmapText.prototype.preUpdate = function () {
  27940. this._cache[0] = this.world.x;
  27941. this._cache[1] = this.world.y;
  27942. this._cache[2] = this.rotation;
  27943. if (!this.exists || !this.parent.exists)
  27944. {
  27945. this.renderOrderID = -1;
  27946. return false;
  27947. }
  27948. if (this.autoCull)
  27949. {
  27950. // Won't get rendered but will still get its transform updated
  27951. this.renderable = this.game.world.camera.screenView.intersects(this.getBounds());
  27952. }
  27953. this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty);
  27954. if (this.visible)
  27955. {
  27956. this._cache[3] = this.game.stage.currentRenderOrderID++;
  27957. }
  27958. return true;
  27959. };
  27960. /**
  27961. * Override and use this function in your own custom objects to handle any update requirements you may have.
  27962. *
  27963. * @method Phaser.BitmapText.prototype.update
  27964. */
  27965. Phaser.BitmapText.prototype.update = function() {
  27966. };
  27967. /**
  27968. * Automatically called by World.postUpdate.
  27969. * @method Phaser.BitmapText.prototype.postUpdate
  27970. */
  27971. Phaser.BitmapText.prototype.postUpdate = function () {
  27972. // Fixed to Camera?
  27973. if (this._cache[7] === 1)
  27974. {
  27975. this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
  27976. this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
  27977. }
  27978. };
  27979. /**
  27980. * Destroy this BitmapText instance. This will remove any filters and un-parent any children.
  27981. * @method Phaser.BitmapText.prototype.destroy
  27982. * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
  27983. */
  27984. Phaser.BitmapText.prototype.destroy = function(destroyChildren) {
  27985. if (this.game === null || this.destroyPhase) { return; }
  27986. if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
  27987. this._cache[8] = 1;
  27988. if (this.parent)
  27989. {
  27990. if (this.parent instanceof Phaser.Group)
  27991. {
  27992. this.parent.remove(this);
  27993. }
  27994. else
  27995. {
  27996. this.parent.removeChild(this);
  27997. }
  27998. }
  27999. var i = this.children.length;
  28000. if (destroyChildren)
  28001. {
  28002. while (i--)
  28003. {
  28004. if (this.children[i].destroy)
  28005. {
  28006. this.children[i].destroy(destroyChildren);
  28007. }
  28008. else
  28009. {
  28010. this.removeChild(this.children[i]);
  28011. }
  28012. }
  28013. }
  28014. else
  28015. {
  28016. while (i--)
  28017. {
  28018. this.removeChild(this.children[i]);
  28019. }
  28020. }
  28021. this.exists = false;
  28022. this.visible = false;
  28023. this.filters = null;
  28024. this.mask = null;
  28025. this.game = null;
  28026. this._cache[8] = 0;
  28027. };
  28028. /**
  28029. * @name Phaser.BitmapText#align
  28030. * @property {string} align - Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text.
  28031. */
  28032. Object.defineProperty(Phaser.BitmapText.prototype, 'align', {
  28033. get: function() {
  28034. return this._align;
  28035. },
  28036. set: function(value) {
  28037. if (value !== this._align)
  28038. {
  28039. this._align = value;
  28040. this.setStyle();
  28041. }
  28042. }
  28043. });
  28044. /**
  28045. * @name Phaser.BitmapText#tint
  28046. * @property {number} tint - The tint applied to the BitmapText. This is a hex value. Set to white to disable (0xFFFFFF)
  28047. */
  28048. Object.defineProperty(Phaser.BitmapText.prototype, 'tint', {
  28049. get: function() {
  28050. return this._tint;
  28051. },
  28052. set: function(value) {
  28053. if (value !== this._tint)
  28054. {
  28055. this._tint = value;
  28056. this.dirty = true;
  28057. }
  28058. }
  28059. });
  28060. /**
  28061. * Indicates the rotation of the Text, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
  28062. * Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
  28063. * If you wish to work in radians instead of degrees use the property Sprite.rotation instead.
  28064. * @name Phaser.BitmapText#angle
  28065. * @property {number} angle - Gets or sets the angle of rotation in degrees.
  28066. */
  28067. Object.defineProperty(Phaser.BitmapText.prototype, 'angle', {
  28068. get: function() {
  28069. return Phaser.Math.radToDeg(this.rotation);
  28070. },
  28071. set: function(value) {
  28072. this.rotation = Phaser.Math.degToRad(value);
  28073. }
  28074. });
  28075. /**
  28076. * @name Phaser.BitmapText#font
  28077. * @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use.
  28078. */
  28079. Object.defineProperty(Phaser.BitmapText.prototype, 'font', {
  28080. get: function() {
  28081. return this._font;
  28082. },
  28083. set: function(value) {
  28084. if (value !== this._font)
  28085. {
  28086. this._font = value.trim();
  28087. this.style.font = this._fontSize + "px '" + this._font + "'";
  28088. this.dirty = true;
  28089. }
  28090. }
  28091. });
  28092. /**
  28093. * @name Phaser.BitmapText#fontSize
  28094. * @property {number} fontSize - The size of the font in pixels.
  28095. */
  28096. Object.defineProperty(Phaser.BitmapText.prototype, 'fontSize', {
  28097. get: function() {
  28098. return this._fontSize;
  28099. },
  28100. set: function(value) {
  28101. value = parseInt(value, 10);
  28102. if (value !== this._fontSize)
  28103. {
  28104. this._fontSize = value;
  28105. this.style.font = this._fontSize + "px '" + this._font + "'";
  28106. this.dirty = true;
  28107. }
  28108. }
  28109. });
  28110. /**
  28111. * The text string to be displayed by this Text object, taking into account the style settings.
  28112. * @name Phaser.BitmapText#text
  28113. * @property {string} text - The text string to be displayed by this Text object, taking into account the style settings.
  28114. */
  28115. Object.defineProperty(Phaser.BitmapText.prototype, 'text', {
  28116. get: function() {
  28117. return this._text;
  28118. },
  28119. set: function(value) {
  28120. if (value !== this._text)
  28121. {
  28122. this._text = value.toString() || ' ';
  28123. this.dirty = true;
  28124. }
  28125. }
  28126. });
  28127. /**
  28128. * By default a Text object won't process any input events at all. By setting inputEnabled to true the Phaser.InputHandler is
  28129. * activated for this object and it will then start to process click/touch events and more.
  28130. *
  28131. * @name Phaser.BitmapText#inputEnabled
  28132. * @property {boolean} inputEnabled - Set to true to allow this object to receive input events.
  28133. */
  28134. Object.defineProperty(Phaser.BitmapText.prototype, "inputEnabled", {
  28135. get: function () {
  28136. return (this.input && this.input.enabled);
  28137. },
  28138. set: function (value) {
  28139. if (value)
  28140. {
  28141. if (this.input === null)
  28142. {
  28143. this.input = new Phaser.InputHandler(this);
  28144. this.input.start();
  28145. }
  28146. else if (this.input && !this.input.enabled)
  28147. {
  28148. this.input.start();
  28149. }
  28150. }
  28151. else
  28152. {
  28153. if (this.input && this.input.enabled)
  28154. {
  28155. this.input.stop();
  28156. }
  28157. }
  28158. }
  28159. });
  28160. /**
  28161. * An BitmapText that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in BitmapText.cameraOffset.
  28162. * Note that the cameraOffset values are in addition to any parent in the display list.
  28163. * So if this BitmapText was in a Group that has x: 200, then this will be added to the cameraOffset.x
  28164. *
  28165. * @name Phaser.BitmapText#fixedToCamera
  28166. * @property {boolean} fixedToCamera - Set to true to fix this BitmapText to the Camera at its current world coordinates.
  28167. */
  28168. Object.defineProperty(Phaser.BitmapText.prototype, "fixedToCamera", {
  28169. get: function () {
  28170. return !!this._cache[7];
  28171. },
  28172. set: function (value) {
  28173. if (value)
  28174. {
  28175. this._cache[7] = 1;
  28176. this.cameraOffset.set(this.x, this.y);
  28177. }
  28178. else
  28179. {
  28180. this._cache[7] = 0;
  28181. }
  28182. }
  28183. });
  28184. /**
  28185. * @name Phaser.BitmapText#destroyPhase
  28186. * @property {boolean} destroyPhase - True if this object is currently being destroyed.
  28187. */
  28188. Object.defineProperty(Phaser.BitmapText.prototype, "destroyPhase", {
  28189. get: function () {
  28190. return !!this._cache[8];
  28191. }
  28192. });
  28193. /**
  28194. * @author Richard Davey <rich@photonstorm.com>
  28195. * @copyright 2014 Photon Storm Ltd.
  28196. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  28197. */
  28198. /**
  28199. * @class Phaser.Button
  28200. *
  28201. * @classdesc Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically. The four states a Button responds to are:
  28202. *
  28203. * * 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'.
  28204. * * 'Out' - when the Pointer that was previously over the Button moves out of it.
  28205. * * 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse.
  28206. * * 'Up' - when the Pointer that was pressed down on the Button is released again.
  28207. *
  28208. * You can set a unique texture frame and Sound for any of these states.
  28209. *
  28210. * @constructor
  28211. * @extends Phaser.Image
  28212. *
  28213. * @param {Phaser.Game} game Current game instance.
  28214. * @param {number} [x=0] - X position of the Button.
  28215. * @param {number} [y=0] - Y position of the Button.
  28216. * @param {string} [key] - The image key as defined in the Game.Cache to use as the texture for this Button.
  28217. * @param {function} [callback] - The function to call when this Button is pressed.
  28218. * @param {object} [callbackContext] - The context in which the callback will be called (usually 'this').
  28219. * @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.
  28220. * @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.
  28221. * @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.
  28222. * @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.
  28223. */
  28224. Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) {
  28225. x = x || 0;
  28226. y = y || 0;
  28227. key = key || null;
  28228. callback = callback || null;
  28229. callbackContext = callbackContext || this;
  28230. Phaser.Image.call(this, game, x, y, key, outFrame);
  28231. /**
  28232. * @property {number} type - The Phaser Object Type.
  28233. */
  28234. this.type = Phaser.BUTTON;
  28235. /**
  28236. * @property {string} _onOverFrameName - Internal variable.
  28237. * @private
  28238. * @default
  28239. */
  28240. this._onOverFrameName = null;
  28241. /**
  28242. * @property {string} _onOutFrameName - Internal variable.
  28243. * @private
  28244. * @default
  28245. */
  28246. this._onOutFrameName = null;
  28247. /**
  28248. * @property {string} _onDownFrameName - Internal variable.
  28249. * @private
  28250. * @default
  28251. */
  28252. this._onDownFrameName = null;
  28253. /**
  28254. * @property {string} _onUpFrameName - Internal variable.
  28255. * @private
  28256. * @default
  28257. */
  28258. this._onUpFrameName = null;
  28259. /**
  28260. * @property {number} _onOverFrameID - Internal variable.
  28261. * @private
  28262. * @default
  28263. */
  28264. this._onOverFrameID = null;
  28265. /**
  28266. * @property {number} _onOutFrameID - Internal variable.
  28267. * @private
  28268. * @default
  28269. */
  28270. this._onOutFrameID = null;
  28271. /**
  28272. * @property {number} _onDownFrameID - Internal variable.
  28273. * @private
  28274. * @default
  28275. */
  28276. this._onDownFrameID = null;
  28277. /**
  28278. * @property {number} _onUpFrameID - Internal variable.
  28279. * @private
  28280. * @default
  28281. */
  28282. this._onUpFrameID = null;
  28283. /**
  28284. * @property {boolean} onOverMouseOnly - If true then onOver events (such as onOverSound) will only be triggered if the Pointer object causing them was the Mouse Pointer.
  28285. * @default
  28286. */
  28287. this.onOverMouseOnly = false;
  28288. /**
  28289. * @property {Phaser.Sound} onOverSound - The Sound to be played when this Buttons Over state is activated.
  28290. * @default
  28291. */
  28292. this.onOverSound = null;
  28293. /**
  28294. * @property {Phaser.Sound} onOutSound - The Sound to be played when this Buttons Out state is activated.
  28295. * @default
  28296. */
  28297. this.onOutSound = null;
  28298. /**
  28299. * @property {Phaser.Sound} onDownSound - The Sound to be played when this Buttons Down state is activated.
  28300. * @default
  28301. */
  28302. this.onDownSound = null;
  28303. /**
  28304. * @property {Phaser.Sound} onUpSound - The Sound to be played when this Buttons Up state is activated.
  28305. * @default
  28306. */
  28307. this.onUpSound = null;
  28308. /**
  28309. * @property {string} onOverSoundMarker - The Sound Marker used in conjunction with the onOverSound.
  28310. * @default
  28311. */
  28312. this.onOverSoundMarker = '';
  28313. /**
  28314. * @property {string} onOutSoundMarker - The Sound Marker used in conjunction with the onOutSound.
  28315. * @default
  28316. */
  28317. this.onOutSoundMarker = '';
  28318. /**
  28319. * @property {string} onDownSoundMarker - The Sound Marker used in conjunction with the onDownSound.
  28320. * @default
  28321. */
  28322. this.onDownSoundMarker = '';
  28323. /**
  28324. * @property {string} onUpSoundMarker - The Sound Marker used in conjunction with the onUpSound.
  28325. * @default
  28326. */
  28327. this.onUpSoundMarker = '';
  28328. /**
  28329. * @property {Phaser.Signal} onInputOver - The Signal (or event) dispatched when this Button is in an Over state.
  28330. */
  28331. this.onInputOver = new Phaser.Signal();
  28332. /**
  28333. * @property {Phaser.Signal} onInputOut - The Signal (or event) dispatched when this Button is in an Out state.
  28334. */
  28335. this.onInputOut = new Phaser.Signal();
  28336. /**
  28337. * @property {Phaser.Signal} onInputDown - The Signal (or event) dispatched when this Button is in an Down state.
  28338. */
  28339. this.onInputDown = new Phaser.Signal();
  28340. /**
  28341. * @property {Phaser.Signal} onInputUp - The Signal (or event) dispatched when this Button is in an Up state.
  28342. */
  28343. this.onInputUp = new Phaser.Signal();
  28344. /**
  28345. * @property {boolean} freezeFrames - When true the Button will cease to change texture frame on all events (over, out, up, down).
  28346. */
  28347. this.freezeFrames = false;
  28348. /**
  28349. * When the Button is touched / clicked and then released you can force it to enter a state of "out" instead of "up".
  28350. * @property {boolean} forceOut
  28351. * @default
  28352. */
  28353. this.forceOut = false;
  28354. this.inputEnabled = true;
  28355. this.input.start(0, true);
  28356. this.setFrames(overFrame, outFrame, downFrame, upFrame);
  28357. if (callback !== null)
  28358. {
  28359. this.onInputUp.add(callback, callbackContext);
  28360. }
  28361. // Redirect the input events to here so we can handle animation updates, etc
  28362. this.events.onInputOver.add(this.onInputOverHandler, this);
  28363. this.events.onInputOut.add(this.onInputOutHandler, this);
  28364. this.events.onInputDown.add(this.onInputDownHandler, this);
  28365. this.events.onInputUp.add(this.onInputUpHandler, this);
  28366. };
  28367. Phaser.Button.prototype = Object.create(Phaser.Image.prototype);
  28368. Phaser.Button.prototype.constructor = Phaser.Button;
  28369. /**
  28370. * Clears all of the frames set on this Button.
  28371. *
  28372. * @method Phaser.Button.prototype.clearFrames
  28373. */
  28374. Phaser.Button.prototype.clearFrames = function () {
  28375. this._onOverFrameName = null;
  28376. this._onOverFrameID = null;
  28377. this._onOutFrameName = null;
  28378. this._onOutFrameID = null;
  28379. this._onDownFrameName = null;
  28380. this._onDownFrameID = null;
  28381. this._onUpFrameName = null;
  28382. this._onUpFrameID = null;
  28383. };
  28384. /**
  28385. * Used to manually set the frames that will be used for the different states of the Button.
  28386. *
  28387. * @method Phaser.Button.prototype.setFrames
  28388. * @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.
  28389. * @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.
  28390. * @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.
  28391. * @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.
  28392. */
  28393. Phaser.Button.prototype.setFrames = function (overFrame, outFrame, downFrame, upFrame) {
  28394. this.clearFrames();
  28395. if (overFrame !== null)
  28396. {
  28397. if (typeof overFrame === 'string')
  28398. {
  28399. this._onOverFrameName = overFrame;
  28400. if (this.input.pointerOver())
  28401. {
  28402. this.frameName = overFrame;
  28403. }
  28404. }
  28405. else
  28406. {
  28407. this._onOverFrameID = overFrame;
  28408. if (this.input.pointerOver())
  28409. {
  28410. this.frame = overFrame;
  28411. }
  28412. }
  28413. }
  28414. if (outFrame !== null)
  28415. {
  28416. if (typeof outFrame === 'string')
  28417. {
  28418. this._onOutFrameName = outFrame;
  28419. if (this.input.pointerOver() === false)
  28420. {
  28421. this.frameName = outFrame;
  28422. }
  28423. }
  28424. else
  28425. {
  28426. this._onOutFrameID = outFrame;
  28427. if (this.input.pointerOver() === false)
  28428. {
  28429. this.frame = outFrame;
  28430. }
  28431. }
  28432. }
  28433. if (downFrame !== null)
  28434. {
  28435. if (typeof downFrame === 'string')
  28436. {
  28437. this._onDownFrameName = downFrame;
  28438. if (this.input.pointerDown())
  28439. {
  28440. this.frameName = downFrame;
  28441. }
  28442. }
  28443. else
  28444. {
  28445. this._onDownFrameID = downFrame;
  28446. if (this.input.pointerDown())
  28447. {
  28448. this.frame = downFrame;
  28449. }
  28450. }
  28451. }
  28452. if (upFrame !== null)
  28453. {
  28454. if (typeof upFrame === 'string')
  28455. {
  28456. this._onUpFrameName = upFrame;
  28457. if (this.input.pointerUp())
  28458. {
  28459. this.frameName = upFrame;
  28460. }
  28461. }
  28462. else
  28463. {
  28464. this._onUpFrameID = upFrame;
  28465. if (this.input.pointerUp())
  28466. {
  28467. this.frame = upFrame;
  28468. }
  28469. }
  28470. }
  28471. };
  28472. /**
  28473. * 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.
  28474. * The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound.
  28475. * Call this function with no parameters at all to reset all sounds on this Button.
  28476. *
  28477. * @method Phaser.Button.prototype.setSounds
  28478. * @param {Phaser.Sound} [overSound] - Over Button Sound.
  28479. * @param {string} [overMarker] - Over Button Sound Marker.
  28480. * @param {Phaser.Sound} [downSound] - Down Button Sound.
  28481. * @param {string} [downMarker] - Down Button Sound Marker.
  28482. * @param {Phaser.Sound} [outSound] - Out Button Sound.
  28483. * @param {string} [outMarker] - Out Button Sound Marker.
  28484. * @param {Phaser.Sound} [upSound] - Up Button Sound.
  28485. * @param {string} [upMarker] - Up Button Sound Marker.
  28486. */
  28487. Phaser.Button.prototype.setSounds = function (overSound, overMarker, downSound, downMarker, outSound, outMarker, upSound, upMarker) {
  28488. this.setOverSound(overSound, overMarker);
  28489. this.setOutSound(outSound, outMarker);
  28490. this.setDownSound(downSound, downMarker);
  28491. this.setUpSound(upSound, upMarker);
  28492. };
  28493. /**
  28494. * The Sound to be played when a Pointer moves over this Button.
  28495. *
  28496. * @method Phaser.Button.prototype.setOverSound
  28497. * @param {Phaser.Sound} sound - The Sound that will be played.
  28498. * @param {string} [marker] - A Sound Marker that will be used in the playback.
  28499. */
  28500. Phaser.Button.prototype.setOverSound = function (sound, marker) {
  28501. this.onOverSound = null;
  28502. this.onOverSoundMarker = '';
  28503. if (sound instanceof Phaser.Sound)
  28504. {
  28505. this.onOverSound = sound;
  28506. }
  28507. if (typeof marker === 'string')
  28508. {
  28509. this.onOverSoundMarker = marker;
  28510. }
  28511. };
  28512. /**
  28513. * The Sound to be played when a Pointer moves out of this Button.
  28514. *
  28515. * @method Phaser.Button.prototype.setOutSound
  28516. * @param {Phaser.Sound} sound - The Sound that will be played.
  28517. * @param {string} [marker] - A Sound Marker that will be used in the playback.
  28518. */
  28519. Phaser.Button.prototype.setOutSound = function (sound, marker) {
  28520. this.onOutSound = null;
  28521. this.onOutSoundMarker = '';
  28522. if (sound instanceof Phaser.Sound)
  28523. {
  28524. this.onOutSound = sound;
  28525. }
  28526. if (typeof marker === 'string')
  28527. {
  28528. this.onOutSoundMarker = marker;
  28529. }
  28530. };
  28531. /**
  28532. * The Sound to be played when a Pointer presses down on this Button.
  28533. *
  28534. * @method Phaser.Button.prototype.setDownSound
  28535. * @param {Phaser.Sound} sound - The Sound that will be played.
  28536. * @param {string} [marker] - A Sound Marker that will be used in the playback.
  28537. */
  28538. Phaser.Button.prototype.setDownSound = function (sound, marker) {
  28539. this.onDownSound = null;
  28540. this.onDownSoundMarker = '';
  28541. if (sound instanceof Phaser.Sound)
  28542. {
  28543. this.onDownSound = sound;
  28544. }
  28545. if (typeof marker === 'string')
  28546. {
  28547. this.onDownSoundMarker = marker;
  28548. }
  28549. };
  28550. /**
  28551. * The Sound to be played when a Pointer has pressed down and is released from this Button.
  28552. *
  28553. * @method Phaser.Button.prototype.setUpSound
  28554. * @param {Phaser.Sound} sound - The Sound that will be played.
  28555. * @param {string} [marker] - A Sound Marker that will be used in the playback.
  28556. */
  28557. Phaser.Button.prototype.setUpSound = function (sound, marker) {
  28558. this.onUpSound = null;
  28559. this.onUpSoundMarker = '';
  28560. if (sound instanceof Phaser.Sound)
  28561. {
  28562. this.onUpSound = sound;
  28563. }
  28564. if (typeof marker === 'string')
  28565. {
  28566. this.onUpSoundMarker = marker;
  28567. }
  28568. };
  28569. /**
  28570. * Internal function that handles input events.
  28571. *
  28572. * @protected
  28573. * @method Phaser.Button.prototype.onInputOverHandler
  28574. * @param {Phaser.Button} sprite - The Button that the event occured on.
  28575. * @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
  28576. */
  28577. Phaser.Button.prototype.onInputOverHandler = function (sprite, pointer) {
  28578. if (this.freezeFrames === false)
  28579. {
  28580. this.setState(1);
  28581. }
  28582. if (this.onOverMouseOnly && !pointer.isMouse)
  28583. {
  28584. return;
  28585. }
  28586. if (this.onOverSound)
  28587. {
  28588. this.onOverSound.play(this.onOverSoundMarker);
  28589. }
  28590. if (this.onInputOver)
  28591. {
  28592. this.onInputOver.dispatch(this, pointer);
  28593. }
  28594. };
  28595. /**
  28596. * Internal function that handles input events.
  28597. *
  28598. * @protected
  28599. * @method Phaser.Button.prototype.onInputOutHandler
  28600. * @param {Phaser.Button} sprite - The Button that the event occured on.
  28601. * @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
  28602. */
  28603. Phaser.Button.prototype.onInputOutHandler = function (sprite, pointer) {
  28604. if (this.freezeFrames === false)
  28605. {
  28606. this.setState(2);
  28607. }
  28608. if (this.onOutSound)
  28609. {
  28610. this.onOutSound.play(this.onOutSoundMarker);
  28611. }
  28612. if (this.onInputOut)
  28613. {
  28614. this.onInputOut.dispatch(this, pointer);
  28615. }
  28616. };
  28617. /**
  28618. * Internal function that handles input events.
  28619. *
  28620. * @protected
  28621. * @method Phaser.Button.prototype.onInputDownHandler
  28622. * @param {Phaser.Button} sprite - The Button that the event occured on.
  28623. * @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
  28624. */
  28625. Phaser.Button.prototype.onInputDownHandler = function (sprite, pointer) {
  28626. if (this.freezeFrames === false)
  28627. {
  28628. this.setState(3);
  28629. }
  28630. if (this.onDownSound)
  28631. {
  28632. this.onDownSound.play(this.onDownSoundMarker);
  28633. }
  28634. if (this.onInputDown)
  28635. {
  28636. this.onInputDown.dispatch(this, pointer);
  28637. }
  28638. };
  28639. /**
  28640. * Internal function that handles input events.
  28641. *
  28642. * @protected
  28643. * @method Phaser.Button.prototype.onInputUpHandler
  28644. * @param {Phaser.Button} sprite - The Button that the event occured on.
  28645. * @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
  28646. */
  28647. Phaser.Button.prototype.onInputUpHandler = function (sprite, pointer, isOver) {
  28648. if (this.onUpSound)
  28649. {
  28650. this.onUpSound.play(this.onUpSoundMarker);
  28651. }
  28652. if (this.onInputUp)
  28653. {
  28654. this.onInputUp.dispatch(this, pointer, isOver);
  28655. }
  28656. if (this.freezeFrames)
  28657. {
  28658. return;
  28659. }
  28660. if (this.forceOut)
  28661. {
  28662. // Button should be forced to the Out frame when released.
  28663. this.setState(2);
  28664. }
  28665. else
  28666. {
  28667. if (this._onUpFrameName !== null || this._onUpFrameID !== null)
  28668. {
  28669. this.setState(4);
  28670. }
  28671. else
  28672. {
  28673. if (isOver)
  28674. {
  28675. this.setState(1);
  28676. }
  28677. else
  28678. {
  28679. this.setState(2);
  28680. }
  28681. }
  28682. }
  28683. };
  28684. /**
  28685. * Internal function that handles Button state changes.
  28686. *
  28687. * @protected
  28688. * @method Phaser.Button.prototype.setState
  28689. * @param {number} newState - The new State of the Button.
  28690. */
  28691. Phaser.Button.prototype.setState = function (newState) {
  28692. if (newState === 1)
  28693. {
  28694. // Over
  28695. if (this._onOverFrameName != null)
  28696. {
  28697. this.frameName = this._onOverFrameName;
  28698. }
  28699. else if (this._onOverFrameID != null)
  28700. {
  28701. this.frame = this._onOverFrameID;
  28702. }
  28703. }
  28704. else if (newState === 2)
  28705. {
  28706. // Out
  28707. if (this._onOutFrameName != null)
  28708. {
  28709. this.frameName = this._onOutFrameName;
  28710. }
  28711. else if (this._onOutFrameID != null)
  28712. {
  28713. this.frame = this._onOutFrameID;
  28714. }
  28715. }
  28716. else if (newState === 3)
  28717. {
  28718. // Down
  28719. if (this._onDownFrameName != null)
  28720. {
  28721. this.frameName = this._onDownFrameName;
  28722. }
  28723. else if (this._onDownFrameID != null)
  28724. {
  28725. this.frame = this._onDownFrameID;
  28726. }
  28727. }
  28728. else if (newState === 4)
  28729. {
  28730. // Up
  28731. if (this._onUpFrameName != null)
  28732. {
  28733. this.frameName = this._onUpFrameName;
  28734. }
  28735. else if (this._onUpFrameID != null)
  28736. {
  28737. this.frame = this._onUpFrameID;
  28738. }
  28739. }
  28740. };
  28741. /**
  28742. * @author Richard Davey <rich@photonstorm.com>
  28743. * @copyright 2014 Photon Storm Ltd.
  28744. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  28745. */
  28746. /**
  28747. * Creates a new `Graphics` object.
  28748. *
  28749. * @class Phaser.Graphics
  28750. * @constructor
  28751. *
  28752. * @param {Phaser.Game} game Current game instance.
  28753. * @param {number} x - X position of the new graphics object.
  28754. * @param {number} y - Y position of the new graphics object.
  28755. */
  28756. Phaser.Graphics = function (game, x, y) {
  28757. x = x || 0;
  28758. y = y || 0;
  28759. /**
  28760. * @property {Phaser.Game} game - A reference to the currently running Game.
  28761. */
  28762. this.game = game;
  28763. /**
  28764. * @property {boolean} exists - If exists = false then the Text isn't updated by the core game loop.
  28765. * @default
  28766. */
  28767. this.exists = true;
  28768. /**
  28769. * @property {string} name - The user defined name given to this object.
  28770. * @default
  28771. */
  28772. this.name = '';
  28773. /**
  28774. * @property {number} type - The const type of this object.
  28775. * @default
  28776. */
  28777. this.type = Phaser.GRAPHICS;
  28778. /**
  28779. * @property {number} z - The z-depth value of this object within its Group (remember the World is a Group as well). No two objects in a Group can have the same z value.
  28780. */
  28781. this.z = 0;
  28782. /**
  28783. * @property {Phaser.Point} world - The world coordinates of this Sprite. This differs from the x/y coordinates which are relative to the Sprites container.
  28784. */
  28785. this.world = new Phaser.Point(x, y);
  28786. /**
  28787. * @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
  28788. */
  28789. this.cameraOffset = new Phaser.Point();
  28790. PIXI.Graphics.call(this);
  28791. this.position.set(x, y);
  28792. /**
  28793. * A small internal cache:
  28794. * 0 = previous position.x
  28795. * 1 = previous position.y
  28796. * 2 = previous rotation
  28797. * 3 = renderID
  28798. * 4 = fresh? (0 = no, 1 = yes)
  28799. * 5 = outOfBoundsFired (0 = no, 1 = yes)
  28800. * 6 = exists (0 = no, 1 = yes)
  28801. * 7 = fixed to camera (0 = no, 1 = yes)
  28802. * 8 = destroy phase? (0 = no, 1 = yes)
  28803. * @property {Array} _cache
  28804. * @private
  28805. */
  28806. this._cache = [ 0, 0, 0, 0, 1, 0, 1, 0, 0 ];
  28807. };
  28808. Phaser.Graphics.prototype = Object.create(PIXI.Graphics.prototype);
  28809. Phaser.Graphics.prototype.constructor = Phaser.Graphics;
  28810. /**
  28811. * Automatically called by World.preUpdate.
  28812. * @method Phaser.Graphics.prototype.preUpdate
  28813. */
  28814. Phaser.Graphics.prototype.preUpdate = function () {
  28815. this._cache[0] = this.world.x;
  28816. this._cache[1] = this.world.y;
  28817. this._cache[2] = this.rotation;
  28818. if (!this.exists || !this.parent.exists)
  28819. {
  28820. this.renderOrderID = -1;
  28821. return false;
  28822. }
  28823. if (this.autoCull)
  28824. {
  28825. // Won't get rendered but will still get its transform updated
  28826. this.renderable = this.game.world.camera.screenView.intersects(this.getBounds());
  28827. }
  28828. this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty);
  28829. if (this.visible)
  28830. {
  28831. this._cache[3] = this.game.stage.currentRenderOrderID++;
  28832. }
  28833. return true;
  28834. };
  28835. /**
  28836. * Override and use this function in your own custom objects to handle any update requirements you may have.
  28837. *
  28838. * @method Phaser.Graphics#update
  28839. * @memberof Phaser.Graphics
  28840. */
  28841. Phaser.Graphics.prototype.update = function() {
  28842. };
  28843. /**
  28844. * Automatically called by World.postUpdate.
  28845. * @method Phaser.Graphics.prototype.postUpdate
  28846. */
  28847. Phaser.Graphics.prototype.postUpdate = function () {
  28848. // Fixed to Camera?
  28849. if (this._cache[7] === 1)
  28850. {
  28851. this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
  28852. this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
  28853. }
  28854. };
  28855. /**
  28856. * Destroy this Graphics instance.
  28857. *
  28858. * @method Phaser.Graphics.prototype.destroy
  28859. * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
  28860. */
  28861. Phaser.Graphics.prototype.destroy = function(destroyChildren) {
  28862. if (this.game === null || this.destroyPhase) { return; }
  28863. if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
  28864. this._cache[8] = 1;
  28865. this.clear();
  28866. if (this.parent)
  28867. {
  28868. if (this.parent instanceof Phaser.Group)
  28869. {
  28870. this.parent.remove(this);
  28871. }
  28872. else
  28873. {
  28874. this.parent.removeChild(this);
  28875. }
  28876. }
  28877. var i = this.children.length;
  28878. if (destroyChildren)
  28879. {
  28880. while (i--)
  28881. {
  28882. this.children[i].destroy(destroyChildren);
  28883. }
  28884. }
  28885. else
  28886. {
  28887. while (i--)
  28888. {
  28889. this.removeChild(this.children[i]);
  28890. }
  28891. }
  28892. this.exists = false;
  28893. this.visible = false;
  28894. this.game = null;
  28895. this._cache[8] = 0;
  28896. };
  28897. /*
  28898. * Draws a {Phaser.Polygon} or a {PIXI.Polygon} filled
  28899. *
  28900. * @method Phaser.Graphics.prototype.drawPolygon
  28901. */
  28902. Phaser.Graphics.prototype.drawPolygon = function (poly) {
  28903. this.moveTo(poly.points[0].x, poly.points[0].y);
  28904. for (var i = 1; i < poly.points.length; i += 1)
  28905. {
  28906. this.lineTo(poly.points[i].x, poly.points[i].y);
  28907. }
  28908. this.lineTo(poly.points[0].x, poly.points[0].y);
  28909. };
  28910. /*
  28911. * Draws a single {Phaser.Polygon} triangle from a {Phaser.Point} array
  28912. *
  28913. * @method Phaser.Graphics.prototype.drawTriangle
  28914. * @param {Array<Phaser.Point>} points - An array of Phaser.Points that make up the three vertices of this triangle
  28915. * @param {boolean} [cull=false] - Should we check if the triangle is back-facing
  28916. */
  28917. Phaser.Graphics.prototype.drawTriangle = function(points, cull) {
  28918. if (typeof cull === 'undefined') { cull = false; }
  28919. var triangle = new Phaser.Polygon(points);
  28920. if (cull)
  28921. {
  28922. var cameraToFace = new Phaser.Point(this.game.camera.x - points[0].x, this.game.camera.y - points[0].y);
  28923. var ab = new Phaser.Point(points[1].x - points[0].x, points[1].y - points[0].y);
  28924. var cb = new Phaser.Point(points[1].x - points[2].x, points[1].y - points[2].y);
  28925. var faceNormal = cb.cross(ab);
  28926. if (cameraToFace.dot(faceNormal) > 0)
  28927. {
  28928. this.drawPolygon(triangle);
  28929. }
  28930. }
  28931. else
  28932. {
  28933. this.drawPolygon(triangle);
  28934. }
  28935. };
  28936. /*
  28937. * Draws {Phaser.Polygon} triangles
  28938. *
  28939. * @method Phaser.Graphics.prototype.drawTriangles
  28940. * @param {Array<Phaser.Point>|Array<number>} vertices - An array of Phaser.Points or numbers that make up the vertices of the triangles
  28941. * @param {Array<number>} {indices=null} - An array of numbers that describe what order to draw the vertices in
  28942. * @param {boolean} [cull=false] - Should we check if the triangle is back-facing
  28943. */
  28944. Phaser.Graphics.prototype.drawTriangles = function(vertices, indices, cull) {
  28945. if (typeof cull === 'undefined') { cull = false; }
  28946. var point1 = new Phaser.Point();
  28947. var point2 = new Phaser.Point();
  28948. var point3 = new Phaser.Point();
  28949. var points = [];
  28950. var i;
  28951. if (!indices)
  28952. {
  28953. if (vertices[0] instanceof Phaser.Point)
  28954. {
  28955. for (i = 0; i < vertices.length / 3; i++)
  28956. {
  28957. this.drawTriangle([vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2]], cull);
  28958. }
  28959. }
  28960. else
  28961. {
  28962. for (i = 0; i < vertices.length / 6; i++)
  28963. {
  28964. point1.x = vertices[i * 6 + 0];
  28965. point1.y = vertices[i * 6 + 1];
  28966. point2.x = vertices[i * 6 + 2];
  28967. point2.y = vertices[i * 6 + 3];
  28968. point3.x = vertices[i * 6 + 4];
  28969. point3.y = vertices[i * 6 + 5];
  28970. this.drawTriangle([point1, point2, point3], cull);
  28971. }
  28972. }
  28973. }
  28974. else
  28975. {
  28976. if (vertices[0] instanceof Phaser.Point)
  28977. {
  28978. for (i = 0; i < indices.length /3; i++)
  28979. {
  28980. points.push(vertices[indices[i * 3 ]]);
  28981. points.push(vertices[indices[i * 3 + 1]]);
  28982. points.push(vertices[indices[i * 3 + 2]]);
  28983. if (points.length === 3)
  28984. {
  28985. this.drawTriangle(points, cull);
  28986. points = [];
  28987. }
  28988. }
  28989. }
  28990. else
  28991. {
  28992. for (i = 0; i < indices.length; i++)
  28993. {
  28994. point1.x = vertices[indices[i] * 2];
  28995. point1.y = vertices[indices[i] * 2 + 1];
  28996. points.push(point1.copyTo({}));
  28997. if (points.length === 3)
  28998. {
  28999. this.drawTriangle(points, cull);
  29000. points = [];
  29001. }
  29002. }
  29003. }
  29004. }
  29005. };
  29006. /**
  29007. * Indicates the rotation of the Graphics, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
  29008. * Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
  29009. * If you wish to work in radians instead of degrees use the property Sprite.rotation instead.
  29010. *
  29011. * @name Phaser.Graphics#angle
  29012. * @property {number} angle - Gets or sets the angle of rotation in degrees.
  29013. */
  29014. Object.defineProperty(Phaser.Graphics.prototype, 'angle', {
  29015. get: function() {
  29016. return Phaser.Math.radToDeg(this.rotation);
  29017. },
  29018. set: function(value) {
  29019. this.rotation = Phaser.Math.degToRad(value);
  29020. }
  29021. });
  29022. /**
  29023. * An Graphics that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Graphics.cameraOffset.
  29024. * Note that the cameraOffset values are in addition to any parent in the display list.
  29025. * So if this Graphics was in a Group that has x: 200, then this will be added to the cameraOffset.x
  29026. *
  29027. * @name Phaser.Graphics#fixedToCamera
  29028. * @property {boolean} fixedToCamera - Set to true to fix this Graphics to the Camera at its current world coordinates.
  29029. */
  29030. Object.defineProperty(Phaser.Graphics.prototype, "fixedToCamera", {
  29031. get: function () {
  29032. return !!this._cache[7];
  29033. },
  29034. set: function (value) {
  29035. if (value)
  29036. {
  29037. this._cache[7] = 1;
  29038. this.cameraOffset.set(this.x, this.y);
  29039. }
  29040. else
  29041. {
  29042. this._cache[7] = 0;
  29043. }
  29044. }
  29045. });
  29046. /**
  29047. * @name Phaser.Graphics#destroyPhase
  29048. * @property {boolean} destroyPhase - True if this object is currently being destroyed.
  29049. */
  29050. Object.defineProperty(Phaser.Graphics.prototype, "destroyPhase", {
  29051. get: function () {
  29052. return !!this._cache[8];
  29053. }
  29054. });
  29055. /**
  29056. * @author Richard Davey <rich@photonstorm.com>
  29057. * @copyright 2014 Photon Storm Ltd.
  29058. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  29059. */
  29060. /**
  29061. * A RenderTexture is a special texture that allows any displayObject to be rendered to it.
  29062. * @class Phaser.RenderTexture
  29063. * @constructor
  29064. * @param {Phaser.Game} game - Current game instance.
  29065. * @param {string} key - Internal Phaser reference key for the render texture.
  29066. * @param {number} [width=100] - The width of the render texture.
  29067. * @param {number} [height=100] - The height of the render texture.
  29068. * @param {string} [key=''] - The key of the RenderTexture in the Cache, if stored there.
  29069. * @param {number} [scaleMode=Phaser.scaleModes.DEFAULT] - One of the Phaser.scaleModes consts.
  29070. */
  29071. Phaser.RenderTexture = function (game, width, height, key, scaleMode) {
  29072. if (typeof key === 'undefined') { key = ''; }
  29073. if (typeof scaleMode === 'undefined') { scaleMode = Phaser.scaleModes.DEFAULT; }
  29074. /**
  29075. * @property {Phaser.Game} game - A reference to the currently running game.
  29076. */
  29077. this.game = game;
  29078. /**
  29079. * @property {string} key - The key of the RenderTexture in the Cache, if stored there.
  29080. */
  29081. this.key = key;
  29082. /**
  29083. * @property {number} type - Base Phaser object type.
  29084. */
  29085. this.type = Phaser.RENDERTEXTURE;
  29086. /**
  29087. * @property {Phaser.Point} _temp - Internal var.
  29088. * @private
  29089. */
  29090. this._temp = new Phaser.Point();
  29091. PIXI.RenderTexture.call(this, width, height, this.game.renderer, scaleMode);
  29092. };
  29093. Phaser.RenderTexture.prototype = Object.create(PIXI.RenderTexture.prototype);
  29094. Phaser.RenderTexture.prototype.constructor = Phaser.RenderTexture;
  29095. /**
  29096. * This function will draw the display object to the texture.
  29097. *
  29098. * @method Phaser.RenderTexture.prototype.renderXY
  29099. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject The display object to render to this texture.
  29100. * @param {number} x - The x position to render the object at.
  29101. * @param {number} y - The y position to render the object at.
  29102. * @param {boolean} clear - If true the texture will be cleared before the display object is drawn.
  29103. */
  29104. Phaser.RenderTexture.prototype.renderXY = function (displayObject, x, y, clear) {
  29105. this._temp.set(x, y);
  29106. this.render(displayObject, this._temp, clear);
  29107. };
  29108. // Documentation stubs
  29109. /**
  29110. * This function will draw the display object to the texture.
  29111. *
  29112. * @method Phaser.RenderTexture.prototype.render
  29113. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject The display object to render to this texture.
  29114. * @param {Phaser.Point} position - A Point object containing the position to render the display object at.
  29115. * @param {boolean} clear - If true the texture will be cleared before the display object is drawn.
  29116. */
  29117. /**
  29118. * Resize this RenderTexture to the given width and height.
  29119. *
  29120. * @method Phaser.RenderTexture.prototype.resize
  29121. * @param {number} width - The new width of the RenderTexture.
  29122. * @param {number} height - The new height of the RenderTexture.
  29123. */
  29124. /**
  29125. * @author Richard Davey <rich@photonstorm.com>
  29126. * @copyright 2014 Photon Storm Ltd.
  29127. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  29128. */
  29129. /**
  29130. * Phaser SpriteBatch constructor.
  29131. *
  29132. * @classdesc The SpriteBatch class is a really fast version of the DisplayObjectContainer built solely for speed, so use when you need a lot of sprites or particles.
  29133. * @class Phaser.SpriteBatch
  29134. * @extends Phaser.Group
  29135. * @constructor
  29136. * @param {Phaser.Game} game - A reference to the currently running game.
  29137. * @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.
  29138. * @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging.
  29139. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  29140. */
  29141. Phaser.SpriteBatch = function (game, parent, name, addToStage) {
  29142. if (typeof parent === 'undefined' || parent === null) { parent = game.world; }
  29143. PIXI.SpriteBatch.call(this);
  29144. Phaser.Group.call(this, game, parent, name, addToStage);
  29145. /**
  29146. * @property {number} type - Internal Phaser Type value.
  29147. * @protected
  29148. */
  29149. this.type = Phaser.SPRITEBATCH;
  29150. };
  29151. Phaser.SpriteBatch.prototype = Phaser.Utils.extend(true, Phaser.SpriteBatch.prototype, Phaser.Group.prototype, PIXI.SpriteBatch.prototype);
  29152. Phaser.SpriteBatch.prototype.constructor = Phaser.SpriteBatch;
  29153. /**
  29154. * @author Richard Davey <rich@photonstorm.com>
  29155. * @copyright 2014 Photon Storm Ltd.
  29156. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  29157. */
  29158. /**
  29159. * @class Phaser.RetroFont
  29160. * @extends Phaser.RenderTexture
  29161. * @constructor
  29162. * @param {Phaser.Game} game - Current game instance.
  29163. * @param {string} key - The font set graphic set as stored in the Game.Cache.
  29164. * @param {number} characterWidth - The width of each character in the font set.
  29165. * @param {number} characterHeight - The height of each character in the font set.
  29166. * @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.
  29167. * @param {number} [charsPerRow] - The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth.
  29168. * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
  29169. * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
  29170. * @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.
  29171. * @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.
  29172. */
  29173. Phaser.RetroFont = function (game, key, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
  29174. if (!game.cache.checkImageKey(key))
  29175. {
  29176. return false;
  29177. }
  29178. if (typeof charsPerRow === 'undefined' || charsPerRow === null)
  29179. {
  29180. charsPerRow = game.cache.getImage(key).width / characterWidth;
  29181. }
  29182. /**
  29183. * @property {number} characterWidth - The width of each character in the font set.
  29184. */
  29185. this.characterWidth = characterWidth;
  29186. /**
  29187. * @property {number} characterHeight - The height of each character in the font set.
  29188. */
  29189. this.characterHeight = characterHeight;
  29190. /**
  29191. * @property {number} characterSpacingX - If the characters in the font set have horizontal spacing between them set the required amount here.
  29192. */
  29193. this.characterSpacingX = xSpacing || 0;
  29194. /**
  29195. * @property {number} characterSpacingY - If the characters in the font set have vertical spacing between them set the required amount here.
  29196. */
  29197. this.characterSpacingY = ySpacing || 0;
  29198. /**
  29199. * @property {number} characterPerRow - The number of characters per row in the font set.
  29200. */
  29201. this.characterPerRow = charsPerRow;
  29202. /**
  29203. * @property {number} offsetX - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
  29204. * @readonly
  29205. */
  29206. this.offsetX = xOffset || 0;
  29207. /**
  29208. * @property {number} offsetY - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
  29209. * @readonly
  29210. */
  29211. this.offsetY = yOffset || 0;
  29212. /**
  29213. * @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.
  29214. */
  29215. this.align = "left";
  29216. /**
  29217. * @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)
  29218. * @default
  29219. */
  29220. this.multiLine = false;
  29221. /**
  29222. * @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.
  29223. * @default
  29224. */
  29225. this.autoUpperCase = true;
  29226. /**
  29227. * @property {number} customSpacingX - Adds horizontal spacing between each character of the font, in pixels.
  29228. * @default
  29229. */
  29230. this.customSpacingX = 0;
  29231. /**
  29232. * @property {number} customSpacingY - Adds vertical spacing between each line of multi-line text, set in pixels.
  29233. * @default
  29234. */
  29235. this.customSpacingY = 0;
  29236. /**
  29237. * If you need this RetroFont image to have a fixed width you can set the width in this value.
  29238. * If text is wider than the width specified it will be cropped off.
  29239. * @property {number} fixedWidth
  29240. */
  29241. this.fixedWidth = 0;
  29242. /**
  29243. * @property {HTMLImage} fontSet - A reference to the image stored in the Game.Cache that contains the font.
  29244. */
  29245. this.fontSet = game.cache.getImage(key);
  29246. /**
  29247. * @property {string} _text - The text of the font image.
  29248. * @private
  29249. */
  29250. this._text = '';
  29251. /**
  29252. * @property {array} grabData - An array of rects for faster character pasting.
  29253. * @private
  29254. */
  29255. this.grabData = [];
  29256. // Now generate our rects for faster copying later on
  29257. var currentX = this.offsetX;
  29258. var currentY = this.offsetY;
  29259. var r = 0;
  29260. var data = new Phaser.FrameData();
  29261. for (var c = 0; c < chars.length; c++)
  29262. {
  29263. var uuid = game.rnd.uuid();
  29264. var frame = data.addFrame(new Phaser.Frame(c, currentX, currentY, this.characterWidth, this.characterHeight, '', uuid));
  29265. this.grabData[chars.charCodeAt(c)] = frame.index;
  29266. PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[key], {
  29267. x: currentX,
  29268. y: currentY,
  29269. width: this.characterWidth,
  29270. height: this.characterHeight
  29271. });
  29272. r++;
  29273. if (r == this.characterPerRow)
  29274. {
  29275. r = 0;
  29276. currentX = this.offsetX;
  29277. currentY += this.characterHeight + this.characterSpacingY;
  29278. }
  29279. else
  29280. {
  29281. currentX += this.characterWidth + this.characterSpacingX;
  29282. }
  29283. }
  29284. game.cache.updateFrameData(key, data);
  29285. /**
  29286. * @property {Phaser.Image} stamp - The image that is stamped to the RenderTexture for each character in the font.
  29287. * @readonly
  29288. */
  29289. this.stamp = new Phaser.Image(game, 0, 0, key, 0);
  29290. Phaser.RenderTexture.call(this, game, 100, 100, '', Phaser.scaleModes.NEAREST);
  29291. /**
  29292. * @property {number} type - Base Phaser object type.
  29293. */
  29294. this.type = Phaser.RETROFONT;
  29295. };
  29296. Phaser.RetroFont.prototype = Object.create(Phaser.RenderTexture.prototype);
  29297. Phaser.RetroFont.prototype.constructor = Phaser.RetroFont;
  29298. /**
  29299. * Align each line of multi-line text to the left.
  29300. * @constant
  29301. * @type {string}
  29302. */
  29303. Phaser.RetroFont.ALIGN_LEFT = "left";
  29304. /**
  29305. * Align each line of multi-line text to the right.
  29306. * @constant
  29307. * @type {string}
  29308. */
  29309. Phaser.RetroFont.ALIGN_RIGHT = "right";
  29310. /**
  29311. * Align each line of multi-line text in the center.
  29312. * @constant
  29313. * @type {string}
  29314. */
  29315. Phaser.RetroFont.ALIGN_CENTER = "center";
  29316. /**
  29317. * Text Set 1 = !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
  29318. * @constant
  29319. * @type {string}
  29320. */
  29321. Phaser.RetroFont.TEXT_SET1 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
  29322. /**
  29323. * Text Set 2 = !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ
  29324. * @constant
  29325. * @type {string}
  29326. */
  29327. Phaser.RetroFont.TEXT_SET2 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  29328. /**
  29329. * Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
  29330. * @constant
  29331. * @type {string}
  29332. */
  29333. Phaser.RetroFont.TEXT_SET3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
  29334. /**
  29335. * Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789
  29336. * @constant
  29337. * @type {string}
  29338. */
  29339. Phaser.RetroFont.TEXT_SET4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789";
  29340. /**
  29341. * Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789
  29342. * @constant
  29343. * @type {string}
  29344. */
  29345. Phaser.RetroFont.TEXT_SET5 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789";
  29346. /**
  29347. * Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.'
  29348. * @constant
  29349. * @type {string}
  29350. */
  29351. Phaser.RetroFont.TEXT_SET6 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ";
  29352. /**
  29353. * Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39
  29354. * @constant
  29355. * @type {string}
  29356. */
  29357. Phaser.RetroFont.TEXT_SET7 = "AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39";
  29358. /**
  29359. * Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ
  29360. * @constant
  29361. * @type {string}
  29362. */
  29363. Phaser.RetroFont.TEXT_SET8 = "0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  29364. /**
  29365. * Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!
  29366. * @constant
  29367. * @type {string}
  29368. */
  29369. Phaser.RetroFont.TEXT_SET9 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!";
  29370. /**
  29371. * Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ
  29372. * @constant
  29373. * @type {string}
  29374. */
  29375. Phaser.RetroFont.TEXT_SET10 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  29376. /**
  29377. * Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789
  29378. * @constant
  29379. * @type {string}
  29380. */
  29381. Phaser.RetroFont.TEXT_SET11 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789";
  29382. /**
  29383. * If you need this RetroFont to have a fixed width and custom alignment you can set the width here.
  29384. * If text is wider than the width specified it will be cropped off.
  29385. *
  29386. * @method Phaser.RetroFont#setFixedWidth
  29387. * @memberof Phaser.RetroFont
  29388. * @param {number} width - Width in pixels of this RetroFont. Set to zero to disable and re-enable automatic resizing.
  29389. * @param {string} [lineAlignment='left'] - Align the text within this width. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER.
  29390. */
  29391. Phaser.RetroFont.prototype.setFixedWidth = function (width, lineAlignment) {
  29392. if (typeof lineAlignment === 'undefined') { lineAlignment = 'left'; }
  29393. this.fixedWidth = width;
  29394. this.align = lineAlignment;
  29395. };
  29396. /**
  29397. * A helper function that quickly sets lots of variables at once, and then updates the text.
  29398. *
  29399. * @method Phaser.RetroFont#setText
  29400. * @memberof Phaser.RetroFont
  29401. * @param {string} content - The text of this sprite.
  29402. * @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.
  29403. * @param {number} [characterSpacing=0] - To add horizontal spacing between each character specify the amount in pixels.
  29404. * @param {number} [lineSpacing=0] - To add vertical spacing between each line of text, set the amount in pixels.
  29405. * @param {string} [lineAlignment='left'] - Align each line of multi-line text. Set to RetroFont.ALIGN_LEFT, RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER.
  29406. * @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.
  29407. */
  29408. Phaser.RetroFont.prototype.setText = function (content, multiLine, characterSpacing, lineSpacing, lineAlignment, allowLowerCase) {
  29409. this.multiLine = multiLine || false;
  29410. this.customSpacingX = characterSpacing || 0;
  29411. this.customSpacingY = lineSpacing || 0;
  29412. this.align = lineAlignment || 'left';
  29413. if (allowLowerCase)
  29414. {
  29415. this.autoUpperCase = false;
  29416. }
  29417. else
  29418. {
  29419. this.autoUpperCase = true;
  29420. }
  29421. if (content.length > 0)
  29422. {
  29423. this.text = content;
  29424. }
  29425. };
  29426. /**
  29427. * Updates the texture with the new text.
  29428. *
  29429. * @method Phaser.RetroFont#buildRetroFontText
  29430. * @memberof Phaser.RetroFont
  29431. */
  29432. Phaser.RetroFont.prototype.buildRetroFontText = function () {
  29433. var cx = 0;
  29434. var cy = 0;
  29435. this.clear();
  29436. if (this.multiLine)
  29437. {
  29438. var lines = this._text.split("\n");
  29439. if (this.fixedWidth > 0)
  29440. {
  29441. this.resize(this.fixedWidth, (lines.length * (this.characterHeight + this.customSpacingY)) - this.customSpacingY, true);
  29442. }
  29443. else
  29444. {
  29445. this.resize(this.getLongestLine() * (this.characterWidth + this.customSpacingX), (lines.length * (this.characterHeight + this.customSpacingY)) - this.customSpacingY, true);
  29446. }
  29447. // Loop through each line of text
  29448. for (var i = 0; i < lines.length; i++)
  29449. {
  29450. // This line of text is held in lines[i] - need to work out the alignment
  29451. switch (this.align)
  29452. {
  29453. case Phaser.RetroFont.ALIGN_LEFT:
  29454. cx = 0;
  29455. break;
  29456. case Phaser.RetroFont.ALIGN_RIGHT:
  29457. cx = this.width - (lines[i].length * (this.characterWidth + this.customSpacingX));
  29458. break;
  29459. case Phaser.RetroFont.ALIGN_CENTER:
  29460. cx = (this.width / 2) - ((lines[i].length * (this.characterWidth + this.customSpacingX)) / 2);
  29461. cx += this.customSpacingX / 2;
  29462. break;
  29463. }
  29464. // Sanity checks
  29465. if (cx < 0)
  29466. {
  29467. cx = 0;
  29468. }
  29469. this.pasteLine(lines[i], cx, cy, this.customSpacingX);
  29470. cy += this.characterHeight + this.customSpacingY;
  29471. }
  29472. }
  29473. else
  29474. {
  29475. if (this.fixedWidth > 0)
  29476. {
  29477. this.resize(this.fixedWidth, this.characterHeight, true);
  29478. }
  29479. else
  29480. {
  29481. this.resize(this._text.length * (this.characterWidth + this.customSpacingX), this.characterHeight, true);
  29482. }
  29483. switch (this.align)
  29484. {
  29485. case Phaser.RetroFont.ALIGN_LEFT:
  29486. cx = 0;
  29487. break;
  29488. case Phaser.RetroFont.ALIGN_RIGHT:
  29489. cx = this.width - (this._text.length * (this.characterWidth + this.customSpacingX));
  29490. break;
  29491. case Phaser.RetroFont.ALIGN_CENTER:
  29492. cx = (this.width / 2) - ((this._text.length * (this.characterWidth + this.customSpacingX)) / 2);
  29493. cx += this.customSpacingX / 2;
  29494. break;
  29495. }
  29496. this.textureBuffer.clear();
  29497. this.pasteLine(this._text, cx, 0, this.customSpacingX);
  29498. }
  29499. };
  29500. /**
  29501. * Internal function that takes a single line of text (2nd parameter) and pastes it into the BitmapData at the given coordinates.
  29502. * Used by getLine and getMultiLine
  29503. *
  29504. * @method Phaser.RetroFont#pasteLine
  29505. * @memberof Phaser.RetroFont
  29506. * @param {string} line - The single line of text to paste.
  29507. * @param {number} x - The x coordinate.
  29508. * @param {number} y - The y coordinate.
  29509. * @param {number} customSpacingX - Custom X spacing.
  29510. */
  29511. Phaser.RetroFont.prototype.pasteLine = function (line, x, y, customSpacingX) {
  29512. var p = new Phaser.Point();
  29513. for (var c = 0; c < line.length; c++)
  29514. {
  29515. // If it's a space then there is no point copying, so leave a blank space
  29516. if (line.charAt(c) == " ")
  29517. {
  29518. x += this.characterWidth + customSpacingX;
  29519. }
  29520. else
  29521. {
  29522. // If the character doesn't exist in the font then we don't want a blank space, we just want to skip it
  29523. if (this.grabData[line.charCodeAt(c)] >= 0)
  29524. {
  29525. this.stamp.frame = this.grabData[line.charCodeAt(c)];
  29526. p.set(x, y);
  29527. this.render(this.stamp, p, false);
  29528. x += this.characterWidth + customSpacingX;
  29529. if (x > this.width)
  29530. {
  29531. break;
  29532. }
  29533. }
  29534. }
  29535. }
  29536. };
  29537. /**
  29538. * Works out the longest line of text in _text and returns its length
  29539. *
  29540. * @method Phaser.RetroFont#getLongestLine
  29541. * @memberof Phaser.RetroFont
  29542. * @return {number} The length of the longest line of text.
  29543. */
  29544. Phaser.RetroFont.prototype.getLongestLine = function () {
  29545. var longestLine = 0;
  29546. if (this._text.length > 0)
  29547. {
  29548. var lines = this._text.split("\n");
  29549. for (var i = 0; i < lines.length; i++)
  29550. {
  29551. if (lines[i].length > longestLine)
  29552. {
  29553. longestLine = lines[i].length;
  29554. }
  29555. }
  29556. }
  29557. return longestLine;
  29558. };
  29559. /**
  29560. * Internal helper function that removes all unsupported characters from the _text String, leaving only characters contained in the font set.
  29561. *
  29562. * @method Phaser.RetroFont#removeUnsupportedCharacters
  29563. * @memberof Phaser.RetroFont
  29564. * @protected
  29565. * @param {boolean} [stripCR=true] - Should it strip carriage returns as well?
  29566. * @return {string} A clean version of the string.
  29567. */
  29568. Phaser.RetroFont.prototype.removeUnsupportedCharacters = function (stripCR) {
  29569. var newString = "";
  29570. for (var c = 0; c < this._text.length; c++)
  29571. {
  29572. var aChar = this._text[c];
  29573. var code = aChar.charCodeAt(0);
  29574. if (this.grabData[code] >= 0 || (!stripCR && aChar === "\n"))
  29575. {
  29576. newString = newString.concat(aChar);
  29577. }
  29578. }
  29579. return newString;
  29580. };
  29581. /**
  29582. * 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.
  29583. * 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.
  29584. * 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.
  29585. *
  29586. * @method Phaser.RetroFont#updateOffset
  29587. * @memberof Phaser.RetroFont
  29588. * @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.
  29589. * @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.
  29590. */
  29591. Phaser.RetroFont.prototype.updateOffset = function (x, y) {
  29592. if (this.offsetX === x && this.offsetY === y)
  29593. {
  29594. return;
  29595. }
  29596. var diffX = x - this.offsetX;
  29597. var diffY = y - this.offsetY;
  29598. var frames = this.game.cache.getFrameData(this.stamp.key).getFrames();
  29599. var i = frames.length;
  29600. while (i--)
  29601. {
  29602. frames[i].x += diffX;
  29603. frames[i].y += diffY;
  29604. PIXI.TextureCache[frames[i].uuid].frame.x = frames[i].x;
  29605. PIXI.TextureCache[frames[i].uuid].frame.y = frames[i].y;
  29606. }
  29607. this.buildRetroFontText();
  29608. };
  29609. /**
  29610. * @name Phaser.BitmapText#text
  29611. * @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.
  29612. */
  29613. Object.defineProperty(Phaser.RetroFont.prototype, "text", {
  29614. get: function () {
  29615. return this._text;
  29616. },
  29617. set: function (value) {
  29618. var newText;
  29619. if (this.autoUpperCase)
  29620. {
  29621. newText = value.toUpperCase();
  29622. }
  29623. else
  29624. {
  29625. newText = value;
  29626. }
  29627. if (newText !== this._text)
  29628. {
  29629. this._text = newText;
  29630. this.removeUnsupportedCharacters(this.multiLine);
  29631. this.buildRetroFontText();
  29632. }
  29633. }
  29634. });
  29635. /**
  29636. * @name Phaser.BitmapText#smoothed
  29637. * @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.
  29638. */
  29639. Object.defineProperty(Phaser.RetroFont.prototype, "smoothed", {
  29640. get: function () {
  29641. return this.stamp.smoothed;
  29642. },
  29643. set: function (value) {
  29644. this.stamp.smoothed = value;
  29645. this.buildRetroFontText();
  29646. }
  29647. });
  29648. /**
  29649. * @author Richard Davey <rich@photonstorm.com>
  29650. * @copyright 2014 Photon Storm Ltd.
  29651. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  29652. */
  29653. /**
  29654. * @class Phaser.Particle
  29655. *
  29656. * @classdesc Create a new `Particle` object. Particles are extended Sprites that are emitted by a particle emitter such as Phaser.Particles.Arcade.Emitter.
  29657. *
  29658. * @constructor
  29659. * @extends Phaser.Sprite
  29660. * @param {Phaser.Game} game - A reference to the currently running game.
  29661. * @param {number} x - The x coordinate (in world space) to position the Particle at.
  29662. * @param {number} y - The y coordinate (in world space) to position the Particle at.
  29663. * @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.
  29664. * @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.
  29665. */
  29666. Phaser.Particle = function (game, x, y, key, frame) {
  29667. Phaser.Sprite.call(this, game, x, y, key, frame);
  29668. /**
  29669. * @property {boolean} autoScale - If this Particle automatically scales this is set to true by Particle.setScaleData.
  29670. * @protected
  29671. */
  29672. this.autoScale = false;
  29673. /**
  29674. * @property {array} scaleData - A reference to the scaleData array owned by the Emitter that emitted this Particle.
  29675. * @protected
  29676. */
  29677. this.scaleData = null;
  29678. /**
  29679. * @property {number} _s - Internal cache var for tracking auto scale.
  29680. * @private
  29681. */
  29682. this._s = 0;
  29683. /**
  29684. * @property {boolean} autoAlpha - If this Particle automatically changes alpha this is set to true by Particle.setAlphaData.
  29685. * @protected
  29686. */
  29687. this.autoAlpha = false;
  29688. /**
  29689. * @property {array} alphaData - A reference to the alphaData array owned by the Emitter that emitted this Particle.
  29690. * @protected
  29691. */
  29692. this.alphaData = null;
  29693. /**
  29694. * @property {number} _a - Internal cache var for tracking auto alpha.
  29695. * @private
  29696. */
  29697. this._a = 0;
  29698. };
  29699. Phaser.Particle.prototype = Object.create(Phaser.Sprite.prototype);
  29700. Phaser.Particle.prototype.constructor = Phaser.Particle;
  29701. /**
  29702. * Updates the Particle scale or alpha if autoScale and autoAlpha are set.
  29703. *
  29704. * @method Phaser.Particle#update
  29705. * @memberof Phaser.Particle
  29706. */
  29707. Phaser.Particle.prototype.update = function() {
  29708. if (this.autoScale)
  29709. {
  29710. this._s--;
  29711. if (this._s)
  29712. {
  29713. this.scale.set(this.scaleData[this._s].x, this.scaleData[this._s].y);
  29714. }
  29715. else
  29716. {
  29717. this.autoScale = false;
  29718. }
  29719. }
  29720. if (this.autoAlpha)
  29721. {
  29722. this._a--;
  29723. if (this._a)
  29724. {
  29725. this.alpha = this.alphaData[this._a].v;
  29726. }
  29727. else
  29728. {
  29729. this.autoAlpha = false;
  29730. }
  29731. }
  29732. };
  29733. /**
  29734. * Called by the Emitter when this particle is emitted. Left empty for you to over-ride as required.
  29735. *
  29736. * @method Phaser.Particle#onEmit
  29737. * @memberof Phaser.Particle
  29738. */
  29739. Phaser.Particle.prototype.onEmit = function() {
  29740. };
  29741. /**
  29742. * Called by the Emitter if autoAlpha has been enabled. Passes over the alpha ease data and resets the alpha counter.
  29743. *
  29744. * @method Phaser.Particle#setAlphaData
  29745. * @memberof Phaser.Particle
  29746. */
  29747. Phaser.Particle.prototype.setAlphaData = function(data) {
  29748. this.alphaData = data;
  29749. this._a = data.length - 1;
  29750. this.alpha = this.alphaData[this._a].v;
  29751. this.autoAlpha = true;
  29752. };
  29753. /**
  29754. * Called by the Emitter if autoScale has been enabled. Passes over the scale ease data and resets the scale counter.
  29755. *
  29756. * @method Phaser.Particle#setScaleData
  29757. * @memberof Phaser.Particle
  29758. */
  29759. Phaser.Particle.prototype.setScaleData = function(data) {
  29760. this.scaleData = data;
  29761. this._s = data.length - 1;
  29762. this.scale.set(this.scaleData[this._s].x, this.scaleData[this._s].y);
  29763. this.autoScale = true;
  29764. };
  29765. /**
  29766. * Resets the Particle. This places the Particle at the given x/y world coordinates and then
  29767. * sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values.
  29768. * If the Particle has a physics body that too is reset.
  29769. *
  29770. * @method Phaser.Particle#reset
  29771. * @memberof Phaser.Particle
  29772. * @param {number} x - The x coordinate (in world space) to position the Particle at.
  29773. * @param {number} y - The y coordinate (in world space) to position the Particle at.
  29774. * @param {number} [health=1] - The health to give the Particle.
  29775. * @return (Phaser.Particle) This instance.
  29776. */
  29777. Phaser.Particle.prototype.reset = function(x, y, health) {
  29778. if (typeof health === 'undefined') { health = 1; }
  29779. this.world.setTo(x, y);
  29780. this.position.x = x;
  29781. this.position.y = y;
  29782. this.alive = true;
  29783. this.exists = true;
  29784. this.visible = true;
  29785. this.renderable = true;
  29786. this._outOfBoundsFired = false;
  29787. this.health = health;
  29788. if (this.body)
  29789. {
  29790. this.body.reset(x, y, false, false);
  29791. }
  29792. this._cache[4] = 1;
  29793. this.alpha = 1;
  29794. this.scale.set(1);
  29795. this.autoScale = false;
  29796. this.autoAlpha = false;
  29797. return this;
  29798. };
  29799. /**
  29800. * @author Richard Davey <rich@photonstorm.com>
  29801. * @copyright 2014 Photon Storm Ltd.
  29802. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  29803. */
  29804. /**
  29805. * The Canvas class handles everything related to creating the `canvas` DOM tag that Phaser will use, including styles, offset and aspect ratio.
  29806. *
  29807. * @class Phaser.Canvas
  29808. * @static
  29809. */
  29810. Phaser.Canvas = {
  29811. /**
  29812. * Creates a `canvas` DOM element. The element is not automatically added to the document.
  29813. *
  29814. * @method Phaser.Canvas.create
  29815. * @param {number} [width=256] - The width of the canvas element.
  29816. * @param {number} [height=256] - The height of the canvas element..
  29817. * @param {string} [id=''] - If given this will be set as the ID of the canvas element, otherwise no ID will be set.
  29818. * @param {boolean} [noCocoon=false] - DEPRECATED: This parameter is no longer used.
  29819. * @return {HTMLCanvasElement} The newly created canvas element.
  29820. */
  29821. create: function (width, height, id, noCocoon) {
  29822. if (typeof noCocoon === 'undefined') { noCocoon = false; }
  29823. width = width || 256;
  29824. height = height || 256;
  29825. var canvas = document.createElement('canvas');
  29826. if (typeof id === 'string' && id !== '')
  29827. {
  29828. canvas.id = id;
  29829. }
  29830. canvas.width = width;
  29831. canvas.height = height;
  29832. canvas.style.display = 'block';
  29833. return canvas;
  29834. },
  29835. /**
  29836. * Get the DOM offset values of any given element
  29837. * @method Phaser.Canvas.getOffset
  29838. * @param {HTMLElement} element - The targeted element that we want to retrieve the offset.
  29839. * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset.
  29840. * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties.
  29841. */
  29842. getOffset: function (element, point) {
  29843. point = point || new Phaser.Point();
  29844. var box = element.getBoundingClientRect();
  29845. var clientTop = element.clientTop || document.body.clientTop || 0;
  29846. var clientLeft = element.clientLeft || document.body.clientLeft || 0;
  29847. // Without this check Chrome is now throwing console warnings about strict vs. quirks :(
  29848. var scrollTop = 0;
  29849. var scrollLeft = 0;
  29850. if (document.compatMode === 'CSS1Compat')
  29851. {
  29852. scrollTop = window.pageYOffset || document.documentElement.scrollTop || element.scrollTop || 0;
  29853. scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || element.scrollLeft || 0;
  29854. }
  29855. else
  29856. {
  29857. scrollTop = window.pageYOffset || document.body.scrollTop || element.scrollTop || 0;
  29858. scrollLeft = window.pageXOffset || document.body.scrollLeft || element.scrollLeft || 0;
  29859. }
  29860. point.x = box.left + scrollLeft - clientLeft;
  29861. point.y = box.top + scrollTop - clientTop;
  29862. return point;
  29863. },
  29864. /**
  29865. * Returns the aspect ratio of the given canvas.
  29866. *
  29867. * @method Phaser.Canvas.getAspectRatio
  29868. * @param {HTMLCanvasElement} canvas - The canvas to get the aspect ratio from.
  29869. * @return {number} The ratio between canvas' width and height.
  29870. */
  29871. getAspectRatio: function (canvas) {
  29872. return canvas.width / canvas.height;
  29873. },
  29874. /**
  29875. * Sets the background color behind the canvas. This changes the canvas style property.
  29876. *
  29877. * @method Phaser.Canvas.setBackgroundColor
  29878. * @param {HTMLCanvasElement} canvas - The canvas to set the background color on.
  29879. * @param {string} [color] - The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color.
  29880. * @return {HTMLCanvasElement} Returns the source canvas.
  29881. */
  29882. setBackgroundColor: function (canvas, color) {
  29883. color = color || 'rgb(0,0,0)';
  29884. canvas.style.backgroundColor = color;
  29885. return canvas;
  29886. },
  29887. /**
  29888. * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions.
  29889. *
  29890. * @method Phaser.Canvas.setTouchAction
  29891. * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on.
  29892. * @param {String} [value] - The touch action to set. Defaults to 'none'.
  29893. * @return {HTMLCanvasElement} The source canvas.
  29894. */
  29895. setTouchAction: function (canvas, value) {
  29896. value = value || 'none';
  29897. canvas.style.msTouchAction = value;
  29898. canvas.style['ms-touch-action'] = value;
  29899. canvas.style['touch-action'] = value;
  29900. return canvas;
  29901. },
  29902. /**
  29903. * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions.
  29904. *
  29905. * @method Phaser.Canvas.setUserSelect
  29906. * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on.
  29907. * @param {String} [value] - The touch action to set. Defaults to 'none'.
  29908. * @return {HTMLCanvasElement} The source canvas.
  29909. */
  29910. setUserSelect: function (canvas, value) {
  29911. value = value || 'none';
  29912. canvas.style['-webkit-touch-callout'] = value;
  29913. canvas.style['-webkit-user-select'] = value;
  29914. canvas.style['-khtml-user-select'] = value;
  29915. canvas.style['-moz-user-select'] = value;
  29916. canvas.style['-ms-user-select'] = value;
  29917. canvas.style['user-select'] = value;
  29918. canvas.style['-webkit-tap-highlight-color'] = 'rgba(0, 0, 0, 0)';
  29919. return canvas;
  29920. },
  29921. /**
  29922. * Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent.
  29923. * If no parent is given it will be added as a child of the document.body.
  29924. *
  29925. * @method Phaser.Canvas.addToDOM
  29926. * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on.
  29927. * @param {string|HTMLElement} parent - The DOM element to add the canvas to.
  29928. * @param {boolean} [overflowHidden=true] - If set to true it will add the overflow='hidden' style to the parent DOM element.
  29929. * @return {HTMLCanvasElement} Returns the source canvas.
  29930. */
  29931. addToDOM: function (canvas, parent, overflowHidden) {
  29932. var target;
  29933. if (typeof overflowHidden === 'undefined') { overflowHidden = true; }
  29934. if (parent)
  29935. {
  29936. if (typeof parent === 'string')
  29937. {
  29938. // hopefully an element ID
  29939. target = document.getElementById(parent);
  29940. }
  29941. else if (typeof parent === 'object' && parent.nodeType === 1)
  29942. {
  29943. // quick test for a HTMLelement
  29944. target = parent;
  29945. }
  29946. }
  29947. // Fallback, covers an invalid ID and a non HTMLelement object
  29948. if (!target)
  29949. {
  29950. target = document.body;
  29951. }
  29952. if (overflowHidden && target.style)
  29953. {
  29954. target.style.overflow = 'hidden';
  29955. }
  29956. target.appendChild(canvas);
  29957. return canvas;
  29958. },
  29959. /**
  29960. * Sets the transform of the given canvas to the matrix values provided.
  29961. *
  29962. * @method Phaser.Canvas.setTransform
  29963. * @param {CanvasRenderingContext2D} context - The context to set the transform on.
  29964. * @param {number} translateX - The value to translate horizontally by.
  29965. * @param {number} translateY - The value to translate vertically by.
  29966. * @param {number} scaleX - The value to scale horizontally by.
  29967. * @param {number} scaleY - The value to scale vertically by.
  29968. * @param {number} skewX - The value to skew horizontaly by.
  29969. * @param {number} skewY - The value to skew vertically by.
  29970. * @return {CanvasRenderingContext2D} Returns the source context.
  29971. */
  29972. setTransform: function (context, translateX, translateY, scaleX, scaleY, skewX, skewY) {
  29973. context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY);
  29974. return context;
  29975. },
  29976. /**
  29977. * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing.
  29978. * By default browsers have image smoothing enabled, which isn't always what you visually want, especially
  29979. * when using pixel art in a game. Note that this sets the property on the context itself, so that any image
  29980. * drawn to the context will be affected. This sets the property across all current browsers but support is
  29981. * patchy on earlier browsers, especially on mobile.
  29982. *
  29983. * @method Phaser.Canvas.setSmoothingEnabled
  29984. * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on.
  29985. * @param {boolean} value - If set to true it will enable image smoothing, false will disable it.
  29986. * @return {CanvasRenderingContext2D} Returns the source context.
  29987. */
  29988. setSmoothingEnabled: function (context, value) {
  29989. context['imageSmoothingEnabled'] = value;
  29990. context['mozImageSmoothingEnabled'] = value;
  29991. context['oImageSmoothingEnabled'] = value;
  29992. context['webkitImageSmoothingEnabled'] = value;
  29993. context['msImageSmoothingEnabled'] = value;
  29994. return context;
  29995. },
  29996. /**
  29997. * Sets the CSS image-rendering property on the given canvas to be 'crisp' (aka 'optimize contrast on webkit').
  29998. * Note that if this doesn't given the desired result then see the setSmoothingEnabled.
  29999. *
  30000. * @method Phaser.Canvas.setImageRenderingCrisp
  30001. * @param {HTMLCanvasElement} canvas - The canvas to set image-rendering crisp on.
  30002. * @return {HTMLCanvasElement} Returns the source canvas.
  30003. */
  30004. setImageRenderingCrisp: function (canvas) {
  30005. canvas.style['image-rendering'] = 'optimizeSpeed';
  30006. canvas.style['image-rendering'] = 'crisp-edges';
  30007. canvas.style['image-rendering'] = '-moz-crisp-edges';
  30008. canvas.style['image-rendering'] = '-webkit-optimize-contrast';
  30009. canvas.style['image-rendering'] = 'optimize-contrast';
  30010. canvas.style.msInterpolationMode = 'nearest-neighbor';
  30011. return canvas;
  30012. },
  30013. /**
  30014. * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto').
  30015. * Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method.
  30016. *
  30017. * @method Phaser.Canvas.setImageRenderingBicubic
  30018. * @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on.
  30019. * @return {HTMLCanvasElement} Returns the source canvas.
  30020. */
  30021. setImageRenderingBicubic: function (canvas) {
  30022. canvas.style['image-rendering'] = 'auto';
  30023. canvas.style.msInterpolationMode = 'bicubic';
  30024. return canvas;
  30025. }
  30026. };
  30027. /**
  30028. * @author Richard Davey <rich@photonstorm.com>
  30029. * @copyright 2014 Photon Storm Ltd.
  30030. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  30031. */
  30032. /**
  30033. * Detects device support capabilities. Using some elements from System.js by MrDoob and Modernizr
  30034. *
  30035. * @class Phaser.Device
  30036. * @constructor
  30037. */
  30038. Phaser.Device = function (game) {
  30039. /**
  30040. * @property {Phaser.Game} game - A reference to the currently running game.
  30041. */
  30042. this.game = game;
  30043. // Operating System
  30044. /**
  30045. * @property {boolean} desktop - Is running desktop?
  30046. * @default
  30047. */
  30048. this.desktop = false;
  30049. /**
  30050. * @property {boolean} iOS - Is running on iOS?
  30051. * @default
  30052. */
  30053. this.iOS = false;
  30054. /**
  30055. * @property {boolean} cocoonJS - Is the game running under CocoonJS?
  30056. * @default
  30057. */
  30058. this.cocoonJS = false;
  30059. /**
  30060. * @property {boolean} ejecta - Is the game running under Ejecta?
  30061. * @default
  30062. */
  30063. this.ejecta = false;
  30064. /**
  30065. * @property {boolean} crosswalk - Is the game running under the Intel Crosswalk XDK?
  30066. * @default
  30067. */
  30068. this.crosswalk = false;
  30069. /**
  30070. * @property {boolean} android - Is running on android?
  30071. * @default
  30072. */
  30073. this.android = false;
  30074. /**
  30075. * @property {boolean} chromeOS - Is running on chromeOS?
  30076. * @default
  30077. */
  30078. this.chromeOS = false;
  30079. /**
  30080. * @property {boolean} linux - Is running on linux?
  30081. * @default
  30082. */
  30083. this.linux = false;
  30084. /**
  30085. * @property {boolean} macOS - Is running on macOS?
  30086. * @default
  30087. */
  30088. this.macOS = false;
  30089. /**
  30090. * @property {boolean} windows - Is running on windows?
  30091. * @default
  30092. */
  30093. this.windows = false;
  30094. /**
  30095. * @property {boolean} windowsPhone - Is running on a Windows Phone?
  30096. * @default
  30097. */
  30098. this.windowsPhone = false;
  30099. // Features
  30100. /**
  30101. * @property {boolean} canvas - Is canvas available?
  30102. * @default
  30103. */
  30104. this.canvas = false;
  30105. /**
  30106. * @property {boolean} file - Is file available?
  30107. * @default
  30108. */
  30109. this.file = false;
  30110. /**
  30111. * @property {boolean} fileSystem - Is fileSystem available?
  30112. * @default
  30113. */
  30114. this.fileSystem = false;
  30115. /**
  30116. * @property {boolean} localStorage - Is localStorage available?
  30117. * @default
  30118. */
  30119. this.localStorage = false;
  30120. /**
  30121. * @property {boolean} webGL - Is webGL available?
  30122. * @default
  30123. */
  30124. this.webGL = false;
  30125. /**
  30126. * @property {boolean} worker - Is worker available?
  30127. * @default
  30128. */
  30129. this.worker = false;
  30130. /**
  30131. * @property {boolean} touch - Is touch available?
  30132. * @default
  30133. */
  30134. this.touch = false;
  30135. /**
  30136. * @property {boolean} mspointer - Is mspointer available?
  30137. * @default
  30138. */
  30139. this.mspointer = false;
  30140. /**
  30141. * @property {boolean} css3D - Is css3D available?
  30142. * @default
  30143. */
  30144. this.css3D = false;
  30145. /**
  30146. * @property {boolean} pointerLock - Is Pointer Lock available?
  30147. * @default
  30148. */
  30149. this.pointerLock = false;
  30150. /**
  30151. * @property {boolean} typedArray - Does the browser support TypedArrays?
  30152. * @default
  30153. */
  30154. this.typedArray = false;
  30155. /**
  30156. * @property {boolean} vibration - Does the device support the Vibration API?
  30157. * @default
  30158. */
  30159. this.vibration = false;
  30160. /**
  30161. * @property {boolean} getUserMedia - Does the device support the getUserMedia API?
  30162. * @default
  30163. */
  30164. this.getUserMedia = false;
  30165. /**
  30166. * @property {boolean} quirksMode - Is the browser running in strict mode (false) or quirks mode? (true)
  30167. * @default
  30168. */
  30169. this.quirksMode = false;
  30170. // Browser
  30171. /**
  30172. * @property {boolean} arora - Set to true if running in Arora.
  30173. * @default
  30174. */
  30175. this.arora = false;
  30176. /**
  30177. * @property {boolean} chrome - Set to true if running in Chrome.
  30178. * @default
  30179. */
  30180. this.chrome = false;
  30181. /**
  30182. * @property {boolean} epiphany - Set to true if running in Epiphany.
  30183. * @default
  30184. */
  30185. this.epiphany = false;
  30186. /**
  30187. * @property {boolean} firefox - Set to true if running in Firefox.
  30188. * @default
  30189. */
  30190. this.firefox = false;
  30191. /**
  30192. * @property {boolean} ie - Set to true if running in Internet Explorer.
  30193. * @default
  30194. */
  30195. this.ie = false;
  30196. /**
  30197. * @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.
  30198. * @default
  30199. */
  30200. this.ieVersion = 0;
  30201. /**
  30202. * @property {boolean} trident - Set to true if running a Trident version of Internet Explorer (IE11+)
  30203. * @default
  30204. */
  30205. this.trident = false;
  30206. /**
  30207. * @property {number} tridentVersion - If running in Internet Explorer 11 this will contain the major version number. See http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx
  30208. * @default
  30209. */
  30210. this.tridentVersion = 0;
  30211. /**
  30212. * @property {boolean} mobileSafari - Set to true if running in Mobile Safari.
  30213. * @default
  30214. */
  30215. this.mobileSafari = false;
  30216. /**
  30217. * @property {boolean} midori - Set to true if running in Midori.
  30218. * @default
  30219. */
  30220. this.midori = false;
  30221. /**
  30222. * @property {boolean} opera - Set to true if running in Opera.
  30223. * @default
  30224. */
  30225. this.opera = false;
  30226. /**
  30227. * @property {boolean} safari - Set to true if running in Safari.
  30228. * @default
  30229. */
  30230. this.safari = false;
  30231. /**
  30232. * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView
  30233. * @default
  30234. */
  30235. this.webApp = false;
  30236. /**
  30237. * @property {boolean} silk - Set to true if running in the Silk browser (as used on the Amazon Kindle)
  30238. * @default
  30239. */
  30240. this.silk = false;
  30241. // Audio
  30242. /**
  30243. * @property {boolean} audioData - Are Audio tags available?
  30244. * @default
  30245. */
  30246. this.audioData = false;
  30247. /**
  30248. * @property {boolean} webAudio - Is the WebAudio API available?
  30249. * @default
  30250. */
  30251. this.webAudio = false;
  30252. /**
  30253. * @property {boolean} ogg - Can this device play ogg files?
  30254. * @default
  30255. */
  30256. this.ogg = false;
  30257. /**
  30258. * @property {boolean} opus - Can this device play opus files?
  30259. * @default
  30260. */
  30261. this.opus = false;
  30262. /**
  30263. * @property {boolean} mp3 - Can this device play mp3 files?
  30264. * @default
  30265. */
  30266. this.mp3 = false;
  30267. /**
  30268. * @property {boolean} wav - Can this device play wav files?
  30269. * @default
  30270. */
  30271. this.wav = false;
  30272. /**
  30273. * Can this device play m4a files?
  30274. * @property {boolean} m4a - True if this device can play m4a files.
  30275. * @default
  30276. */
  30277. this.m4a = false;
  30278. /**
  30279. * @property {boolean} webm - Can this device play webm files?
  30280. * @default
  30281. */
  30282. this.webm = false;
  30283. // Device
  30284. /**
  30285. * @property {boolean} iPhone - Is running on iPhone?
  30286. * @default
  30287. */
  30288. this.iPhone = false;
  30289. /**
  30290. * @property {boolean} iPhone4 - Is running on iPhone4?
  30291. * @default
  30292. */
  30293. this.iPhone4 = false;
  30294. /**
  30295. * @property {boolean} iPad - Is running on iPad?
  30296. * @default
  30297. */
  30298. this.iPad = false;
  30299. /**
  30300. * @property {number} pixelRatio - PixelRatio of the host device?
  30301. * @default
  30302. */
  30303. this.pixelRatio = 0;
  30304. /**
  30305. * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays)
  30306. * @default
  30307. */
  30308. this.littleEndian = false;
  30309. /**
  30310. * @property {boolean} support32bit - Does the device context support 32bit pixel manipulation using array buffer views?
  30311. * @default
  30312. */
  30313. this.support32bit = false;
  30314. /**
  30315. * @property {boolean} fullscreen - Does the browser support the Full Screen API?
  30316. * @default
  30317. */
  30318. this.fullscreen = false;
  30319. /**
  30320. * @property {string} requestFullscreen - If the browser supports the Full Screen API this holds the call you need to use to activate it.
  30321. * @default
  30322. */
  30323. this.requestFullscreen = '';
  30324. /**
  30325. * @property {string} cancelFullscreen - If the browser supports the Full Screen API this holds the call you need to use to cancel it.
  30326. * @default
  30327. */
  30328. this.cancelFullscreen = '';
  30329. /**
  30330. * @property {boolean} fullscreenKeyboard - Does the browser support access to the Keyboard during Full Screen mode?
  30331. * @default
  30332. */
  30333. this.fullscreenKeyboard = false;
  30334. // Run the checks
  30335. this._checkOS();
  30336. this._checkAudio();
  30337. this._checkBrowser();
  30338. this._checkCSS3D();
  30339. this._checkDevice();
  30340. this._checkFeatures();
  30341. };
  30342. Phaser.Device.LITTLE_ENDIAN = false;
  30343. Phaser.Device.prototype = {
  30344. /**
  30345. * Check which OS is game running on.
  30346. * @method Phaser.Device#_checkOS
  30347. * @private
  30348. */
  30349. _checkOS: function () {
  30350. var ua = navigator.userAgent;
  30351. if (/Android/.test(ua))
  30352. {
  30353. this.android = true;
  30354. }
  30355. else if (/CrOS/.test(ua))
  30356. {
  30357. this.chromeOS = true;
  30358. }
  30359. else if (/iP[ao]d|iPhone/i.test(ua))
  30360. {
  30361. this.iOS = true;
  30362. }
  30363. else if (/Linux/.test(ua))
  30364. {
  30365. this.linux = true;
  30366. }
  30367. else if (/Mac OS/.test(ua))
  30368. {
  30369. this.macOS = true;
  30370. }
  30371. else if (/Windows/.test(ua))
  30372. {
  30373. this.windows = true;
  30374. if (/Windows Phone/i.test(ua))
  30375. {
  30376. this.windowsPhone = true;
  30377. }
  30378. }
  30379. if (this.windows || this.macOS || (this.linux && this.silk === false))
  30380. {
  30381. this.desktop = true;
  30382. }
  30383. // Windows Phone / Table reset
  30384. if (this.windowsPhone || ((/Windows NT/i.test(ua)) && (/Touch/i.test(ua))))
  30385. {
  30386. this.desktop = false;
  30387. }
  30388. },
  30389. /**
  30390. * Check HTML5 features of the host environment.
  30391. * @method Phaser.Device#_checkFeatures
  30392. * @private
  30393. */
  30394. _checkFeatures: function () {
  30395. this.canvas = !!window['CanvasRenderingContext2D'] || this.cocoonJS;
  30396. try {
  30397. this.localStorage = !!localStorage.getItem;
  30398. } catch (error) {
  30399. this.localStorage = false;
  30400. }
  30401. this.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob'];
  30402. this.fileSystem = !!window['requestFileSystem'];
  30403. this.webGL = ( function () { try { var canvas = document.createElement( 'canvas' ); return !! window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ); } catch( e ) { return false; } } )();
  30404. if (this.webGL === null || this.webGL === false)
  30405. {
  30406. this.webGL = false;
  30407. }
  30408. else
  30409. {
  30410. this.webGL = true;
  30411. }
  30412. this.worker = !!window['Worker'];
  30413. if ('ontouchstart' in document.documentElement || (window.navigator.maxTouchPoints && window.navigator.maxTouchPoints > 1))
  30414. {
  30415. this.touch = true;
  30416. }
  30417. if (window.navigator.msPointerEnabled || window.navigator.pointerEnabled)
  30418. {
  30419. this.mspointer = true;
  30420. }
  30421. this.pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document;
  30422. this.quirksMode = (document.compatMode === 'CSS1Compat') ? false : true;
  30423. this.getUserMedia = !!(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
  30424. },
  30425. /**
  30426. * Checks for support of the Full Screen API.
  30427. *
  30428. * @method Phaser.Device#checkFullScreenSupport
  30429. */
  30430. checkFullScreenSupport: function () {
  30431. var fs = [
  30432. 'requestFullscreen',
  30433. 'requestFullScreen',
  30434. 'webkitRequestFullscreen',
  30435. 'webkitRequestFullScreen',
  30436. 'msRequestFullscreen',
  30437. 'msRequestFullScreen',
  30438. 'mozRequestFullScreen',
  30439. 'mozRequestFullscreen'
  30440. ];
  30441. for (var i = 0; i < fs.length; i++)
  30442. {
  30443. if (this.game.canvas[fs[i]])
  30444. // if (document[fs[i]])
  30445. {
  30446. this.fullscreen = true;
  30447. this.requestFullscreen = fs[i];
  30448. break;
  30449. }
  30450. }
  30451. var cfs = [
  30452. 'cancelFullScreen',
  30453. 'exitFullscreen',
  30454. 'webkitCancelFullScreen',
  30455. 'webkitExitFullscreen',
  30456. 'msCancelFullScreen',
  30457. 'msExitFullscreen',
  30458. 'mozCancelFullScreen',
  30459. 'mozExitFullscreen'
  30460. ];
  30461. if (this.fullscreen)
  30462. {
  30463. for (var i = 0; i < cfs.length; i++)
  30464. {
  30465. if (document[cfs[i]])
  30466. {
  30467. this.cancelFullscreen = cfs[i];
  30468. break;
  30469. }
  30470. }
  30471. }
  30472. // Keyboard Input?
  30473. if (window['Element'] && Element['ALLOW_KEYBOARD_INPUT'])
  30474. {
  30475. this.fullscreenKeyboard = true;
  30476. }
  30477. },
  30478. /**
  30479. * Check what browser is game running in.
  30480. * @method Phaser.Device#_checkBrowser
  30481. * @private
  30482. */
  30483. _checkBrowser: function () {
  30484. var ua = navigator.userAgent;
  30485. if (/Arora/.test(ua))
  30486. {
  30487. this.arora = true;
  30488. }
  30489. else if (/Chrome/.test(ua))
  30490. {
  30491. this.chrome = true;
  30492. }
  30493. else if (/Epiphany/.test(ua))
  30494. {
  30495. this.epiphany = true;
  30496. }
  30497. else if (/Firefox/.test(ua))
  30498. {
  30499. this.firefox = true;
  30500. }
  30501. else if (/AppleWebKit/.test(ua) && this.iOS)
  30502. {
  30503. this.mobileSafari = true;
  30504. }
  30505. else if (/MSIE (\d+\.\d+);/.test(ua))
  30506. {
  30507. this.ie = true;
  30508. this.ieVersion = parseInt(RegExp.$1, 10);
  30509. }
  30510. else if (/Midori/.test(ua))
  30511. {
  30512. this.midori = true;
  30513. }
  30514. else if (/Opera/.test(ua))
  30515. {
  30516. this.opera = true;
  30517. }
  30518. else if (/Safari/.test(ua))
  30519. {
  30520. this.safari = true;
  30521. }
  30522. else if (/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(ua))
  30523. {
  30524. this.ie = true;
  30525. this.trident = true;
  30526. this.tridentVersion = parseInt(RegExp.$1, 10);
  30527. this.ieVersion = parseInt(RegExp.$3, 10);
  30528. }
  30529. //Silk gets its own if clause because its ua also contains 'Safari'
  30530. if (/Silk/.test(ua))
  30531. {
  30532. this.silk = true;
  30533. }
  30534. // WebApp mode in iOS
  30535. if (navigator['standalone'])
  30536. {
  30537. this.webApp = true;
  30538. }
  30539. if (navigator['isCocoonJS'])
  30540. {
  30541. this.cocoonJS = true;
  30542. }
  30543. if (typeof window.ejecta !== "undefined")
  30544. {
  30545. this.ejecta = true;
  30546. }
  30547. if (/Crosswalk/.test(ua))
  30548. {
  30549. this.crosswalk = true;
  30550. }
  30551. },
  30552. /**
  30553. * Check audio support.
  30554. * @method Phaser.Device#_checkAudio
  30555. * @private
  30556. */
  30557. _checkAudio: function () {
  30558. this.audioData = !!(window['Audio']);
  30559. this.webAudio = !!(window['webkitAudioContext'] || window['AudioContext']);
  30560. var audioElement = document.createElement('audio');
  30561. var result = false;
  30562. try {
  30563. if (result = !!audioElement.canPlayType) {
  30564. if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  30565. this.ogg = true;
  30566. }
  30567. if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, '')) {
  30568. this.opus = true;
  30569. }
  30570. if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, '')) {
  30571. this.mp3 = true;
  30572. }
  30573. // Mimetypes accepted:
  30574. // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
  30575. // bit.ly/iphoneoscodecs
  30576. if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')) {
  30577. this.wav = true;
  30578. }
  30579. if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, '')) {
  30580. this.m4a = true;
  30581. }
  30582. if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')) {
  30583. this.webm = true;
  30584. }
  30585. }
  30586. } catch (e) {
  30587. }
  30588. },
  30589. /**
  30590. * Check PixelRatio, iOS device, Vibration API, ArrayBuffers and endianess.
  30591. * @method Phaser.Device#_checkDevice
  30592. * @private
  30593. */
  30594. _checkDevice: function () {
  30595. this.pixelRatio = window['devicePixelRatio'] || 1;
  30596. this.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') != -1;
  30597. this.iPhone4 = (this.pixelRatio == 2 && this.iPhone);
  30598. this.iPad = navigator.userAgent.toLowerCase().indexOf('ipad') != -1;
  30599. if (typeof Int8Array !== 'undefined')
  30600. {
  30601. this.typedArray = true;
  30602. }
  30603. else
  30604. {
  30605. this.typedArray = false;
  30606. }
  30607. if (typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined' && typeof Uint32Array !== 'undefined')
  30608. {
  30609. this.littleEndian = this._checkIsLittleEndian();
  30610. Phaser.Device.LITTLE_ENDIAN = this.littleEndian;
  30611. }
  30612. this.support32bit = (typeof ArrayBuffer !== "undefined" && typeof Uint8ClampedArray !== "undefined" && typeof Int32Array !== "undefined" && this.littleEndian !== null && this._checkIsUint8ClampedImageData());
  30613. navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate;
  30614. if (navigator.vibrate)
  30615. {
  30616. this.vibration = true;
  30617. }
  30618. },
  30619. /**
  30620. * Check Little or Big Endian system.
  30621. * @author Matt DesLauriers (@mattdesl)
  30622. * @method Phaser.Device#_checkIsLittleEndian
  30623. * @private
  30624. */
  30625. _checkIsLittleEndian: function () {
  30626. var a = new ArrayBuffer(4);
  30627. var b = new Uint8Array(a);
  30628. var c = new Uint32Array(a);
  30629. b[0] = 0xa1;
  30630. b[1] = 0xb2;
  30631. b[2] = 0xc3;
  30632. b[3] = 0xd4;
  30633. if (c[0] == 0xd4c3b2a1)
  30634. {
  30635. return true;
  30636. }
  30637. if (c[0] == 0xa1b2c3d4)
  30638. {
  30639. return false;
  30640. }
  30641. else
  30642. {
  30643. // Could not determine endianness
  30644. return null;
  30645. }
  30646. },
  30647. /**
  30648. * Test to see if ImageData uses CanvasPixelArray or Uint8ClampedArray.
  30649. * @author Matt DesLauriers (@mattdesl)
  30650. * @method Phaser.Device#_checkIsUint8ClampedImageData
  30651. * @private
  30652. */
  30653. _checkIsUint8ClampedImageData: function () {
  30654. if (typeof Uint8ClampedArray === "undefined")
  30655. {
  30656. return false;
  30657. }
  30658. var elem = document.createElement('canvas');
  30659. var ctx = elem.getContext('2d');
  30660. if (!ctx)
  30661. {
  30662. return false;
  30663. }
  30664. var image = ctx.createImageData(1, 1);
  30665. return image.data instanceof Uint8ClampedArray;
  30666. },
  30667. /**
  30668. * Check whether the host environment support 3D CSS.
  30669. * @method Phaser.Device#_checkCSS3D
  30670. * @private
  30671. */
  30672. _checkCSS3D: function () {
  30673. var el = document.createElement('p');
  30674. var has3d;
  30675. var transforms = {
  30676. 'webkitTransform': '-webkit-transform',
  30677. 'OTransform': '-o-transform',
  30678. 'msTransform': '-ms-transform',
  30679. 'MozTransform': '-moz-transform',
  30680. 'transform': 'transform'
  30681. };
  30682. // Add it to the body to get the computed style.
  30683. document.body.insertBefore(el, null);
  30684. for (var t in transforms)
  30685. {
  30686. if (el.style[t] !== undefined)
  30687. {
  30688. el.style[t] = "translate3d(1px,1px,1px)";
  30689. has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
  30690. }
  30691. }
  30692. document.body.removeChild(el);
  30693. this.css3D = (has3d !== undefined && has3d.length > 0 && has3d !== "none");
  30694. },
  30695. /**
  30696. * Check whether the host environment can play audio.
  30697. * @method Phaser.Device#canPlayAudio
  30698. * @param {string} type - One of 'mp3, 'ogg', 'm4a', 'wav', 'webm'.
  30699. * @return {boolean} True if the given file type is supported by the browser, otherwise false.
  30700. */
  30701. canPlayAudio: function (type) {
  30702. if (type == 'mp3' && this.mp3)
  30703. {
  30704. return true;
  30705. }
  30706. else if (type == 'ogg' && (this.ogg || this.opus))
  30707. {
  30708. return true;
  30709. }
  30710. else if (type == 'm4a' && this.m4a)
  30711. {
  30712. return true;
  30713. }
  30714. else if (type == 'wav' && this.wav)
  30715. {
  30716. return true;
  30717. }
  30718. else if (type == 'webm' && this.webm)
  30719. {
  30720. return true;
  30721. }
  30722. return false;
  30723. },
  30724. /**
  30725. * Check whether the console is open.
  30726. * Note that this only works in Firefox with Firebug and earlier versions of Chrome.
  30727. * It used to work in Chrome, but then they removed the ability: http://src.chromium.org/viewvc/blink?view=revision&revision=151136
  30728. *
  30729. * @method Phaser.Device#isConsoleOpen
  30730. * @return {boolean} True if the browser dev console is open.
  30731. */
  30732. isConsoleOpen: function () {
  30733. if (window.console && window.console['firebug'])
  30734. {
  30735. return true;
  30736. }
  30737. if (window.console)
  30738. {
  30739. console.profile();
  30740. console.profileEnd();
  30741. if (console.clear)
  30742. {
  30743. console.clear();
  30744. }
  30745. if (console['profiles'])
  30746. {
  30747. return console['profiles'].length > 0;
  30748. }
  30749. }
  30750. return false;
  30751. }
  30752. };
  30753. Phaser.Device.prototype.constructor = Phaser.Device;
  30754. /**
  30755. * @author Richard Davey <rich@photonstorm.com>
  30756. * @copyright 2014 Photon Storm Ltd.
  30757. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  30758. */
  30759. /**
  30760. * Abstracts away the use of RAF or setTimeOut for the core game update loop.
  30761. *
  30762. * @class Phaser.RequestAnimationFrame
  30763. * @constructor
  30764. * @param {Phaser.Game} game - A reference to the currently running game.
  30765. * @param {boolean} [forceSetTimeOut=false] - Tell Phaser to use setTimeOut even if raf is available.
  30766. */
  30767. Phaser.RequestAnimationFrame = function(game, forceSetTimeOut) {
  30768. if (typeof forceSetTimeOut === 'undefined') { forceSetTimeOut = false; }
  30769. /**
  30770. * @property {Phaser.Game} game - The currently running game.
  30771. */
  30772. this.game = game;
  30773. /**
  30774. * @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false.
  30775. * @default
  30776. */
  30777. this.isRunning = false;
  30778. /**
  30779. * @property {boolean} forceSetTimeOut - Tell Phaser to use setTimeOut even if raf is available.
  30780. */
  30781. this.forceSetTimeOut = forceSetTimeOut;
  30782. var vendors = [
  30783. 'ms',
  30784. 'moz',
  30785. 'webkit',
  30786. 'o'
  30787. ];
  30788. for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++)
  30789. {
  30790. window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
  30791. window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'];
  30792. }
  30793. /**
  30794. * @property {boolean} _isSetTimeOut - true if the browser is using setTimeout instead of raf.
  30795. * @private
  30796. */
  30797. this._isSetTimeOut = false;
  30798. /**
  30799. * @property {function} _onLoop - The function called by the update.
  30800. * @private
  30801. */
  30802. this._onLoop = null;
  30803. /**
  30804. * @property {number} _timeOutID - The callback ID used when calling cancel.
  30805. * @private
  30806. */
  30807. this._timeOutID = null;
  30808. };
  30809. Phaser.RequestAnimationFrame.prototype = {
  30810. /**
  30811. * Starts the requestAnimationFrame running or setTimeout if unavailable in browser
  30812. * @method Phaser.RequestAnimationFrame#start
  30813. */
  30814. start: function () {
  30815. this.isRunning = true;
  30816. var _this = this;
  30817. if (!window.requestAnimationFrame || this.forceSetTimeOut)
  30818. {
  30819. this._isSetTimeOut = true;
  30820. this._onLoop = function () {
  30821. return _this.updateSetTimeout();
  30822. };
  30823. this._timeOutID = window.setTimeout(this._onLoop, 0);
  30824. }
  30825. else
  30826. {
  30827. this._isSetTimeOut = false;
  30828. this._onLoop = function (time) {
  30829. return _this.updateRAF(time);
  30830. };
  30831. this._timeOutID = window.requestAnimationFrame(this._onLoop);
  30832. }
  30833. },
  30834. /**
  30835. * The update method for the requestAnimationFrame
  30836. * @method Phaser.RequestAnimationFrame#updateRAF
  30837. */
  30838. updateRAF: function () {
  30839. this.game.update(Date.now());
  30840. // fixed can't stop requestAnimationFrame in iOS by paicha
  30841. if (this.isRunning) {
  30842. this._timeOutID = window.requestAnimationFrame(this._onLoop);
  30843. }
  30844. },
  30845. /**
  30846. * The update method for the setTimeout.
  30847. * @method Phaser.RequestAnimationFrame#updateSetTimeout
  30848. */
  30849. updateSetTimeout: function () {
  30850. this.game.update(Date.now());
  30851. this._timeOutID = window.setTimeout(this._onLoop, this.game.time.timeToCall);
  30852. },
  30853. /**
  30854. * Stops the requestAnimationFrame from running.
  30855. * @method Phaser.RequestAnimationFrame#stop
  30856. */
  30857. stop: function () {
  30858. if (this._isSetTimeOut)
  30859. {
  30860. clearTimeout(this._timeOutID);
  30861. }
  30862. else
  30863. {
  30864. window.cancelAnimationFrame(this._timeOutID);
  30865. }
  30866. this.isRunning = false;
  30867. },
  30868. /**
  30869. * Is the browser using setTimeout?
  30870. * @method Phaser.RequestAnimationFrame#isSetTimeOut
  30871. * @return {boolean}
  30872. */
  30873. isSetTimeOut: function () {
  30874. return this._isSetTimeOut;
  30875. },
  30876. /**
  30877. * Is the browser using requestAnimationFrame?
  30878. * @method Phaser.RequestAnimationFrame#isRAF
  30879. * @return {boolean}
  30880. */
  30881. isRAF: function () {
  30882. return (this._isSetTimeOut === false);
  30883. }
  30884. };
  30885. Phaser.RequestAnimationFrame.prototype.constructor = Phaser.RequestAnimationFrame;
  30886. /**
  30887. * @author Richard Davey <rich@photonstorm.com>
  30888. * @copyright 2014 Photon Storm Ltd.
  30889. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  30890. */
  30891. /**
  30892. * A collection of mathematical methods.
  30893. *
  30894. * @class Phaser.Math
  30895. */
  30896. Phaser.Math = {
  30897. /**
  30898. * = 2 &pi;
  30899. * @method Phaser.Math#PI2
  30900. */
  30901. PI2: Math.PI * 2,
  30902. /**
  30903. * Two number are fuzzyEqual if their difference is less than &epsilon;.
  30904. * @method Phaser.Math#fuzzyEqual
  30905. * @param {number} a
  30906. * @param {number} b
  30907. * @param {number} epsilon
  30908. * @return {boolean} True if |a-b|<&epsilon;
  30909. */
  30910. fuzzyEqual: function (a, b, epsilon) {
  30911. if (typeof epsilon === "undefined") { epsilon = 0.0001; }
  30912. return Math.abs(a - b) < epsilon;
  30913. },
  30914. /**
  30915. * a is fuzzyLessThan b if it is less than b + &epsilon;.
  30916. * @method Phaser.Math#fuzzyLessThan
  30917. * @param {number} a
  30918. * @param {number} b
  30919. * @param {number} epsilon
  30920. * @return {boolean} True if a<b+&epsilon;
  30921. */
  30922. fuzzyLessThan: function (a, b, epsilon) {
  30923. if (typeof epsilon === "undefined") { epsilon = 0.0001; }
  30924. return a < b + epsilon;
  30925. },
  30926. /**
  30927. * a is fuzzyGreaterThan b if it is more than b - &epsilon;.
  30928. * @method Phaser.Math#fuzzyGreaterThan
  30929. * @param {number} a
  30930. * @param {number} b
  30931. * @param {number} epsilon
  30932. * @return {boolean} True if a>b+&epsilon;
  30933. */
  30934. fuzzyGreaterThan: function (a, b, epsilon) {
  30935. if (typeof epsilon === "undefined") { epsilon = 0.0001; }
  30936. return a > b - epsilon;
  30937. },
  30938. /**
  30939. * @method Phaser.Math#fuzzyCeil
  30940. * @param {number} val
  30941. * @param {number} epsilon
  30942. * @return {boolean} ceiling(val-&epsilon;)
  30943. */
  30944. fuzzyCeil: function (val, epsilon) {
  30945. if (typeof epsilon === "undefined") { epsilon = 0.0001; }
  30946. return Math.ceil(val - epsilon);
  30947. },
  30948. /**
  30949. * @method Phaser.Math#fuzzyFloor
  30950. * @param {number} val
  30951. * @param {number} epsilon
  30952. * @return {boolean} floor(val-&epsilon;)
  30953. */
  30954. fuzzyFloor: function (val, epsilon) {
  30955. if (typeof epsilon === "undefined") { epsilon = 0.0001; }
  30956. return Math.floor(val + epsilon);
  30957. },
  30958. /**
  30959. * Averages all values passed to the function and returns the result. You can pass as many parameters as you like.
  30960. * @method Phaser.Math#average
  30961. * @return {number} The average of all given values.
  30962. */
  30963. average: function () {
  30964. var args = [];
  30965. for (var _i = 0; _i < (arguments.length - 0); _i++) {
  30966. args[_i] = arguments[_i + 0];
  30967. }
  30968. var avg = 0;
  30969. for (var i = 0; i < args.length; i++) {
  30970. avg += args[i];
  30971. }
  30972. return avg / args.length;
  30973. },
  30974. /**
  30975. * @method Phaser.Math#truncate
  30976. * @param {number} n
  30977. * @return {number}
  30978. */
  30979. truncate: function (n) {
  30980. return (n > 0) ? Math.floor(n) : Math.ceil(n);
  30981. },
  30982. /**
  30983. * @method Phaser.Math#shear
  30984. * @param {number} n
  30985. * @return {number} n mod 1
  30986. */
  30987. shear: function (n) {
  30988. return n % 1;
  30989. },
  30990. /**
  30991. * Snap a value to nearest grid slice, using rounding.
  30992. *
  30993. * 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.
  30994. *
  30995. * @method Phaser.Math#snapTo
  30996. * @param {number} input - The value to snap.
  30997. * @param {number} gap - The interval gap of the grid.
  30998. * @param {number} [start] - Optional starting offset for gap.
  30999. * @return {number}
  31000. */
  31001. snapTo: function (input, gap, start) {
  31002. if (typeof start === "undefined") { start = 0; }
  31003. if (gap === 0) {
  31004. return input;
  31005. }
  31006. input -= start;
  31007. input = gap * Math.round(input / gap);
  31008. return start + input;
  31009. },
  31010. /**
  31011. * Snap a value to nearest grid slice, using floor.
  31012. *
  31013. * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. As will 14 snap to 10... but 16 will snap to 15
  31014. *
  31015. * @method Phaser.Math#snapToFloor
  31016. * @param {number} input - The value to snap.
  31017. * @param {number} gap - The interval gap of the grid.
  31018. * @param {number} [start] - Optional starting offset for gap.
  31019. * @return {number}
  31020. */
  31021. snapToFloor: function (input, gap, start) {
  31022. if (typeof start === "undefined") { start = 0; }
  31023. if (gap === 0) {
  31024. return input;
  31025. }
  31026. input -= start;
  31027. input = gap * Math.floor(input / gap);
  31028. return start + input;
  31029. },
  31030. /**
  31031. * Snap a value to nearest grid slice, using ceil.
  31032. *
  31033. * Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. As will 14 will snap to 15... but 16 will snap to 20.
  31034. *
  31035. * @method Phaser.Math#snapToCeil
  31036. * @param {number} input - The value to snap.
  31037. * @param {number} gap - The interval gap of the grid.
  31038. * @param {number} [start] - Optional starting offset for gap.
  31039. * @return {number}
  31040. */
  31041. snapToCeil: function (input, gap, start) {
  31042. if (typeof start === "undefined") { start = 0; }
  31043. if (gap === 0) {
  31044. return input;
  31045. }
  31046. input -= start;
  31047. input = gap * Math.ceil(input / gap);
  31048. return start + input;
  31049. },
  31050. /**
  31051. * Snaps a value to the nearest value in an array.
  31052. * @method Phaser.Math#snapToInArray
  31053. * @param {number} input
  31054. * @param {array} arr
  31055. * @param {boolean} sort - True if the array needs to be sorted.
  31056. * @return {number}
  31057. */
  31058. snapToInArray: function (input, arr, sort) {
  31059. if (typeof sort === "undefined") { sort = true; }
  31060. if (sort) {
  31061. arr.sort();
  31062. }
  31063. if (input < arr[0]) {
  31064. return arr[0];
  31065. }
  31066. var i = 1;
  31067. while (arr[i] < input) {
  31068. i++;
  31069. }
  31070. var low = arr[i - 1];
  31071. var high = (i < arr.length) ? arr[i] : Number.POSITIVE_INFINITY;
  31072. return ((high - input) <= (input - low)) ? high : low;
  31073. },
  31074. /**
  31075. * Round to some place comparative to a 'base', default is 10 for decimal place.
  31076. *
  31077. * 'place' is represented by the power applied to 'base' to get that place
  31078. * e.g.
  31079. * 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011
  31080. *
  31081. * roundTo(2000/7,3) === 0
  31082. * roundTo(2000/7,2) == 300
  31083. * roundTo(2000/7,1) == 290
  31084. * roundTo(2000/7,0) == 286
  31085. * roundTo(2000/7,-1) == 285.7
  31086. * roundTo(2000/7,-2) == 285.71
  31087. * roundTo(2000/7,-3) == 285.714
  31088. * roundTo(2000/7,-4) == 285.7143
  31089. * roundTo(2000/7,-5) == 285.71429
  31090. *
  31091. * roundTo(2000/7,3,2) == 288 -- 100100000
  31092. * roundTo(2000/7,2,2) == 284 -- 100011100
  31093. * roundTo(2000/7,1,2) == 286 -- 100011110
  31094. * roundTo(2000/7,0,2) == 286 -- 100011110
  31095. * roundTo(2000/7,-1,2) == 285.5 -- 100011101.1
  31096. * roundTo(2000/7,-2,2) == 285.75 -- 100011101.11
  31097. * roundTo(2000/7,-3,2) == 285.75 -- 100011101.11
  31098. * roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011
  31099. * roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111
  31100. *
  31101. * Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed
  31102. * because we are rounding 100011.1011011011011011 which rounds up.
  31103. *
  31104. * @method Phaser.Math#roundTo
  31105. * @param {number} value - The value to round.
  31106. * @param {number} place - The place to round to.
  31107. * @param {number} base - The base to round in... default is 10 for decimal.
  31108. * @return {number}
  31109. */
  31110. roundTo: function (value, place, base) {
  31111. if (typeof place === "undefined") { place = 0; }
  31112. if (typeof base === "undefined") { base = 10; }
  31113. var p = Math.pow(base, -place);
  31114. return Math.round(value * p) / p;
  31115. },
  31116. /**
  31117. * @method Phaser.Math#floorTo
  31118. * @param {number} value - The value to round.
  31119. * @param {number} place - The place to round to.
  31120. * @param {number} base - The base to round in... default is 10 for decimal.
  31121. * @return {number}
  31122. */
  31123. floorTo: function (value, place, base) {
  31124. if (typeof place === "undefined") { place = 0; }
  31125. if (typeof base === "undefined") { base = 10; }
  31126. var p = Math.pow(base, -place);
  31127. return Math.floor(value * p) / p;
  31128. },
  31129. /**
  31130. * @method Phaser.Math#ceilTo
  31131. * @param {number} value - The value to round.
  31132. * @param {number} place - The place to round to.
  31133. * @param {number} base - The base to round in... default is 10 for decimal.
  31134. * @return {number}
  31135. */
  31136. ceilTo: function (value, place, base) {
  31137. if (typeof place === "undefined") { place = 0; }
  31138. if (typeof base === "undefined") { base = 10; }
  31139. var p = Math.pow(base, -place);
  31140. return Math.ceil(value * p) / p;
  31141. },
  31142. /**
  31143. * A one dimensional linear interpolation of a value.
  31144. * @method Phaser.Math#interpolateFloat
  31145. * @param {number} a
  31146. * @param {number} b
  31147. * @param {number} weight
  31148. * @return {number}
  31149. */
  31150. interpolateFloat: function (a, b, weight) {
  31151. return (b - a) * weight + a;
  31152. },
  31153. /**
  31154. * Find the angle of a segment from (x1, y1) -> (x2, y2).
  31155. * @method Phaser.Math#angleBetween
  31156. * @param {number} x1
  31157. * @param {number} y1
  31158. * @param {number} x2
  31159. * @param {number} y2
  31160. * @return {number}
  31161. */
  31162. angleBetween: function (x1, y1, x2, y2) {
  31163. return Math.atan2(y2 - y1, x2 - x1);
  31164. },
  31165. /**
  31166. * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y).
  31167. * @method Phaser.Math#angleBetweenPoints
  31168. * @param {Phaser.Point} point1
  31169. * @param {Phaser.Point} point2
  31170. * @return {number}
  31171. */
  31172. angleBetweenPoints: function (point1, point2) {
  31173. return Math.atan2(point2.y - point1.y, point2.x - point1.x);
  31174. },
  31175. /**
  31176. * Reverses an angle.
  31177. * @method Phaser.Math#reverseAngle
  31178. * @param {number} angleRad - The angle to reverse, in radians.
  31179. * @return {number} Returns the reverse angle, in radians.
  31180. */
  31181. reverseAngle: function (angleRad) {
  31182. return this.normalizeAngle(angleRad + Math.PI, true);
  31183. },
  31184. /**
  31185. * Normalizes an angle to the [0,2pi) range.
  31186. * @method Phaser.Math#normalizeAngle
  31187. * @param {number} angleRad - The angle to normalize, in radians.
  31188. * @return {number} Returns the angle, fit within the [0,2pi] range, in radians.
  31189. */
  31190. normalizeAngle: function (angleRad) {
  31191. angleRad = angleRad % (2 * Math.PI);
  31192. return angleRad >= 0 ? angleRad : angleRad + 2 * Math.PI;
  31193. },
  31194. /**
  31195. * Normalizes a latitude to the [-90,90] range. Latitudes above 90 or below -90 are capped, not wrapped.
  31196. * @method Phaser.Math#normalizeLatitude
  31197. * @param {number} lat - The latitude to normalize, in degrees.
  31198. * @return {number} Returns the latitude, fit within the [-90,90] range.
  31199. */
  31200. normalizeLatitude: function (lat) {
  31201. return Math.max(-90, Math.min(90, lat));
  31202. },
  31203. /**
  31204. * Normalizes a longitude to the [-180,180] range. Longitudes above 180 or below -180 are wrapped.
  31205. * @method Phaser.Math#normalizeLongitude
  31206. * @param {number} lng - The longitude to normalize, in degrees.
  31207. * @return {number} Returns the longitude, fit within the [-180,180] range.
  31208. */
  31209. normalizeLongitude: function (lng) {
  31210. if (lng % 360 == 180)
  31211. {
  31212. return 180;
  31213. }
  31214. lng = lng % 360;
  31215. return lng < -180 ? lng + 360 : lng > 180 ? lng - 360 : lng;
  31216. },
  31217. /**
  31218. * Closest angle between two angles from a1 to a2 absolute value the return for exact angle
  31219. * @method Phaser.Math#nearestAngleBetween
  31220. * @param {number} a1
  31221. * @param {number} a2
  31222. * @param {boolean} radians - True if angle sizes are expressed in radians.
  31223. * @return {number}
  31224. nearestAngleBetween: function (a1, a2, radians) {
  31225. if (typeof radians === "undefined") { radians = true; }
  31226. var rd = (radians) ? Math.PI : 180;
  31227. a1 = this.normalizeAngle(a1, radians);
  31228. a2 = this.normalizeAngle(a2, radians);
  31229. if (a1 < -rd / 2 && a2 > rd / 2)
  31230. {
  31231. a1 += rd * 2;
  31232. }
  31233. if (a2 < -rd / 2 && a1 > rd / 2)
  31234. {
  31235. a2 += rd * 2;
  31236. }
  31237. return a2 - a1;
  31238. },
  31239. */
  31240. /**
  31241. * Interpolate across the shortest arc between two angles.
  31242. * @method Phaser.Math#interpolateAngles
  31243. * @param {number} a1 - Description.
  31244. * @param {number} a2 - Description.
  31245. * @param {number} weight - Description.
  31246. * @param {boolean} radians - True if angle sizes are expressed in radians.
  31247. * @param {Description} ease - Description.
  31248. * @return {number}
  31249. interpolateAngles: function (a1, a2, weight, radians, ease) {
  31250. if (typeof radians === "undefined") { radians = true; }
  31251. if (typeof ease === "undefined") { ease = null; }
  31252. a1 = this.normalizeAngle(a1, radians);
  31253. a2 = this.normalizeAngleToAnother(a2, a1, radians);
  31254. return (typeof ease === 'function') ? ease(weight, a1, a2 - a1, 1) : this.interpolateFloat(a1, a2, weight);
  31255. },
  31256. */
  31257. /**
  31258. * Generate a random bool result based on the chance value.
  31259. * <p>
  31260. * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance
  31261. * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed.
  31262. * </p>
  31263. * @method Phaser.Math#chanceRoll
  31264. * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%).
  31265. * @return {boolean} True if the roll passed, or false otherwise.
  31266. */
  31267. chanceRoll: function (chance) {
  31268. if (typeof chance === "undefined") { chance = 50; }
  31269. if (chance <= 0)
  31270. {
  31271. return false;
  31272. }
  31273. else if (chance >= 100)
  31274. {
  31275. return true;
  31276. }
  31277. else
  31278. {
  31279. if (Math.random() * 100 >= chance)
  31280. {
  31281. return false;
  31282. }
  31283. else
  31284. {
  31285. return true;
  31286. }
  31287. }
  31288. },
  31289. /**
  31290. * Returns an Array containing the numbers from min to max (inclusive).
  31291. *
  31292. * @method Phaser.Math#numberArray
  31293. * @param {number} min - The minimum value the array starts with.
  31294. * @param {number} max - The maximum value the array contains.
  31295. * @return {array} The array of number values.
  31296. */
  31297. numberArray: function (min, max) {
  31298. var result = [];
  31299. for (var i = min; i <= max; i++)
  31300. {
  31301. result.push(i);
  31302. }
  31303. return result;
  31304. },
  31305. /**
  31306. * Adds the given amount to the value, but never lets the value go over the specified maximum.
  31307. *
  31308. * @method Phaser.Math#maxAdd
  31309. * @param {number} value - The value to add the amount to.
  31310. * @param {number} amount - The amount to add to the value.
  31311. * @param {number} max- The maximum the value is allowed to be.
  31312. * @return {number}
  31313. */
  31314. maxAdd: function (value, amount, max) {
  31315. value += amount;
  31316. if (value > max)
  31317. {
  31318. value = max;
  31319. }
  31320. return value;
  31321. },
  31322. /**
  31323. * Subtracts the given amount from the value, but never lets the value go below the specified minimum.
  31324. *
  31325. * @method Phaser.Math#minSub
  31326. * @param {number} value - The base value.
  31327. * @param {number} amount - The amount to subtract from the base value.
  31328. * @param {number} min - The minimum the value is allowed to be.
  31329. * @return {number} The new value.
  31330. */
  31331. minSub: function (value, amount, min) {
  31332. value -= amount;
  31333. if (value < min)
  31334. {
  31335. value = min;
  31336. }
  31337. return value;
  31338. },
  31339. /**
  31340. * Ensures that the value always stays between min and max, by wrapping the value around.
  31341. * max should be larger than min, or the function will return 0.
  31342. *
  31343. * @method Phaser.Math#wrap
  31344. * @param {number} value - The value to wrap.
  31345. * @param {number} min - The minimum the value is allowed to be.
  31346. * @param {number} max - The maximum the value is allowed to be.
  31347. * @return {number} The wrapped value.
  31348. */
  31349. wrap: function (value, min, max) {
  31350. var range = max - min;
  31351. if (range <= 0)
  31352. {
  31353. return 0;
  31354. }
  31355. var result = (value - min) % range;
  31356. if (result < 0)
  31357. {
  31358. result += range;
  31359. }
  31360. return result + min;
  31361. },
  31362. /**
  31363. * Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around.
  31364. * Values must be positive integers, and are passed through Math.abs.
  31365. *
  31366. * @method Phaser.Math#wrapValue
  31367. * @param {number} value - The value to add the amount to.
  31368. * @param {number} amount - The amount to add to the value.
  31369. * @param {number} max - The maximum the value is allowed to be.
  31370. * @return {number} The wrapped value.
  31371. */
  31372. wrapValue: function (value, amount, max) {
  31373. var diff;
  31374. value = Math.abs(value);
  31375. amount = Math.abs(amount);
  31376. max = Math.abs(max);
  31377. diff = (value + amount) % max;
  31378. return diff;
  31379. },
  31380. /**
  31381. * Ensures the given value is between min and max inclusive.
  31382. *
  31383. * @method Phaser.Math#limitValue
  31384. * @param {number} value - The value to limit.
  31385. * @param {number} min - The minimum the value can be.
  31386. * @param {number} max - The maximum the value can be.
  31387. * @return {number} The limited value.
  31388. */
  31389. limitValue: function(value, min, max) {
  31390. return value < min ? min : value > max ? max : value;
  31391. },
  31392. /**
  31393. * Randomly returns either a 1 or -1.
  31394. *
  31395. * @method Phaser.Math#randomSign
  31396. * @return {number} 1 or -1
  31397. */
  31398. randomSign: function () {
  31399. return (Math.random() > 0.5) ? 1 : -1;
  31400. },
  31401. /**
  31402. * Returns true if the number given is odd.
  31403. *
  31404. * @method Phaser.Math#isOdd
  31405. * @param {number} n - The number to check.
  31406. * @return {boolean} True if the given number is odd. False if the given number is even.
  31407. */
  31408. isOdd: function (n) {
  31409. return (n & 1);
  31410. },
  31411. /**
  31412. * Returns true if the number given is even.
  31413. *
  31414. * @method Phaser.Math#isEven
  31415. * @param {number} n - The number to check.
  31416. * @return {boolean} True if the given number is even. False if the given number is odd.
  31417. */
  31418. isEven: function (n) {
  31419. if (n & 1)
  31420. {
  31421. return false;
  31422. }
  31423. else
  31424. {
  31425. return true;
  31426. }
  31427. },
  31428. /**
  31429. * Updated version of Math.min that can be passed either an array of numbers or the numbers as parameters.
  31430. * See http://jsperf.com/math-s-min-max-vs-homemade/5
  31431. *
  31432. * @method Phaser.Math#min
  31433. * @return {number} The lowest value from those given.
  31434. */
  31435. min: function () {
  31436. if (arguments.length === 1 && typeof arguments[0] === 'object')
  31437. {
  31438. var data = arguments[0];
  31439. }
  31440. else
  31441. {
  31442. var data = arguments;
  31443. }
  31444. for (var i = 1, min = 0, len = data.length; i < len; i++)
  31445. {
  31446. if (data[i] < data[min])
  31447. {
  31448. min = i;
  31449. }
  31450. }
  31451. return data[min];
  31452. },
  31453. /**
  31454. * Updated version of Math.max that can be passed either an array of numbers or the numbers as parameters.
  31455. *
  31456. * @method Phaser.Math#max
  31457. * @return {number} The largest value from those given.
  31458. */
  31459. max: function () {
  31460. if (arguments.length === 1 && typeof arguments[0] === 'object')
  31461. {
  31462. var data = arguments[0];
  31463. }
  31464. else
  31465. {
  31466. var data = arguments;
  31467. }
  31468. for (var i = 1, max = 0, len = data.length; i < len; i++)
  31469. {
  31470. if (data[i] > data[max])
  31471. {
  31472. max = i;
  31473. }
  31474. }
  31475. return data[max];
  31476. },
  31477. /**
  31478. * Updated version of Math.min that can be passed a property and either an array of objects or the objects as parameters.
  31479. * It will find the lowest matching property value from the given objects.
  31480. *
  31481. * @method Phaser.Math#minProperty
  31482. * @return {number} The lowest value from those given.
  31483. */
  31484. minProperty: function (property) {
  31485. if (arguments.length === 2 && typeof arguments[1] === 'object')
  31486. {
  31487. var data = arguments[1];
  31488. }
  31489. else
  31490. {
  31491. var data = arguments.slice(1);
  31492. }
  31493. for (var i = 1, min = 0, len = data.length; i < len; i++)
  31494. {
  31495. if (data[i][property] < data[min][property])
  31496. {
  31497. min = i;
  31498. }
  31499. }
  31500. return data[min][property];
  31501. },
  31502. /**
  31503. * Updated version of Math.max that can be passed a property and either an array of objects or the objects as parameters.
  31504. * It will find the largest matching property value from the given objects.
  31505. *
  31506. * @method Phaser.Math#maxProperty
  31507. * @return {number} The largest value from those given.
  31508. */
  31509. maxProperty: function (property) {
  31510. if (arguments.length === 2 && typeof arguments[1] === 'object')
  31511. {
  31512. var data = arguments[1];
  31513. }
  31514. else
  31515. {
  31516. var data = arguments.slice(1);
  31517. }
  31518. for (var i = 1, max = 0, len = data.length; i < len; i++)
  31519. {
  31520. if (data[i][property] > data[max][property])
  31521. {
  31522. max = i;
  31523. }
  31524. }
  31525. return data[max][property];
  31526. },
  31527. /**
  31528. * Keeps an angle value between -180 and +180.
  31529. *
  31530. * @method Phaser.Math#wrapAngle
  31531. * @param {number} angle - The angle value to check
  31532. * @param {boolean} radians - True if angle is given in radians.
  31533. * @return {number} The new angle value, returns the same as the input angle if it was within bounds.
  31534. */
  31535. wrapAngle: function (angle, radians) {
  31536. var radianFactor = (radians) ? Math.PI / 180 : 1;
  31537. return this.wrap(angle, -180 * radianFactor, 180 * radianFactor);
  31538. },
  31539. /**
  31540. * Keeps an angle value between the given min and max values.
  31541. *
  31542. * @method Phaser.Math#angleLimit
  31543. * @param {number} angle - The angle value to check. Must be between -180 and +180.
  31544. * @param {number} min - The minimum angle that is allowed (must be -180 or greater).
  31545. * @param {number} max - The maximum angle that is allowed (must be 180 or less).
  31546. * @return {number} The new angle value, returns the same as the input angle if it was within bounds
  31547. */
  31548. angleLimit: function (angle, min, max) {
  31549. var result = angle;
  31550. if (angle > max)
  31551. {
  31552. result = max;
  31553. }
  31554. else if (angle < min)
  31555. {
  31556. result = min;
  31557. }
  31558. return result;
  31559. },
  31560. /**
  31561. * A Linear Interpolation Method, mostly used by Phaser.Tween.
  31562. * @method Phaser.Math#linearInterpolation
  31563. * @param {Array} v
  31564. * @param {number} k
  31565. * @return {number}
  31566. */
  31567. linearInterpolation: function (v, k) {
  31568. var m = v.length - 1;
  31569. var f = m * k;
  31570. var i = Math.floor(f);
  31571. if (k < 0)
  31572. {
  31573. return this.linear(v[0], v[1], f);
  31574. }
  31575. if (k > 1)
  31576. {
  31577. return this.linear(v[m], v[m - 1], m - f);
  31578. }
  31579. return this.linear(v[i], v[i + 1 > m ? m : i + 1], f - i);
  31580. },
  31581. /**
  31582. * A Bezier Interpolation Method, mostly used by Phaser.Tween.
  31583. * @method Phaser.Math#bezierInterpolation
  31584. * @param {Array} v
  31585. * @param {number} k
  31586. * @return {number}
  31587. */
  31588. bezierInterpolation: function (v, k) {
  31589. var b = 0;
  31590. var n = v.length - 1;
  31591. for (var i = 0; i <= n; i++)
  31592. {
  31593. b += Math.pow(1 - k, n - i) * Math.pow(k, i) * v[i] * this.bernstein(n, i);
  31594. }
  31595. return b;
  31596. },
  31597. /**
  31598. * A Catmull Rom Interpolation Method, mostly used by Phaser.Tween.
  31599. * @method Phaser.Math#catmullRomInterpolation
  31600. * @param {Array} v
  31601. * @param {number} k
  31602. * @return {number}
  31603. */
  31604. catmullRomInterpolation: function (v, k) {
  31605. var m = v.length - 1;
  31606. var f = m * k;
  31607. var i = Math.floor(f);
  31608. if (v[0] === v[m])
  31609. {
  31610. if (k < 0)
  31611. {
  31612. i = Math.floor(f = m * (1 + k));
  31613. }
  31614. return this.catmullRom(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i);
  31615. }
  31616. else
  31617. {
  31618. if (k < 0)
  31619. {
  31620. return v[0] - (this.catmullRom(v[0], v[0], v[1], v[1], -f) - v[0]);
  31621. }
  31622. if (k > 1)
  31623. {
  31624. return v[m] - (this.catmullRom(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]);
  31625. }
  31626. 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);
  31627. }
  31628. },
  31629. /**
  31630. * Description.
  31631. * @method Phaser.Math#Linear
  31632. * @param {number} p0
  31633. * @param {number} p1
  31634. * @param {number} t
  31635. * @return {number}
  31636. */
  31637. linear: function (p0, p1, t) {
  31638. return (p1 - p0) * t + p0;
  31639. },
  31640. /**
  31641. * @method Phaser.Math#bernstein
  31642. * @param {number} n
  31643. * @param {number} i
  31644. * @return {number}
  31645. */
  31646. bernstein: function (n, i) {
  31647. return this.factorial(n) / this.factorial(i) / this.factorial(n - i);
  31648. },
  31649. /**
  31650. * @method Phaser.Math#factorial
  31651. * @param {number} value - the number you want to evaluate
  31652. * @return {number}
  31653. */
  31654. factorial : function( value ){
  31655. if(value === 0)
  31656. {
  31657. return 1;
  31658. }
  31659. var res = value;
  31660. while( --value )
  31661. {
  31662. res *= value;
  31663. }
  31664. return res;
  31665. },
  31666. /**
  31667. * Description.
  31668. * @method Phaser.Math#catmullRom
  31669. * @param {number} p0
  31670. * @param {number} p1
  31671. * @param {number} p2
  31672. * @param {number} p3
  31673. * @param {number} t
  31674. * @return {number}
  31675. */
  31676. catmullRom: function (p0, p1, p2, p3, t) {
  31677. var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2;
  31678. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  31679. },
  31680. /**
  31681. * @method Phaser.Math#difference
  31682. * @param {number} a
  31683. * @param {number} b
  31684. * @return {number}
  31685. */
  31686. difference: function (a, b) {
  31687. return Math.abs(a - b);
  31688. },
  31689. /**
  31690. * Fetch a random entry from the given array.
  31691. * Will return null if random selection is missing, or array has no entries.
  31692. *
  31693. * @method Phaser.Math#getRandom
  31694. * @param {array} objects - An array of objects.
  31695. * @param {number} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array.
  31696. * @param {number} length - Optional restriction on the number of values you want to randomly select from.
  31697. * @return {object} The random object that was selected.
  31698. */
  31699. getRandom: function (objects, startIndex, length) {
  31700. if (typeof startIndex === "undefined") { startIndex = 0; }
  31701. if (typeof length === "undefined") { length = 0; }
  31702. if (objects != null) {
  31703. var l = length;
  31704. if ((l === 0) || (l > objects.length - startIndex))
  31705. {
  31706. l = objects.length - startIndex;
  31707. }
  31708. if (l > 0)
  31709. {
  31710. return objects[startIndex + Math.floor(Math.random() * l)];
  31711. }
  31712. }
  31713. return null;
  31714. },
  31715. /**
  31716. * Removes a random object from the given array and returns it.
  31717. * Will return null if random selection is missing, or array has no entries.
  31718. *
  31719. * @method Phaser.Math#removeRandom
  31720. * @param {array} objects - An array of objects.
  31721. * @param {number} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array.
  31722. * @param {number} length - Optional restriction on the number of values you want to randomly select from.
  31723. * @return {object} The random object that was removed.
  31724. */
  31725. removeRandom: function (objects, startIndex, length) {
  31726. if (typeof startIndex === "undefined") { startIndex = 0; }
  31727. if (typeof length === "undefined") { length = 0; }
  31728. if (objects != null) {
  31729. var l = length;
  31730. if ((l === 0) || (l > objects.length - startIndex))
  31731. {
  31732. l = objects.length - startIndex;
  31733. }
  31734. if (l > 0)
  31735. {
  31736. var idx = startIndex + Math.floor(Math.random() * l);
  31737. var removed = objects.splice(idx, 1);
  31738. return removed[0];
  31739. }
  31740. }
  31741. return null;
  31742. },
  31743. /**
  31744. * Round down to the next whole number. E.g. floor(1.7) == 1, and floor(-2.7) == -2.
  31745. *
  31746. * @method Phaser.Math#floor
  31747. * @param {number} Value Any number.
  31748. * @return {number} The rounded value of that number.
  31749. */
  31750. floor: function (value) {
  31751. var n = value | 0;
  31752. return (value > 0) ? (n) : ((n != value) ? (n - 1) : (n));
  31753. },
  31754. /**
  31755. * Round up to the next whole number. E.g. ceil(1.3) == 2, and ceil(-2.3) == -3.
  31756. *
  31757. * @method Phaser.Math#ceil
  31758. * @param {number} value - Any number.
  31759. * @return {number} The rounded value of that number.
  31760. */
  31761. ceil: function (value) {
  31762. var n = value | 0;
  31763. return (value > 0) ? ((n != value) ? (n + 1) : (n)) : (n);
  31764. },
  31765. /**
  31766. * Generate a sine and cosine table simultaneously and extremely quickly. Based on research by Franky of scene.at
  31767. * <p>
  31768. * The parameters allow you to specify the length, amplitude and frequency of the wave. Once you have called this function
  31769. * you should get the results via getSinTable() and getCosTable(). This generator is fast enough to be used in real-time.
  31770. * </p>
  31771. * @method Phaser.Math#sinCosGenerator
  31772. * @param {number} length - The length of the wave
  31773. * @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
  31774. * @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
  31775. * @param {number} frequency - The frequency of the sine and cosine table data
  31776. * @return {Array} Returns the sine table
  31777. */
  31778. sinCosGenerator: function (length, sinAmplitude, cosAmplitude, frequency) {
  31779. if (typeof sinAmplitude === "undefined") { sinAmplitude = 1.0; }
  31780. if (typeof cosAmplitude === "undefined") { cosAmplitude = 1.0; }
  31781. if (typeof frequency === "undefined") { frequency = 1.0; }
  31782. var sin = sinAmplitude;
  31783. var cos = cosAmplitude;
  31784. var frq = frequency * Math.PI / length;
  31785. var cosTable = [];
  31786. var sinTable = [];
  31787. for (var c = 0; c < length; c++) {
  31788. cos -= sin * frq;
  31789. sin += cos * frq;
  31790. cosTable[c] = cos;
  31791. sinTable[c] = sin;
  31792. }
  31793. return { sin: sinTable, cos: cosTable, length: length };
  31794. },
  31795. /**
  31796. * Removes the top element from the stack and re-inserts it onto the bottom, then returns it.
  31797. * The original stack is modified in the process. This effectively moves the position of the data from the start to the end of the table.
  31798. *
  31799. * @method Phaser.Math#shift
  31800. * @param {array} stack - The array to shift.
  31801. * @return {any} The shifted value.
  31802. */
  31803. shift: function (stack) {
  31804. var s = stack.shift();
  31805. stack.push(s);
  31806. return s;
  31807. },
  31808. /**
  31809. * Shuffles the data in the given array into a new order
  31810. * @method Phaser.Math#shuffleArray
  31811. * @param {array} array - The array to shuffle
  31812. * @return {array} The array
  31813. */
  31814. shuffleArray: function (array) {
  31815. for (var i = array.length - 1; i > 0; i--) {
  31816. var j = Math.floor(Math.random() * (i + 1));
  31817. var temp = array[i];
  31818. array[i] = array[j];
  31819. array[j] = temp;
  31820. }
  31821. return array;
  31822. },
  31823. /**
  31824. * Returns the distance between the two given set of coordinates.
  31825. *
  31826. * @method Phaser.Math#distance
  31827. * @param {number} x1
  31828. * @param {number} y1
  31829. * @param {number} x2
  31830. * @param {number} y2
  31831. * @return {number} The distance between the two sets of coordinates.
  31832. */
  31833. distance: function (x1, y1, x2, y2) {
  31834. var dx = x1 - x2;
  31835. var dy = y1 - y2;
  31836. return Math.sqrt(dx * dx + dy * dy);
  31837. },
  31838. /**
  31839. * Returns the distance between the two given set of coordinates at the power given.
  31840. *
  31841. * @method Phaser.Math#distancePow
  31842. * @param {number} x1
  31843. * @param {number} y1
  31844. * @param {number} x2
  31845. * @param {number} y2
  31846. * @param {number} [pow=2]
  31847. * @return {number} The distance between the two sets of coordinates.
  31848. */
  31849. distancePow: function (x1, y1, x2, y2, pow) {
  31850. if (typeof pow === 'undefined') { pow = 2; }
  31851. return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow));
  31852. },
  31853. /**
  31854. * Returns the rounded distance between the two given set of coordinates.
  31855. *
  31856. * @method Phaser.Math#distanceRounded
  31857. * @param {number} x1
  31858. * @param {number} y1
  31859. * @param {number} x2
  31860. * @param {number} y2
  31861. * @return {number} The distance between this Point object and the destination Point object.
  31862. */
  31863. distanceRounded: function (x1, y1, x2, y2) {
  31864. return Math.round(Phaser.Math.distance(x1, y1, x2, y2));
  31865. },
  31866. /**
  31867. * Force a value within the boundaries of two values.
  31868. * Clamp value to range <a, b>
  31869. *
  31870. * @method Phaser.Math#clamp
  31871. * @param {number} x
  31872. * @param {number} a
  31873. * @param {number} b
  31874. * @return {number}
  31875. */
  31876. clamp: function ( x, a, b ) {
  31877. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  31878. },
  31879. /**
  31880. * Clamp value to range <a, inf).
  31881. *
  31882. * @method Phaser.Math#clampBottom
  31883. * @param {number} x
  31884. * @param {number} a
  31885. * @return {number}
  31886. */
  31887. clampBottom: function ( x, a ) {
  31888. return x < a ? a : x;
  31889. },
  31890. /**
  31891. * Checks if two values are within the given tolerance of each other.
  31892. *
  31893. * @method Phaser.Math#within
  31894. * @param {number} a - The first number to check
  31895. * @param {number} b - The second number to check
  31896. * @param {number} tolerance - The tolerance. Anything equal to or less than this is considered within the range.
  31897. * @return {boolean} True if a is <= tolerance of b.
  31898. */
  31899. within: function ( a, b, tolerance ) {
  31900. return (Math.abs(a - b) <= tolerance);
  31901. },
  31902. /**
  31903. * Linear mapping from range <a1, a2> to range <b1, b2>
  31904. *
  31905. * @method Phaser.Math#mapLinear
  31906. * @param {number} x the value to map
  31907. * @param {number} a1 first endpoint of the range <a1, a2>
  31908. * @param {number} a2 final endpoint of the range <a1, a2>
  31909. * @param {number} b1 first endpoint of the range <b1, b2>
  31910. * @param {number} b2 final endpoint of the range <b1, b2>
  31911. * @return {number}
  31912. */
  31913. mapLinear: function ( x, a1, a2, b1, b2 ) {
  31914. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  31915. },
  31916. /**
  31917. * Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep
  31918. *
  31919. * @method Phaser.Math#smoothstep
  31920. * @param {number} x
  31921. * @param {number} min
  31922. * @param {number} max
  31923. * @return {number}
  31924. */
  31925. smoothstep: function ( x, min, max ) {
  31926. x = Math.max(0, Math.min(1, (x - min) / (max - min)));
  31927. return x * x * (3 - 2 * x);
  31928. },
  31929. /**
  31930. * Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep
  31931. *
  31932. * @method Phaser.Math#smootherstep
  31933. * @param {number} x
  31934. * @param {number} min
  31935. * @param {number} max
  31936. * @return {number}
  31937. */
  31938. smootherstep: function ( x, min, max ) {
  31939. x = Math.max(0, Math.min(1, (x - min) / (max - min)));
  31940. return x * x * x * (x * (x * 6 - 15) + 10);
  31941. },
  31942. /**
  31943. * A value representing the sign of the value.
  31944. * -1 for negative, +1 for positive, 0 if value is 0
  31945. *
  31946. * @method Phaser.Math#sign
  31947. * @param {number} x
  31948. * @return {number}
  31949. */
  31950. sign: function ( x ) {
  31951. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  31952. },
  31953. /**
  31954. * Work out what percentage value a is of value b using the given base.
  31955. *
  31956. * @method Phaser.Math#percent
  31957. * @param {number} a - The value to work out the percentage for.
  31958. * @param {number} b - The value you wish to get the percentage of.
  31959. * @param {number} [base=0] - The base value.
  31960. * @return {number} The percentage a is of b, between 0 and 1.
  31961. */
  31962. percent: function (a, b, base) {
  31963. if (typeof base === 'undefined') { base = 0; }
  31964. if (a > b || base > b)
  31965. {
  31966. return 1;
  31967. }
  31968. else if (a < base || base > a)
  31969. {
  31970. return 0;
  31971. }
  31972. else
  31973. {
  31974. return (a - base) / b;
  31975. }
  31976. },
  31977. /**
  31978. * Convert degrees to radians.
  31979. *
  31980. * @method Phaser.Math#degToRad
  31981. * @return {function}
  31982. */
  31983. degToRad: (function() {
  31984. var degreeToRadiansFactor = Math.PI / 180;
  31985. return function ( degrees ) {
  31986. return degrees * degreeToRadiansFactor;
  31987. };
  31988. }()),
  31989. /**
  31990. * Convert degrees to radians.
  31991. *
  31992. * @method Phaser.Math#radToDeg
  31993. * @return {function}
  31994. */
  31995. radToDeg: (function() {
  31996. var radianToDegreesFactor = 180 / Math.PI;
  31997. return function ( radians ) {
  31998. return radians * radianToDegreesFactor;
  31999. };
  32000. }())
  32001. };
  32002. /* jshint noempty: false */
  32003. /**
  32004. * @author Richard Davey <rich@photonstorm.com>
  32005. * @copyright 2014 Photon Storm Ltd.
  32006. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  32007. */
  32008. /**
  32009. * Phaser.RandomDataGenerator constructor.
  32010. *
  32011. * @class Phaser.RandomDataGenerator
  32012. * @classdesc An extremely useful repeatable random data generator. Access it via Phaser.Game.rnd
  32013. * Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense.
  32014. * Random number generator from http://baagoe.org/en/wiki/Better_random_numbers_for_javascript
  32015. *
  32016. * @constructor
  32017. * @param {array} seeds
  32018. */
  32019. Phaser.RandomDataGenerator = function (seeds) {
  32020. if (typeof seeds === "undefined") { seeds = []; }
  32021. /**
  32022. * @property {number} c - Internal var.
  32023. * @private
  32024. */
  32025. this.c = 1;
  32026. /**
  32027. * @property {number} s0 - Internal var.
  32028. * @private
  32029. */
  32030. this.s0 = 0;
  32031. /**
  32032. * @property {number} s1 - Internal var.
  32033. * @private
  32034. */
  32035. this.s1 = 0;
  32036. /**
  32037. * @property {number} s2 - Internal var.
  32038. * @private
  32039. */
  32040. this.s2 = 0;
  32041. this.sow(seeds);
  32042. };
  32043. Phaser.RandomDataGenerator.prototype = {
  32044. /**
  32045. * Private random helper.
  32046. *
  32047. * @method Phaser.RandomDataGenerator#rnd
  32048. * @private
  32049. * @return {number}
  32050. */
  32051. rnd: function () {
  32052. var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32
  32053. this.c = t | 0;
  32054. this.s0 = this.s1;
  32055. this.s1 = this.s2;
  32056. this.s2 = t - this.c;
  32057. return this.s2;
  32058. },
  32059. /**
  32060. * Reset the seed of the random data generator.
  32061. *
  32062. * @method Phaser.RandomDataGenerator#sow
  32063. * @param {array} seeds
  32064. */
  32065. sow: function (seeds) {
  32066. if (typeof seeds === "undefined") { seeds = []; }
  32067. this.s0 = this.hash(' ');
  32068. this.s1 = this.hash(this.s0);
  32069. this.s2 = this.hash(this.s1);
  32070. this.c = 1;
  32071. var seed;
  32072. for (var i = 0; seed = seeds[i++]; )
  32073. {
  32074. this.s0 -= this.hash(seed);
  32075. this.s0 += ~~(this.s0 < 0);
  32076. this.s1 -= this.hash(seed);
  32077. this.s1 += ~~(this.s1 < 0);
  32078. this.s2 -= this.hash(seed);
  32079. this.s2 += ~~(this.s2 < 0);
  32080. }
  32081. },
  32082. /**
  32083. * Internal method that creates a seed hash.
  32084. *
  32085. * @method Phaser.RandomDataGenerator#hash
  32086. * @private
  32087. * @param {Any} data
  32088. * @return {number} hashed value.
  32089. */
  32090. hash: function (data) {
  32091. var h, i, n;
  32092. n = 0xefc8249d;
  32093. data = data.toString();
  32094. for (i = 0; i < data.length; i++) {
  32095. n += data.charCodeAt(i);
  32096. h = 0.02519603282416938 * n;
  32097. n = h >>> 0;
  32098. h -= n;
  32099. h *= n;
  32100. n = h >>> 0;
  32101. h -= n;
  32102. n += h * 0x100000000;// 2^32
  32103. }
  32104. return (n >>> 0) * 2.3283064365386963e-10;// 2^-32
  32105. },
  32106. /**
  32107. * Returns a random integer between 0 and 2^32.
  32108. *
  32109. * @method Phaser.RandomDataGenerator#integer
  32110. * @return {number} A random integer between 0 and 2^32.
  32111. */
  32112. integer: function() {
  32113. return this.rnd.apply(this) * 0x100000000;// 2^32
  32114. },
  32115. /**
  32116. * Returns a random real number between 0 and 1.
  32117. *
  32118. * @method Phaser.RandomDataGenerator#frac
  32119. * @return {number} A random real number between 0 and 1.
  32120. */
  32121. frac: function() {
  32122. return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
  32123. },
  32124. /**
  32125. * Returns a random real number between 0 and 2^32.
  32126. *
  32127. * @method Phaser.RandomDataGenerator#real
  32128. * @return {number} A random real number between 0 and 2^32.
  32129. */
  32130. real: function() {
  32131. return this.integer() + this.frac();
  32132. },
  32133. /**
  32134. * Returns a random integer between and including min and max.
  32135. *
  32136. * @method Phaser.RandomDataGenerator#integerInRange
  32137. * @param {number} min - The minimum value in the range.
  32138. * @param {number} max - The maximum value in the range.
  32139. * @return {number} A random number between min and max.
  32140. */
  32141. integerInRange: function (min, max) {
  32142. return Math.floor(this.realInRange(0, max - min + 1) + min);
  32143. },
  32144. /**
  32145. * Returns a random integer between and including min and max.
  32146. * This method is an alias for RandomDataGenerator.integerInRange.
  32147. *
  32148. * @method Phaser.RandomDataGenerator#between
  32149. * @param {number} min - The minimum value in the range.
  32150. * @param {number} max - The maximum value in the range.
  32151. * @return {number} A random number between min and max.
  32152. */
  32153. between: function (min, max) {
  32154. return this.integerInRange(min, max);
  32155. },
  32156. /**
  32157. * Returns a random real number between min and max.
  32158. *
  32159. * @method Phaser.RandomDataGenerator#realInRange
  32160. * @param {number} min - The minimum value in the range.
  32161. * @param {number} max - The maximum value in the range.
  32162. * @return {number} A random number between min and max.
  32163. */
  32164. realInRange: function (min, max) {
  32165. return this.frac() * (max - min) + min;
  32166. },
  32167. /**
  32168. * Returns a random real number between -1 and 1.
  32169. *
  32170. * @method Phaser.RandomDataGenerator#normal
  32171. * @return {number} A random real number between -1 and 1.
  32172. */
  32173. normal: function () {
  32174. return 1 - 2 * this.frac();
  32175. },
  32176. /**
  32177. * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368
  32178. *
  32179. * @method Phaser.RandomDataGenerator#uuid
  32180. * @return {string} A valid RFC4122 version4 ID hex string
  32181. */
  32182. uuid: function () {
  32183. var a = '';
  32184. var b = '';
  32185. for (b = a = ''; a++ < 36; b +=~a % 5 | a * 3&4 ? (a^15 ? 8^this.frac() * (a^20 ? 16 : 4) : 4).toString(16) : '-')
  32186. {
  32187. }
  32188. return b;
  32189. },
  32190. /**
  32191. * Returns a random member of `array`.
  32192. *
  32193. * @method Phaser.RandomDataGenerator#pick
  32194. * @param {Array} ary - An Array to pick a random member of.
  32195. * @return {any} A random member of the array.
  32196. */
  32197. pick: function (ary) {
  32198. return ary[this.integerInRange(0, ary.length - 1)];
  32199. },
  32200. /**
  32201. * Returns a random member of `array`, favoring the earlier entries.
  32202. *
  32203. * @method Phaser.RandomDataGenerator#weightedPick
  32204. * @param {Array} ary - An Array to pick a random member of.
  32205. * @return {any} A random member of the array.
  32206. */
  32207. weightedPick: function (ary) {
  32208. return ary[~~(Math.pow(this.frac(), 2) * (ary.length - 1))];
  32209. },
  32210. /**
  32211. * 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.
  32212. *
  32213. * @method Phaser.RandomDataGenerator#timestamp
  32214. * @param {number} min - The minimum value in the range.
  32215. * @param {number} max - The maximum value in the range.
  32216. * @return {number} A random timestamp between min and max.
  32217. */
  32218. timestamp: function (min, max) {
  32219. return this.realInRange(min || 946684800000, max || 1577862000000);
  32220. },
  32221. /**
  32222. * Returns a random angle between -180 and 180.
  32223. *
  32224. * @method Phaser.RandomDataGenerator#angle
  32225. * @return {number} A random number between -180 and 180.
  32226. */
  32227. angle: function() {
  32228. return this.integerInRange(-180, 180);
  32229. }
  32230. };
  32231. Phaser.RandomDataGenerator.prototype.constructor = Phaser.RandomDataGenerator;
  32232. /**
  32233. * @author Richard Davey <rich@photonstorm.com>
  32234. * @copyright 2014 Photon Storm Ltd.
  32235. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  32236. */
  32237. /**
  32238. * Javascript QuadTree
  32239. * @version 1.0
  32240. * @author Timo Hausmann
  32241. *
  32242. * @version 1.3, March 11th 2014
  32243. * @author Richard Davey
  32244. * The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked
  32245. * it massively to add node indexing, removed lots of temp. var creation and significantly
  32246. * increased performance as a result.
  32247. *
  32248. * Original version at https://github.com/timohausmann/quadtree-js/
  32249. */
  32250. /**
  32251. * @copyright © 2012 Timo Hausmann
  32252. *
  32253. * Permission is hereby granted, free of charge, to any person obtaining
  32254. * a copy of this software and associated documentation files (the
  32255. * "Software"), to deal in the Software without restriction, including
  32256. * without limitation the rights to use, copy, modify, merge, publish,
  32257. * distribute, sublicense, and/or sell copies of the Software, and to
  32258. * permit persons to whom the Software is furnished to do so, subject to
  32259. * the following conditions:
  32260. *
  32261. * The above copyright notice and this permission notice shall be
  32262. * included in all copies or substantial portions of the Software.
  32263. *
  32264. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  32265. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  32266. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  32267. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  32268. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  32269. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  32270. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32271. */
  32272. /**
  32273. * QuadTree Constructor
  32274. *
  32275. * @class Phaser.QuadTree
  32276. * @classdesc A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts.
  32277. * However I've tweaked it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result.
  32278. * Original version at https://github.com/timohausmann/quadtree-js/
  32279. * @constructor
  32280. * @param {number} x - The top left coordinate of the quadtree.
  32281. * @param {number} y - The top left coordinate of the quadtree.
  32282. * @param {number} width - The width of the quadtree in pixels.
  32283. * @param {number} height - The height of the quadtree in pixels.
  32284. * @param {number} [maxObjects=10] - The maximum number of objects per node.
  32285. * @param {number} [maxLevels=4] - The maximum number of levels to iterate to.
  32286. * @param {number} [level=0] - Which level is this?
  32287. */
  32288. Phaser.QuadTree = function(x, y, width, height, maxObjects, maxLevels, level) {
  32289. /**
  32290. * @property {number} maxObjects - The maximum number of objects per node.
  32291. * @default
  32292. */
  32293. this.maxObjects = 10;
  32294. /**
  32295. * @property {number} maxLevels - The maximum number of levels to break down to.
  32296. * @default
  32297. */
  32298. this.maxLevels = 4;
  32299. /**
  32300. * @property {number} level - The current level.
  32301. */
  32302. this.level = 0;
  32303. /**
  32304. * @property {object} bounds - Object that contains the quadtree bounds.
  32305. */
  32306. this.bounds = {};
  32307. /**
  32308. * @property {array} objects - Array of quadtree children.
  32309. */
  32310. this.objects = [];
  32311. /**
  32312. * @property {array} nodes - Array of associated child nodes.
  32313. */
  32314. this.nodes = [];
  32315. /**
  32316. * @property {array} _empty - Internal empty array.
  32317. * @private
  32318. */
  32319. this._empty = [];
  32320. this.reset(x, y, width, height, maxObjects, maxLevels, level);
  32321. };
  32322. Phaser.QuadTree.prototype = {
  32323. /**
  32324. * Resets the QuadTree.
  32325. *
  32326. * @method Phaser.QuadTree#reset
  32327. * @param {number} x - The top left coordinate of the quadtree.
  32328. * @param {number} y - The top left coordinate of the quadtree.
  32329. * @param {number} width - The width of the quadtree in pixels.
  32330. * @param {number} height - The height of the quadtree in pixels.
  32331. * @param {number} [maxObjects=10] - The maximum number of objects per node.
  32332. * @param {number} [maxLevels=4] - The maximum number of levels to iterate to.
  32333. * @param {number} [level=0] - Which level is this?
  32334. */
  32335. reset: function (x, y, width, height, maxObjects, maxLevels, level) {
  32336. this.maxObjects = maxObjects || 10;
  32337. this.maxLevels = maxLevels || 4;
  32338. this.level = level || 0;
  32339. this.bounds = {
  32340. x: Math.round(x),
  32341. y: Math.round(y),
  32342. width: width,
  32343. height: height,
  32344. subWidth: Math.floor(width / 2),
  32345. subHeight: Math.floor(height / 2),
  32346. right: Math.round(x) + Math.floor(width / 2),
  32347. bottom: Math.round(y) + Math.floor(height / 2)
  32348. };
  32349. this.objects.length = 0;
  32350. this.nodes.length = 0;
  32351. },
  32352. /**
  32353. * Populates this quadtree with the children of the given Group. In order to be added the child must exist and have a body property.
  32354. *
  32355. * @method Phaser.QuadTree#populate
  32356. * @param {Phaser.Group} group - The Group to add to the quadtree.
  32357. */
  32358. populate: function (group) {
  32359. group.forEach(this.populateHandler, this, true);
  32360. },
  32361. /**
  32362. * Handler for the populate method.
  32363. *
  32364. * @method Phaser.QuadTree#populateHandler
  32365. * @param {Phaser.Sprite|object} sprite - The Sprite to check.
  32366. */
  32367. populateHandler: function (sprite) {
  32368. if (sprite.body && sprite.exists)
  32369. {
  32370. this.insert(sprite.body);
  32371. }
  32372. },
  32373. /**
  32374. * Split the node into 4 subnodes
  32375. *
  32376. * @method Phaser.QuadTree#split
  32377. */
  32378. split: function () {
  32379. // top right node
  32380. 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));
  32381. // top left node
  32382. 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));
  32383. // bottom left node
  32384. 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));
  32385. // bottom right node
  32386. 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));
  32387. },
  32388. /**
  32389. * Insert the object into the node. If the node exceeds the capacity, it will split and add all objects to their corresponding subnodes.
  32390. *
  32391. * @method Phaser.QuadTree#insert
  32392. * @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.
  32393. */
  32394. insert: function (body) {
  32395. var i = 0;
  32396. var index;
  32397. // if we have subnodes ...
  32398. if (this.nodes[0] != null)
  32399. {
  32400. index = this.getIndex(body);
  32401. if (index !== -1)
  32402. {
  32403. this.nodes[index].insert(body);
  32404. return;
  32405. }
  32406. }
  32407. this.objects.push(body);
  32408. if (this.objects.length > this.maxObjects && this.level < this.maxLevels)
  32409. {
  32410. // Split if we don't already have subnodes
  32411. if (this.nodes[0] == null)
  32412. {
  32413. this.split();
  32414. }
  32415. // Add objects to subnodes
  32416. while (i < this.objects.length)
  32417. {
  32418. index = this.getIndex(this.objects[i]);
  32419. if (index !== -1)
  32420. {
  32421. // this is expensive - see what we can do about it
  32422. this.nodes[index].insert(this.objects.splice(i, 1)[0]);
  32423. }
  32424. else
  32425. {
  32426. i++;
  32427. }
  32428. }
  32429. }
  32430. },
  32431. /**
  32432. * Determine which node the object belongs to.
  32433. *
  32434. * @method Phaser.QuadTree#getIndex
  32435. * @param {Phaser.Rectangle|object} rect - The bounds in which to check.
  32436. * @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.
  32437. */
  32438. getIndex: function (rect) {
  32439. // default is that rect doesn't fit, i.e. it straddles the internal quadrants
  32440. var index = -1;
  32441. if (rect.x < this.bounds.right && rect.right < this.bounds.right)
  32442. {
  32443. if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom)
  32444. {
  32445. // rect fits within the top-left quadrant of this quadtree
  32446. index = 1;
  32447. }
  32448. else if (rect.y > this.bounds.bottom)
  32449. {
  32450. // rect fits within the bottom-left quadrant of this quadtree
  32451. index = 2;
  32452. }
  32453. }
  32454. else if (rect.x > this.bounds.right)
  32455. {
  32456. // rect can completely fit within the right quadrants
  32457. if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom)
  32458. {
  32459. // rect fits within the top-right quadrant of this quadtree
  32460. index = 0;
  32461. }
  32462. else if (rect.y > this.bounds.bottom)
  32463. {
  32464. // rect fits within the bottom-right quadrant of this quadtree
  32465. index = 3;
  32466. }
  32467. }
  32468. return index;
  32469. },
  32470. /**
  32471. * Return all objects that could collide with the given Sprite or Rectangle.
  32472. *
  32473. * @method Phaser.QuadTree#retrieve
  32474. * @param {Phaser.Sprite|Phaser.Rectangle} source - The source object to check the QuadTree against. Either a Sprite or Rectangle.
  32475. * @return {array} - Array with all detected objects.
  32476. */
  32477. retrieve: function (source) {
  32478. if (source instanceof Phaser.Rectangle)
  32479. {
  32480. var returnObjects = this.objects;
  32481. var index = this.getIndex(source);
  32482. }
  32483. else
  32484. {
  32485. if (!source.body)
  32486. {
  32487. return this._empty;
  32488. }
  32489. var returnObjects = this.objects;
  32490. var index = this.getIndex(source.body);
  32491. }
  32492. if (this.nodes[0])
  32493. {
  32494. // If rect fits into a subnode ..
  32495. if (index !== -1)
  32496. {
  32497. returnObjects = returnObjects.concat(this.nodes[index].retrieve(source));
  32498. }
  32499. else
  32500. {
  32501. // If rect does not fit into a subnode, check it against all subnodes (unrolled for speed)
  32502. returnObjects = returnObjects.concat(this.nodes[0].retrieve(source));
  32503. returnObjects = returnObjects.concat(this.nodes[1].retrieve(source));
  32504. returnObjects = returnObjects.concat(this.nodes[2].retrieve(source));
  32505. returnObjects = returnObjects.concat(this.nodes[3].retrieve(source));
  32506. }
  32507. }
  32508. return returnObjects;
  32509. },
  32510. /**
  32511. * Clear the quadtree.
  32512. * @method Phaser.QuadTree#clear
  32513. */
  32514. clear: function () {
  32515. this.objects.length = 0;
  32516. var i = this.nodes.length;
  32517. while (i--)
  32518. {
  32519. this.nodes[i].clear();
  32520. this.nodes.splice(i, 1);
  32521. }
  32522. this.nodes.length = 0;
  32523. }
  32524. };
  32525. Phaser.QuadTree.prototype.constructor = Phaser.QuadTree;
  32526. /**
  32527. * @author Richard Davey <rich@photonstorm.com>
  32528. * @copyright 2014 Photon Storm Ltd.
  32529. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  32530. */
  32531. /**
  32532. * Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation.
  32533. *
  32534. * @class Phaser.Net
  32535. * @constructor
  32536. * @param {Phaser.Game} game - A reference to the currently running game.
  32537. */
  32538. Phaser.Net = function (game) {
  32539. this.game = game;
  32540. };
  32541. Phaser.Net.prototype = {
  32542. /**
  32543. * Returns the hostname given by the browser.
  32544. *
  32545. * @method Phaser.Net#getHostName
  32546. * @return {string}
  32547. */
  32548. getHostName: function () {
  32549. if (window.location && window.location.hostname) {
  32550. return window.location.hostname;
  32551. }
  32552. return null;
  32553. },
  32554. /**
  32555. * Compares the given domain name against the hostname of the browser containing the game.
  32556. * If the domain name is found it returns true.
  32557. * You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc.
  32558. * Do not include 'http://' at the start.
  32559. *
  32560. * @method Phaser.Net#checkDomainName
  32561. * @param {string} domain
  32562. * @return {boolean} true if the given domain fragment can be found in the window.location.hostname
  32563. */
  32564. checkDomainName: function (domain) {
  32565. return window.location.hostname.indexOf(domain) !== -1;
  32566. },
  32567. /**
  32568. * Updates a value on the Query String and returns it in full.
  32569. * If the value doesn't already exist it is set.
  32570. * 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.
  32571. * Optionally you can redirect to the new url, or just return it as a string.
  32572. *
  32573. * @method Phaser.Net#updateQueryString
  32574. * @param {string} key - The querystring key to update.
  32575. * @param {string} value - The new value to be set. If it already exists it will be replaced.
  32576. * @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring.
  32577. * @param {string} url - The URL to modify. If none is given it uses window.location.href.
  32578. * @return {string} If redirect is false then the modified url and query string is returned.
  32579. */
  32580. updateQueryString: function (key, value, redirect, url) {
  32581. if (typeof redirect === "undefined") { redirect = false; }
  32582. if (typeof url === "undefined" || url === '') { url = window.location.href; }
  32583. var output = '';
  32584. var re = new RegExp("([?|&])" + key + "=.*?(&|#|$)(.*)", "gi");
  32585. if (re.test(url))
  32586. {
  32587. if (typeof value !== 'undefined' && value !== null)
  32588. {
  32589. output = url.replace(re, '$1' + key + "=" + value + '$2$3');
  32590. }
  32591. else
  32592. {
  32593. output = url.replace(re, '$1$3').replace(/(&|\?)$/, '');
  32594. }
  32595. }
  32596. else
  32597. {
  32598. if (typeof value !== 'undefined' && value !== null)
  32599. {
  32600. var separator = url.indexOf('?') !== -1 ? '&' : '?';
  32601. var hash = url.split('#');
  32602. url = hash[0] + separator + key + '=' + value;
  32603. if (hash[1]) {
  32604. url += '#' + hash[1];
  32605. }
  32606. output = url;
  32607. }
  32608. else
  32609. {
  32610. output = url;
  32611. }
  32612. }
  32613. if (redirect)
  32614. {
  32615. window.location.href = output;
  32616. }
  32617. else
  32618. {
  32619. return output;
  32620. }
  32621. },
  32622. /**
  32623. * Returns the Query String as an object.
  32624. * If you specify a parameter it will return just the value of that parameter, should it exist.
  32625. *
  32626. * @method Phaser.Net#getQueryString
  32627. * @param {string} [parameter=''] - If specified this will return just the value for that key.
  32628. * @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given.
  32629. */
  32630. getQueryString: function (parameter) {
  32631. if (typeof parameter === "undefined") { parameter = ''; }
  32632. var output = {};
  32633. var keyValues = location.search.substring(1).split('&');
  32634. for (var i in keyValues)
  32635. {
  32636. var key = keyValues[i].split('=');
  32637. if (key.length > 1)
  32638. {
  32639. if (parameter && parameter == this.decodeURI(key[0]))
  32640. {
  32641. return this.decodeURI(key[1]);
  32642. }
  32643. else
  32644. {
  32645. output[this.decodeURI(key[0])] = this.decodeURI(key[1]);
  32646. }
  32647. }
  32648. }
  32649. return output;
  32650. },
  32651. /**
  32652. * Returns the Query String as an object.
  32653. * If you specify a parameter it will return just the value of that parameter, should it exist.
  32654. *
  32655. * @method Phaser.Net#decodeURI
  32656. * @param {string} value - The URI component to be decoded.
  32657. * @return {string} The decoded value.
  32658. */
  32659. decodeURI: function (value) {
  32660. return decodeURIComponent(value.replace(/\+/g, " "));
  32661. }
  32662. };
  32663. Phaser.Net.prototype.constructor = Phaser.Net;
  32664. /**
  32665. * @author Richard Davey <rich@photonstorm.com>
  32666. * @copyright 2014 Photon Storm Ltd.
  32667. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  32668. */
  32669. /**
  32670. * Phaser - TweenManager
  32671. *
  32672. * @class Phaser.TweenManager
  32673. * @classdesc
  32674. * Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated.
  32675. * Tweens are hooked into the game clock and pause system, adjusting based on the game state.
  32676. *
  32677. * TweenManager is based heavily on tween.js by http://soledadpenades.com.
  32678. * The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object.
  32679. * It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors.
  32680. * Please see https://github.com/sole/tween.js for a full list of contributors.
  32681. * @constructor
  32682. *
  32683. * @param {Phaser.Game} game - A reference to the currently running game.
  32684. */
  32685. Phaser.TweenManager = function (game) {
  32686. /**
  32687. * @property {Phaser.Game} game - Local reference to game.
  32688. */
  32689. this.game = game;
  32690. /**
  32691. * @property {array<Phaser.Tween>} _tweens - All of the currently running tweens.
  32692. * @private
  32693. */
  32694. this._tweens = [];
  32695. /**
  32696. * @property {array<Phaser.Tween>} _add - All of the tweens queued to be added in the next update.
  32697. * @private
  32698. */
  32699. this._add = [];
  32700. this.game.onPause.add(this._pauseAll, this);
  32701. this.game.onResume.add(this._resumeAll, this);
  32702. };
  32703. Phaser.TweenManager.prototype = {
  32704. /**
  32705. * Get all the tween objects in an array.
  32706. * @method Phaser.TweenManager#getAll
  32707. * @returns {Phaser.Tween[]} Array with all tween objects.
  32708. */
  32709. getAll: function () {
  32710. return this._tweens;
  32711. },
  32712. /**
  32713. * Remove all tweens running and in the queue. Doesn't call any of the tween onComplete events.
  32714. * @method Phaser.TweenManager#removeAll
  32715. */
  32716. removeAll: function () {
  32717. for (var i = 0; i < this._tweens.length; i++)
  32718. {
  32719. this._tweens[i].pendingDelete = true;
  32720. }
  32721. this._add = [];
  32722. },
  32723. /**
  32724. * Add a new tween into the TweenManager.
  32725. *
  32726. * @method Phaser.TweenManager#add
  32727. * @param {Phaser.Tween} tween - The tween object you want to add.
  32728. * @returns {Phaser.Tween} The tween object you added to the manager.
  32729. */
  32730. add: function (tween) {
  32731. tween._manager = this;
  32732. this._add.push(tween);
  32733. },
  32734. /**
  32735. * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite.
  32736. *
  32737. * @method Phaser.TweenManager#create
  32738. * @param {Object} object - Object the tween will be run on.
  32739. * @returns {Phaser.Tween} The newly created tween object.
  32740. */
  32741. create: function (object) {
  32742. return new Phaser.Tween(object, this.game, this);
  32743. },
  32744. /**
  32745. * Remove a tween from this manager.
  32746. *
  32747. * @method Phaser.TweenManager#remove
  32748. * @param {Phaser.Tween} tween - The tween object you want to remove.
  32749. */
  32750. remove: function (tween) {
  32751. var i = this._tweens.indexOf(tween);
  32752. if (i !== -1)
  32753. {
  32754. this._tweens[i].pendingDelete = true;
  32755. }
  32756. else
  32757. {
  32758. i = this._add.indexOf(tween);
  32759. if (i !== -1)
  32760. {
  32761. this._add[i].pendingDelete = true;
  32762. }
  32763. }
  32764. },
  32765. /**
  32766. * Update all the tween objects you added to this manager.
  32767. *
  32768. * @method Phaser.TweenManager#update
  32769. * @returns {boolean} Return false if there's no tween to update, otherwise return true.
  32770. */
  32771. update: function () {
  32772. var addTweens = this._add.length;
  32773. var numTweens = this._tweens.length;
  32774. if (numTweens === 0 && addTweens === 0)
  32775. {
  32776. return false;
  32777. }
  32778. var i = 0;
  32779. while (i < numTweens)
  32780. {
  32781. if (this._tweens[i].update(this.game.time.now))
  32782. {
  32783. i++;
  32784. }
  32785. else
  32786. {
  32787. this._tweens.splice(i, 1);
  32788. numTweens--;
  32789. }
  32790. }
  32791. // If there are any new tweens to be added, do so now - otherwise they can be spliced out of the array before ever running
  32792. if (addTweens > 0)
  32793. {
  32794. this._tweens = this._tweens.concat(this._add);
  32795. this._add.length = 0;
  32796. }
  32797. return true;
  32798. },
  32799. /**
  32800. * Checks to see if a particular Sprite is currently being tweened.
  32801. *
  32802. * @method Phaser.TweenManager#isTweening
  32803. * @param {object} object - The object to check for tweens against.
  32804. * @returns {boolean} Returns true if the object is currently being tweened, false if not.
  32805. */
  32806. isTweening: function(object) {
  32807. return this._tweens.some(function(tween) {
  32808. return tween._object === object;
  32809. });
  32810. },
  32811. /**
  32812. * Private. Called by game focus loss. Pauses all currently running tweens.
  32813. *
  32814. * @method Phaser.TweenManager#_pauseAll
  32815. * @private
  32816. */
  32817. _pauseAll: function () {
  32818. for (var i = this._tweens.length - 1; i >= 0; i--)
  32819. {
  32820. this._tweens[i]._pause();
  32821. }
  32822. },
  32823. /**
  32824. * Private. Called by game focus loss. Resumes all currently paused tweens.
  32825. *
  32826. * @method Phaser.TweenManager#_resumeAll
  32827. * @private
  32828. */
  32829. _resumeAll: function () {
  32830. for (var i = this._tweens.length - 1; i >= 0; i--)
  32831. {
  32832. this._tweens[i]._resume();
  32833. }
  32834. },
  32835. /**
  32836. * Pauses all currently running tweens.
  32837. *
  32838. * @method Phaser.TweenManager#pauseAll
  32839. */
  32840. pauseAll: function () {
  32841. for (var i = this._tweens.length - 1; i >= 0; i--)
  32842. {
  32843. this._tweens[i].pause();
  32844. }
  32845. },
  32846. /**
  32847. * Resumes all currently paused tweens.
  32848. *
  32849. * @method Phaser.TweenManager#resumeAll
  32850. */
  32851. resumeAll: function () {
  32852. for (var i = this._tweens.length - 1; i >= 0; i--)
  32853. {
  32854. this._tweens[i].resume(true);
  32855. }
  32856. }
  32857. };
  32858. Phaser.TweenManager.prototype.constructor = Phaser.TweenManager;
  32859. /**
  32860. * @author Richard Davey <rich@photonstorm.com>
  32861. * @copyright 2014 Photon Storm Ltd.
  32862. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  32863. */
  32864. /**
  32865. * Tween constructor
  32866. * Create a new <code>Tween</code>.
  32867. *
  32868. * @class Phaser.Tween
  32869. * @constructor
  32870. * @param {object} object - Target object will be affected by this tween.
  32871. * @param {Phaser.Game} game - Current game instance.
  32872. * @param {Phaser.TweenManager} manager - The TweenManager responsible for looking after this Tween.
  32873. */
  32874. Phaser.Tween = function (object, game, manager) {
  32875. /**
  32876. * Reference to the target object.
  32877. * @property {object} _object
  32878. * @private
  32879. */
  32880. this._object = object;
  32881. /**
  32882. * @property {Phaser.Game} game - A reference to the currently running Game.
  32883. */
  32884. this.game = game;
  32885. /**
  32886. * @property {Phaser.TweenManager} _manager - Reference to the TweenManager.
  32887. * @private
  32888. */
  32889. this._manager = manager;
  32890. /**
  32891. * @property {object} _valuesStart - Private value object.
  32892. * @private
  32893. */
  32894. this._valuesStart = {};
  32895. /**
  32896. * @property {object} _valuesEnd - Private value object.
  32897. * @private
  32898. */
  32899. this._valuesEnd = {};
  32900. /**
  32901. * @property {object} _valuesStartRepeat - Private value object.
  32902. * @private
  32903. */
  32904. this._valuesStartRepeat = {};
  32905. /**
  32906. * @property {number} _duration - Private duration counter.
  32907. * @private
  32908. * @default
  32909. */
  32910. this._duration = 1000;
  32911. /**
  32912. * @property {number} _repeat - Private repeat counter.
  32913. * @private
  32914. * @default
  32915. */
  32916. this._repeat = 0;
  32917. /**
  32918. * @property {boolean} _yoyo - Private yoyo flag.
  32919. * @private
  32920. * @default
  32921. */
  32922. this._yoyo = false;
  32923. /**
  32924. * @property {boolean} _reversed - Private reversed flag.
  32925. * @private
  32926. * @default
  32927. */
  32928. this._reversed = false;
  32929. /**
  32930. * @property {number} _delayTime - Private delay counter.
  32931. * @private
  32932. * @default
  32933. */
  32934. this._delayTime = 0;
  32935. /**
  32936. * @property {number} _startTime - Private start time counter.
  32937. * @private
  32938. * @default null
  32939. */
  32940. this._startTime = null;
  32941. /**
  32942. * @property {function} _easingFunction - The easing function used for the tween.
  32943. * @private
  32944. */
  32945. this._easingFunction = Phaser.Easing.Linear.None;
  32946. /**
  32947. * @property {function} _interpolationFunction - The interpolation function used for the tween.
  32948. * @private
  32949. */
  32950. this._interpolationFunction = Phaser.Math.linearInterpolation;
  32951. /**
  32952. * @property {array} _chainedTweens - A private array of chained tweens.
  32953. * @private
  32954. */
  32955. this._chainedTweens = [];
  32956. /**
  32957. * @property {boolean} _onStartCallbackFired - Private flag.
  32958. * @private
  32959. * @default
  32960. */
  32961. this._onStartCallbackFired = false;
  32962. /**
  32963. * @property {function} _onUpdateCallback - An onUpdate callback.
  32964. * @private
  32965. * @default null
  32966. */
  32967. this._onUpdateCallback = null;
  32968. /**
  32969. * @property {object} _onUpdateCallbackContext - The context in which to call the onUpdate callback.
  32970. * @private
  32971. * @default null
  32972. */
  32973. this._onUpdateCallbackContext = null;
  32974. /**
  32975. * @property {boolean} _paused - Is this Tween paused or not?
  32976. * @private
  32977. * @default
  32978. */
  32979. this._paused = false;
  32980. /**
  32981. * @property {number} _pausedTime - Private pause timer.
  32982. * @private
  32983. * @default
  32984. */
  32985. this._pausedTime = 0;
  32986. /**
  32987. * @property {boolean} _codePaused - Was the Tween paused by code or by Game focus loss?
  32988. * @private
  32989. */
  32990. this._codePaused = false;
  32991. /**
  32992. * @property {boolean} pendingDelete - If this tween is ready to be deleted by the TweenManager.
  32993. * @default
  32994. */
  32995. this.pendingDelete = false;
  32996. // Set all starting values present on the target object - why? this will copy loads of properties we don't need - commenting out for now
  32997. // for (var field in object)
  32998. // {
  32999. // this._valuesStart[field] = parseFloat(object[field], 10);
  33000. // }
  33001. /**
  33002. * @property {Phaser.Signal} onStart - The onStart event is fired when the Tween begins.
  33003. */
  33004. this.onStart = new Phaser.Signal();
  33005. /**
  33006. * @property {Phaser.Signal} onLoop - The onLoop event is fired if the Tween loops.
  33007. */
  33008. this.onLoop = new Phaser.Signal();
  33009. /**
  33010. * @property {Phaser.Signal} onComplete - The onComplete event is fired when the Tween completes. Does not fire if the Tween is set to loop.
  33011. */
  33012. this.onComplete = new Phaser.Signal();
  33013. /**
  33014. * @property {boolean} isRunning - If the tween is running this is set to true, otherwise false. Tweens that are in a delayed state, waiting to start, are considered as being running.
  33015. * @default
  33016. */
  33017. this.isRunning = false;
  33018. };
  33019. Phaser.Tween.prototype = {
  33020. /**
  33021. * 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.
  33022. * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`.
  33023. *
  33024. * @method Phaser.Tween#to
  33025. * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object.
  33026. * @param {number} [duration=1000] - Duration of this tween in ms.
  33027. * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Linear.None.
  33028. * @param {boolean} [autoStart=false] - Whether this tween will start automatically or not.
  33029. * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms.
  33030. * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as Number.MAX_VALUE. This ignores any chained tweens.
  33031. * @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.
  33032. * @return {Phaser.Tween} This Tween object.
  33033. */
  33034. to: function (properties, duration, ease, autoStart, delay, repeat, yoyo) {
  33035. duration = duration || 1000;
  33036. ease = ease || null;
  33037. autoStart = autoStart || false;
  33038. delay = delay || 0;
  33039. repeat = repeat || 0;
  33040. yoyo = yoyo || false;
  33041. if (yoyo && repeat === 0)
  33042. {
  33043. repeat = 1;
  33044. }
  33045. var self;
  33046. if (this._parent)
  33047. {
  33048. self = this._manager.create(this._object);
  33049. this._lastChild.chain(self);
  33050. this._lastChild = self;
  33051. }
  33052. else
  33053. {
  33054. self = this;
  33055. this._parent = this;
  33056. this._lastChild = this;
  33057. }
  33058. self._repeat = repeat;
  33059. self._duration = duration;
  33060. self._valuesEnd = properties;
  33061. if (ease !== null)
  33062. {
  33063. self._easingFunction = ease;
  33064. }
  33065. if (delay > 0)
  33066. {
  33067. self._delayTime = delay;
  33068. }
  33069. self._yoyo = yoyo;
  33070. if (autoStart)
  33071. {
  33072. return this.start();
  33073. }
  33074. else
  33075. {
  33076. return this;
  33077. }
  33078. },
  33079. /**
  33080. * Sets this tween to be a `from` tween on the properties given. A `from` tween starts at the given value and tweens to the current values.
  33081. * For example a Sprite with an `x` coordinate of 100 could be tweened from `x: 200` by giving a properties object of `{ x: 200 }`.
  33082. *
  33083. * @method Phaser.Tween#from
  33084. * @param {object} properties - Properties you want to tween from.
  33085. * @param {number} [duration=1000] - Duration of this tween in ms.
  33086. * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Linear.None.
  33087. * @param {boolean} [autoStart=false] - Whether this tween will start automatically or not.
  33088. * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms.
  33089. * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as Number.MAX_VALUE. This ignores any chained tweens.
  33090. * @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.
  33091. * @return {Phaser.Tween} This Tween object.
  33092. */
  33093. from: function(properties, duration, ease, autoStart, delay, repeat, yoyo) {
  33094. var _cache = {};
  33095. for (var prop in properties)
  33096. {
  33097. _cache[prop] = this._object[prop];
  33098. this._object[prop] = properties[prop];
  33099. }
  33100. return this.to(_cache, duration, ease, autoStart, delay, repeat, yoyo);
  33101. },
  33102. /**
  33103. * Starts the tween running. Can also be called by the autoStart parameter of Tween.to.
  33104. *
  33105. * @method Phaser.Tween#start
  33106. * @return {Phaser.Tween} Itself.
  33107. */
  33108. start: function () {
  33109. if (this.game === null || this._object === null)
  33110. {
  33111. return;
  33112. }
  33113. this._manager.add(this);
  33114. this.isRunning = true;
  33115. this._onStartCallbackFired = false;
  33116. this._startTime = this.game.time.now + this._delayTime;
  33117. for (var property in this._valuesEnd)
  33118. {
  33119. // check if an Array was provided as property value
  33120. if (Array.isArray(this._valuesEnd[property]))
  33121. {
  33122. if (this._valuesEnd[property].length === 0)
  33123. {
  33124. continue;
  33125. }
  33126. // create a local copy of the Array with the start value at the front
  33127. this._valuesEnd[property] = [this._object[property]].concat(this._valuesEnd[property]);
  33128. }
  33129. this._valuesStart[property] = this._object[property];
  33130. if (!Array.isArray(this._valuesStart[property]))
  33131. {
  33132. this._valuesStart[property] *= 1.0; // Ensures we're using numbers, not strings
  33133. }
  33134. this._valuesStartRepeat[property] = this._valuesStart[property] || 0;
  33135. }
  33136. return this;
  33137. },
  33138. /**
  33139. * This will generate an array populated with the tweened object values from start to end.
  33140. * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and similar functions.
  33141. * It ignores delay and repeat counts and any chained tweens. Just one play through of tween data is returned, including yoyo if set.
  33142. *
  33143. * @method Phaser.Tween#generateData
  33144. * @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.
  33145. * @param {array} [data] - If given the generated data will be appended to this array, otherwise a new array will be returned.
  33146. * @return {array} An array of tweened values.
  33147. */
  33148. generateData: function (frameRate, data) {
  33149. if (this.game === null || this._object === null)
  33150. {
  33151. return null;
  33152. }
  33153. this._startTime = 0;
  33154. for (var property in this._valuesEnd)
  33155. {
  33156. // Check if an Array was provided as property value
  33157. if (Array.isArray(this._valuesEnd[property]))
  33158. {
  33159. if (this._valuesEnd[property].length === 0)
  33160. {
  33161. continue;
  33162. }
  33163. // create a local copy of the Array with the start value at the front
  33164. this._valuesEnd[property] = [this._object[property]].concat(this._valuesEnd[property]);
  33165. }
  33166. this._valuesStart[property] = this._object[property];
  33167. if (!Array.isArray(this._valuesStart[property]))
  33168. {
  33169. this._valuesStart[property] *= 1.0; // Ensures we're using numbers, not strings
  33170. }
  33171. this._valuesStartRepeat[property] = this._valuesStart[property] || 0;
  33172. }
  33173. // Simulate the tween. We will run for frameRate * (this._duration / 1000) (ms)
  33174. var time = 0;
  33175. var total = Math.floor(frameRate * (this._duration / 1000));
  33176. var tick = this._duration / total;
  33177. var output = [];
  33178. while (total--)
  33179. {
  33180. var property;
  33181. var elapsed = (time - this._startTime) / this._duration;
  33182. elapsed = elapsed > 1 ? 1 : elapsed;
  33183. var value = this._easingFunction(elapsed);
  33184. var blob = {};
  33185. for (property in this._valuesEnd)
  33186. {
  33187. var start = this._valuesStart[property] || 0;
  33188. var end = this._valuesEnd[property];
  33189. if (end instanceof Array)
  33190. {
  33191. blob[property] = this._interpolationFunction(end, value);
  33192. }
  33193. else
  33194. {
  33195. // Parses relative end values with start as base (e.g.: +10, -3)
  33196. if (typeof(end) === 'string')
  33197. {
  33198. end = start + parseFloat(end, 10);
  33199. }
  33200. // protect against non numeric properties.
  33201. if (typeof(end) === 'number')
  33202. {
  33203. blob[property] = start + ( end - start ) * value;
  33204. }
  33205. }
  33206. }
  33207. output.push(blob);
  33208. time += tick;
  33209. }
  33210. if (this._yoyo)
  33211. {
  33212. var reversed = output.slice();
  33213. reversed.reverse();
  33214. output = output.concat(reversed);
  33215. }
  33216. if (typeof data !== 'undefined')
  33217. {
  33218. data = data.concat(output);
  33219. return data;
  33220. }
  33221. else
  33222. {
  33223. return output;
  33224. }
  33225. },
  33226. /**
  33227. * Stops the tween if running and removes it from the TweenManager. If there are any onComplete callbacks or events they are not dispatched.
  33228. *
  33229. * @method Phaser.Tween#stop
  33230. * @return {Phaser.Tween} Itself.
  33231. */
  33232. stop: function () {
  33233. this.isRunning = false;
  33234. this._onUpdateCallback = null;
  33235. this._manager.remove(this);
  33236. return this;
  33237. },
  33238. /**
  33239. * Sets a delay time before this tween will start.
  33240. *
  33241. * @method Phaser.Tween#delay
  33242. * @param {number} amount - The amount of the delay in ms.
  33243. * @return {Phaser.Tween} Itself.
  33244. */
  33245. delay: function (amount) {
  33246. this._delayTime = amount;
  33247. return this;
  33248. },
  33249. /**
  33250. * Sets the number of times this tween will repeat.
  33251. *
  33252. * @method Phaser.Tween#repeat
  33253. * @param {number} times - How many times to repeat.
  33254. * @return {Phaser.Tween} Itself.
  33255. */
  33256. repeat: function (times) {
  33257. this._repeat = times;
  33258. return this;
  33259. },
  33260. /**
  33261. * A tween that has yoyo set to true will run through from start to finish, then reverse from finish to start.
  33262. * Used in combination with repeat you can create endless loops.
  33263. *
  33264. * @method Phaser.Tween#yoyo
  33265. * @param {boolean} yoyo - Set to true to yoyo this tween.
  33266. * @return {Phaser.Tween} Itself.
  33267. */
  33268. yoyo: function(yoyo) {
  33269. this._yoyo = yoyo;
  33270. if (yoyo && this._repeat === 0)
  33271. {
  33272. this._repeat = 1;
  33273. }
  33274. return this;
  33275. },
  33276. /**
  33277. * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None.
  33278. *
  33279. * @method Phaser.Tween#easing
  33280. * @param {function} easing - The easing function this tween will use, i.e. Phaser.Easing.Linear.None.
  33281. * @return {Phaser.Tween} Itself.
  33282. */
  33283. easing: function (easing) {
  33284. this._easingFunction = easing;
  33285. return this;
  33286. },
  33287. /**
  33288. * Set interpolation function the tween will use, by default it uses Phaser.Math.linearInterpolation.
  33289. * Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation.
  33290. *
  33291. * @method Phaser.Tween#interpolation
  33292. * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default)
  33293. * @return {Phaser.Tween} Itself.
  33294. */
  33295. interpolation: function (interpolation) {
  33296. this._interpolationFunction = interpolation;
  33297. return this;
  33298. },
  33299. /**
  33300. * You can chain tweens together by passing a reference to the chain function. This enables one tween to call another on completion.
  33301. * You can pass as many tweens as you like to this function, they will each be chained in sequence.
  33302. *
  33303. * @method Phaser.Tween#chain
  33304. * @return {Phaser.Tween} Itself.
  33305. */
  33306. chain: function () {
  33307. this._chainedTweens = arguments;
  33308. return this;
  33309. },
  33310. /**
  33311. * Loop a chain of tweens
  33312. *
  33313. * Usage:
  33314. * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true)
  33315. * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None)
  33316. * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None)
  33317. * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None)
  33318. * .loop();
  33319. * @method Phaser.Tween#loop
  33320. * @return {Phaser.Tween} Itself.
  33321. */
  33322. loop: function() {
  33323. this._lastChild.chain(this);
  33324. return this;
  33325. },
  33326. /**
  33327. * Sets a callback to be fired each time this tween updates.
  33328. *
  33329. * @method Phaser.Tween#onUpdateCallback
  33330. * @param {function} callback - The callback to invoke each time this tween is updated.
  33331. * @param {object} callbackContext - The context in which to call the onUpdate callback.
  33332. * @return {Phaser.Tween} Itself.
  33333. */
  33334. onUpdateCallback: function (callback, callbackContext) {
  33335. this._onUpdateCallback = callback;
  33336. this._onUpdateCallbackContext = callbackContext;
  33337. return this;
  33338. },
  33339. /**
  33340. * Pauses the tween.
  33341. *
  33342. * @method Phaser.Tween#pause
  33343. */
  33344. pause: function () {
  33345. this._codePaused = true;
  33346. this._paused = true;
  33347. this._pausedTime = this.game.time.now;
  33348. },
  33349. /**
  33350. * This is called by the core Game loop. Do not call it directly, instead use Tween.pause.
  33351. * @method Phaser.Tween#_pause
  33352. * @private
  33353. */
  33354. _pause: function () {
  33355. if (!this._codePaused)
  33356. {
  33357. this._paused = true;
  33358. this._pausedTime = this.game.time.now;
  33359. }
  33360. },
  33361. /**
  33362. * Resumes a paused tween.
  33363. *
  33364. * @method Phaser.Tween#resume
  33365. */
  33366. resume: function () {
  33367. if (this._paused)
  33368. {
  33369. this._paused = false;
  33370. this._codePaused = false;
  33371. this._startTime += (this.game.time.now - this._pausedTime);
  33372. }
  33373. },
  33374. /**
  33375. * This is called by the core Game loop. Do not call it directly, instead use Tween.pause.
  33376. * @method Phaser.Tween#_resume
  33377. * @private
  33378. */
  33379. _resume: function () {
  33380. if (this._codePaused)
  33381. {
  33382. return;
  33383. }
  33384. else
  33385. {
  33386. this._startTime += this.game.time.pauseDuration;
  33387. this._paused = false;
  33388. }
  33389. },
  33390. /**
  33391. * Core tween update function called by the TweenManager. Does not need to be invoked directly.
  33392. *
  33393. * @method Phaser.Tween#update
  33394. * @param {number} time - A timestamp passed in by the TweenManager.
  33395. * @return {boolean} false if the tween has completed and should be deleted from the manager, otherwise true (still active).
  33396. */
  33397. update: function (time) {
  33398. if (this.pendingDelete)
  33399. {
  33400. return false;
  33401. }
  33402. if (this._paused || time < this._startTime)
  33403. {
  33404. return true;
  33405. }
  33406. var property;
  33407. if (time < this._startTime)
  33408. {
  33409. return true;
  33410. }
  33411. if (this._onStartCallbackFired === false)
  33412. {
  33413. this.onStart.dispatch(this._object);
  33414. this._onStartCallbackFired = true;
  33415. }
  33416. var elapsed = (time - this._startTime) / this._duration;
  33417. elapsed = elapsed > 1 ? 1 : elapsed;
  33418. var value = this._easingFunction(elapsed);
  33419. for (property in this._valuesEnd)
  33420. {
  33421. var start = this._valuesStart[property] || 0;
  33422. var end = this._valuesEnd[property];
  33423. if (end instanceof Array)
  33424. {
  33425. this._object[property] = this._interpolationFunction(end, value);
  33426. }
  33427. else
  33428. {
  33429. // Parses relative end values with start as base (e.g.: +10, -3)
  33430. if (typeof(end) === 'string')
  33431. {
  33432. end = start + parseFloat(end, 10);
  33433. }
  33434. // protect against non numeric properties.
  33435. if (typeof(end) === 'number')
  33436. {
  33437. this._object[property] = start + ( end - start ) * value;
  33438. }
  33439. }
  33440. }
  33441. if (this._onUpdateCallback !== null)
  33442. {
  33443. this._onUpdateCallback.call(this._onUpdateCallbackContext, this, value);
  33444. if (!this.isRunning)
  33445. {
  33446. return false;
  33447. }
  33448. }
  33449. if (elapsed == 1)
  33450. {
  33451. if (this._repeat > 0)
  33452. {
  33453. if (isFinite(this._repeat))
  33454. {
  33455. this._repeat--;
  33456. }
  33457. // reassign starting values, restart by making startTime = now
  33458. for (property in this._valuesStartRepeat)
  33459. {
  33460. if (typeof(this._valuesEnd[property]) === 'string')
  33461. {
  33462. this._valuesStartRepeat[property] = this._valuesStartRepeat[property] + parseFloat(this._valuesEnd[property], 10);
  33463. }
  33464. if (this._yoyo)
  33465. {
  33466. var tmp = this._valuesStartRepeat[property];
  33467. this._valuesStartRepeat[property] = this._valuesEnd[property];
  33468. this._valuesEnd[property] = tmp;
  33469. }
  33470. this._valuesStart[property] = this._valuesStartRepeat[property];
  33471. }
  33472. if (this._yoyo)
  33473. {
  33474. this._reversed = !this._reversed;
  33475. }
  33476. this._startTime = time + this._delayTime;
  33477. this.onLoop.dispatch(this._object);
  33478. return true;
  33479. }
  33480. else
  33481. {
  33482. this.isRunning = false;
  33483. this.onComplete.dispatch(this._object);
  33484. for (var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i ++)
  33485. {
  33486. this._chainedTweens[i].start(time);
  33487. }
  33488. return false;
  33489. }
  33490. }
  33491. return true;
  33492. }
  33493. };
  33494. Phaser.Tween.prototype.constructor = Phaser.Tween;
  33495. /* jshint curly: false */
  33496. /**
  33497. * @author Richard Davey <rich@photonstorm.com>
  33498. * @copyright 2014 Photon Storm Ltd.
  33499. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  33500. */
  33501. /**
  33502. * A collection of easing methods defining ease-in ease-out curves.
  33503. *
  33504. * @class Phaser.Easing
  33505. */
  33506. Phaser.Easing = {
  33507. /**
  33508. * Linear easing.
  33509. *
  33510. * @class Phaser.Easing.Linear
  33511. */
  33512. Linear: {
  33513. /**
  33514. * Ease-in.
  33515. *
  33516. * @method Phaser.Easing.Linear#In
  33517. * @param {number} k - The value to be tweened.
  33518. * @returns {number} k^2.
  33519. */
  33520. None: function ( k ) {
  33521. return k;
  33522. }
  33523. },
  33524. /**
  33525. * Quadratic easing.
  33526. *
  33527. * @class Phaser.Easing.Quadratic
  33528. */
  33529. Quadratic: {
  33530. /**
  33531. * Ease-in.
  33532. *
  33533. * @method Phaser.Easing.Quadratic#In
  33534. * @param {number} k - The value to be tweened.
  33535. * @returns {number} k^2.
  33536. */
  33537. In: function ( k ) {
  33538. return k * k;
  33539. },
  33540. /**
  33541. * Ease-out.
  33542. *
  33543. * @method Phaser.Easing.Quadratic#Out
  33544. * @param {number} k - The value to be tweened.
  33545. * @returns {number} k* (2-k).
  33546. */
  33547. Out: function ( k ) {
  33548. return k * ( 2 - k );
  33549. },
  33550. /**
  33551. * Ease-in/out.
  33552. *
  33553. * @method Phaser.Easing.Quadratic#InOut
  33554. * @param {number} k - The value to be tweened.
  33555. * @returns {number} The tweened value.
  33556. */
  33557. InOut: function ( k ) {
  33558. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
  33559. return - 0.5 * ( --k * ( k - 2 ) - 1 );
  33560. }
  33561. },
  33562. /**
  33563. * Cubic easing.
  33564. *
  33565. * @class Phaser.Easing.Cubic
  33566. */
  33567. Cubic: {
  33568. /**
  33569. * Cubic ease-in.
  33570. *
  33571. * @method Phaser.Easing.Cubic#In
  33572. * @param {number} k - The value to be tweened.
  33573. * @returns {number} The tweened value.
  33574. */
  33575. In: function ( k ) {
  33576. return k * k * k;
  33577. },
  33578. /**
  33579. * Cubic ease-out.
  33580. *
  33581. * @method Phaser.Easing.Cubic#Out
  33582. * @param {number} k - The value to be tweened.
  33583. * @returns {number} The tweened value.
  33584. */
  33585. Out: function ( k ) {
  33586. return --k * k * k + 1;
  33587. },
  33588. /**
  33589. * Cubic ease-in/out.
  33590. *
  33591. * @method Phaser.Easing.Cubic#InOut
  33592. * @param {number} k - The value to be tweened.
  33593. * @returns {number} The tweened value.
  33594. */
  33595. InOut: function ( k ) {
  33596. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k;
  33597. return 0.5 * ( ( k -= 2 ) * k * k + 2 );
  33598. }
  33599. },
  33600. /**
  33601. * Quartic easing.
  33602. *
  33603. * @class Phaser.Easing.Quartic
  33604. */
  33605. Quartic: {
  33606. /**
  33607. * Quartic ease-in.
  33608. *
  33609. * @method Phaser.Easing.Quartic#In
  33610. * @param {number} k - The value to be tweened.
  33611. * @returns {number} The tweened value.
  33612. */
  33613. In: function ( k ) {
  33614. return k * k * k * k;
  33615. },
  33616. /**
  33617. * Quartic ease-out.
  33618. *
  33619. * @method Phaser.Easing.Quartic#Out
  33620. * @param {number} k - The value to be tweened.
  33621. * @returns {number} The tweened value.
  33622. */
  33623. Out: function ( k ) {
  33624. return 1 - ( --k * k * k * k );
  33625. },
  33626. /**
  33627. * Quartic ease-in/out.
  33628. *
  33629. * @method Phaser.Easing.Quartic#InOut
  33630. * @param {number} k - The value to be tweened.
  33631. * @returns {number} The tweened value.
  33632. */
  33633. InOut: function ( k ) {
  33634. if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k;
  33635. return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 );
  33636. }
  33637. },
  33638. /**
  33639. * Quintic easing.
  33640. *
  33641. * @class Phaser.Easing.Quintic
  33642. */
  33643. Quintic: {
  33644. /**
  33645. * Quintic ease-in.
  33646. *
  33647. * @method Phaser.Easing.Quintic#In
  33648. * @param {number} k - The value to be tweened.
  33649. * @returns {number} The tweened value.
  33650. */
  33651. In: function ( k ) {
  33652. return k * k * k * k * k;
  33653. },
  33654. /**
  33655. * Quintic ease-out.
  33656. *
  33657. * @method Phaser.Easing.Quintic#Out
  33658. * @param {number} k - The value to be tweened.
  33659. * @returns {number} The tweened value.
  33660. */
  33661. Out: function ( k ) {
  33662. return --k * k * k * k * k + 1;
  33663. },
  33664. /**
  33665. * Quintic ease-in/out.
  33666. *
  33667. * @method Phaser.Easing.Quintic#InOut
  33668. * @param {number} k - The value to be tweened.
  33669. * @returns {number} The tweened value.
  33670. */
  33671. InOut: function ( k ) {
  33672. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k;
  33673. return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 );
  33674. }
  33675. },
  33676. /**
  33677. * Sinusoidal easing.
  33678. *
  33679. * @class Phaser.Easing.Sinusoidal
  33680. */
  33681. Sinusoidal: {
  33682. /**
  33683. * Sinusoidal ease-in.
  33684. *
  33685. * @method Phaser.Easing.Sinusoidal#In
  33686. * @param {number} k - The value to be tweened.
  33687. * @returns {number} The tweened value.
  33688. */
  33689. In: function ( k ) {
  33690. return 1 - Math.cos( k * Math.PI / 2 );
  33691. },
  33692. /**
  33693. * Sinusoidal ease-out.
  33694. *
  33695. * @method Phaser.Easing.Sinusoidal#Out
  33696. * @param {number} k - The value to be tweened.
  33697. * @returns {number} The tweened value.
  33698. */
  33699. Out: function ( k ) {
  33700. return Math.sin( k * Math.PI / 2 );
  33701. },
  33702. /**
  33703. * Sinusoidal ease-in/out.
  33704. *
  33705. * @method Phaser.Easing.Sinusoidal#InOut
  33706. * @param {number} k - The value to be tweened.
  33707. * @returns {number} The tweened value.
  33708. */
  33709. InOut: function ( k ) {
  33710. return 0.5 * ( 1 - Math.cos( Math.PI * k ) );
  33711. }
  33712. },
  33713. /**
  33714. * Exponential easing.
  33715. *
  33716. * @class Phaser.Easing.Exponential
  33717. */
  33718. Exponential: {
  33719. /**
  33720. * Exponential ease-in.
  33721. *
  33722. * @method Phaser.Easing.Exponential#In
  33723. * @param {number} k - The value to be tweened.
  33724. * @returns {number} The tweened value.
  33725. */
  33726. In: function ( k ) {
  33727. return k === 0 ? 0 : Math.pow( 1024, k - 1 );
  33728. },
  33729. /**
  33730. * Exponential ease-out.
  33731. *
  33732. * @method Phaser.Easing.Exponential#Out
  33733. * @param {number} k - The value to be tweened.
  33734. * @returns {number} The tweened value.
  33735. */
  33736. Out: function ( k ) {
  33737. return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k );
  33738. },
  33739. /**
  33740. * Exponential ease-in/out.
  33741. *
  33742. * @method Phaser.Easing.Exponential#InOut
  33743. * @param {number} k - The value to be tweened.
  33744. * @returns {number} The tweened value.
  33745. */
  33746. InOut: function ( k ) {
  33747. if ( k === 0 ) return 0;
  33748. if ( k === 1 ) return 1;
  33749. if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 );
  33750. return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 );
  33751. }
  33752. },
  33753. /**
  33754. * Circular easing.
  33755. *
  33756. * @class Phaser.Easing.Circular
  33757. */
  33758. Circular: {
  33759. /**
  33760. * Circular ease-in.
  33761. *
  33762. * @method Phaser.Easing.Circular#In
  33763. * @param {number} k - The value to be tweened.
  33764. * @returns {number} The tweened value.
  33765. */
  33766. In: function ( k ) {
  33767. return 1 - Math.sqrt( 1 - k * k );
  33768. },
  33769. /**
  33770. * Circular ease-out.
  33771. *
  33772. * @method Phaser.Easing.Circular#Out
  33773. * @param {number} k - The value to be tweened.
  33774. * @returns {number} The tweened value.
  33775. */
  33776. Out: function ( k ) {
  33777. return Math.sqrt( 1 - ( --k * k ) );
  33778. },
  33779. /**
  33780. * Circular ease-in/out.
  33781. *
  33782. * @method Phaser.Easing.Circular#InOut
  33783. * @param {number} k - The value to be tweened.
  33784. * @returns {number} The tweened value.
  33785. */
  33786. InOut: function ( k ) {
  33787. if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1);
  33788. return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1);
  33789. }
  33790. },
  33791. /**
  33792. * Elastic easing.
  33793. *
  33794. * @class Phaser.Easing.Elastic
  33795. */
  33796. Elastic: {
  33797. /**
  33798. * Elastic ease-in.
  33799. *
  33800. * @method Phaser.Easing.Elastic#In
  33801. * @param {number} k - The value to be tweened.
  33802. * @returns {number} The tweened value.
  33803. */
  33804. In: function ( k ) {
  33805. var s, a = 0.1, p = 0.4;
  33806. if ( k === 0 ) return 0;
  33807. if ( k === 1 ) return 1;
  33808. if ( !a || a < 1 ) { a = 1; s = p / 4; }
  33809. else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
  33810. return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) );
  33811. },
  33812. /**
  33813. * Elastic ease-out.
  33814. *
  33815. * @method Phaser.Easing.Elastic#Out
  33816. * @param {number} k - The value to be tweened.
  33817. * @returns {number} The tweened value.
  33818. */
  33819. Out: function ( k ) {
  33820. var s, a = 0.1, p = 0.4;
  33821. if ( k === 0 ) return 0;
  33822. if ( k === 1 ) return 1;
  33823. if ( !a || a < 1 ) { a = 1; s = p / 4; }
  33824. else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
  33825. return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 );
  33826. },
  33827. /**
  33828. * Elastic ease-in/out.
  33829. *
  33830. * @method Phaser.Easing.Elastic#InOut
  33831. * @param {number} k - The value to be tweened.
  33832. * @returns {number} The tweened value.
  33833. */
  33834. InOut: function ( k ) {
  33835. var s, a = 0.1, p = 0.4;
  33836. if ( k === 0 ) return 0;
  33837. if ( k === 1 ) return 1;
  33838. if ( !a || a < 1 ) { a = 1; s = p / 4; }
  33839. else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
  33840. if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) );
  33841. return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1;
  33842. }
  33843. },
  33844. /**
  33845. * Back easing.
  33846. *
  33847. * @class Phaser.Easing.Back
  33848. */
  33849. Back: {
  33850. /**
  33851. * Back ease-in.
  33852. *
  33853. * @method Phaser.Easing.Back#In
  33854. * @param {number} k - The value to be tweened.
  33855. * @returns {number} The tweened value.
  33856. */
  33857. In: function ( k ) {
  33858. var s = 1.70158;
  33859. return k * k * ( ( s + 1 ) * k - s );
  33860. },
  33861. /**
  33862. * Back ease-out.
  33863. *
  33864. * @method Phaser.Easing.Back#Out
  33865. * @param {number} k - The value to be tweened.
  33866. * @returns {number} The tweened value.
  33867. */
  33868. Out: function ( k ) {
  33869. var s = 1.70158;
  33870. return --k * k * ( ( s + 1 ) * k + s ) + 1;
  33871. },
  33872. /**
  33873. * Back ease-in/out.
  33874. *
  33875. * @method Phaser.Easing.Back#InOut
  33876. * @param {number} k - The value to be tweened.
  33877. * @returns {number} The tweened value.
  33878. */
  33879. InOut: function ( k ) {
  33880. var s = 1.70158 * 1.525;
  33881. if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) );
  33882. return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 );
  33883. }
  33884. },
  33885. /**
  33886. * Bounce easing.
  33887. *
  33888. * @class Phaser.Easing.Bounce
  33889. */
  33890. Bounce: {
  33891. /**
  33892. * Bounce ease-in.
  33893. *
  33894. * @method Phaser.Easing.Bounce#In
  33895. * @param {number} k - The value to be tweened.
  33896. * @returns {number} The tweened value.
  33897. */
  33898. In: function ( k ) {
  33899. return 1 - Phaser.Easing.Bounce.Out( 1 - k );
  33900. },
  33901. /**
  33902. * Bounce ease-out.
  33903. *
  33904. * @method Phaser.Easing.Bounce#Out
  33905. * @param {number} k - The value to be tweened.
  33906. * @returns {number} The tweened value.
  33907. */
  33908. Out: function ( k ) {
  33909. if ( k < ( 1 / 2.75 ) ) {
  33910. return 7.5625 * k * k;
  33911. } else if ( k < ( 2 / 2.75 ) ) {
  33912. return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75;
  33913. } else if ( k < ( 2.5 / 2.75 ) ) {
  33914. return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375;
  33915. } else {
  33916. return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375;
  33917. }
  33918. },
  33919. /**
  33920. * Bounce ease-in/out.
  33921. *
  33922. * @method Phaser.Easing.Bounce#InOut
  33923. * @param {number} k - The value to be tweened.
  33924. * @returns {number} The tweened value.
  33925. */
  33926. InOut: function ( k ) {
  33927. if ( k < 0.5 ) return Phaser.Easing.Bounce.In( k * 2 ) * 0.5;
  33928. return Phaser.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5;
  33929. }
  33930. }
  33931. };
  33932. /**
  33933. * @author Richard Davey <rich@photonstorm.com>
  33934. * @copyright 2014 Photon Storm Ltd.
  33935. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  33936. */
  33937. /**
  33938. * Time constructor.
  33939. *
  33940. * @class Phaser.Time
  33941. * @classdesc This is the core internal game clock. It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens.
  33942. * @constructor
  33943. * @param {Phaser.Game} game A reference to the currently running game.
  33944. */
  33945. Phaser.Time = function (game) {
  33946. /**
  33947. * @property {Phaser.Game} game - Local reference to game.
  33948. */
  33949. this.game = game;
  33950. /**
  33951. * @property {number} time - Game time counter. If you need a value for in-game calculation please use Phaser.Time.now instead.
  33952. * @protected
  33953. */
  33954. this.time = 0;
  33955. /**
  33956. * @property {number} now - The time right now.
  33957. * @protected
  33958. */
  33959. this.now = 0;
  33960. /**
  33961. * @property {number} elapsed - Elapsed time since the last frame (in ms).
  33962. * @protected
  33963. */
  33964. this.elapsed = 0;
  33965. /**
  33966. * @property {number} pausedTime - Records how long the game has been paused for. Is reset each time the game pauses.
  33967. * @protected
  33968. */
  33969. this.pausedTime = 0;
  33970. /**
  33971. * @property {boolean} advancedTiming - If true Phaser.Time will perform advanced profiling including the fps rate, fps min/max and msMin and msMax.
  33972. * @default
  33973. */
  33974. this.advancedTiming = false;
  33975. /**
  33976. * @property {number} fps - Frames per second. Only calculated if Time.advancedTiming is true.
  33977. * @protected
  33978. */
  33979. this.fps = 0;
  33980. /**
  33981. * @property {number} fpsMin - The lowest rate the fps has dropped to. Only calculated if Time.advancedTiming is true.
  33982. */
  33983. this.fpsMin = 1000;
  33984. /**
  33985. * @property {number} fpsMax - The highest rate the fps has reached (usually no higher than 60fps). Only calculated if Time.advancedTiming is true.
  33986. */
  33987. this.fpsMax = 0;
  33988. /**
  33989. * @property {number} msMin - The minimum amount of time the game has taken between two frames. Only calculated if Time.advancedTiming is true.
  33990. * @default
  33991. */
  33992. this.msMin = 1000;
  33993. /**
  33994. * @property {number} msMax - The maximum amount of time the game has taken between two frames. Only calculated if Time.advancedTiming is true.
  33995. */
  33996. this.msMax = 0;
  33997. /**
  33998. * @property {number} physicsElapsed - The elapsed time calculated for the physics motion updates. In a stable 60fps system this will be 0.016 every frame.
  33999. */
  34000. this.physicsElapsed = 0;
  34001. /**
  34002. * @property {number} deltaCap - If you need to cap the delta timer, set the value here. For 60fps the delta should be 0.016, so try variances just above this.
  34003. */
  34004. this.deltaCap = 0;
  34005. /**
  34006. * @property {number} timeCap - If the difference in time between two frame updates exceeds this value, the frame time is reset to avoid huge elapsed counts.
  34007. */
  34008. this.timeCap = 1000;
  34009. /**
  34010. * @property {number} frames - The number of frames record in the last second. Only calculated if Time.advancedTiming is true.
  34011. */
  34012. this.frames = 0;
  34013. /**
  34014. * @property {number} pauseDuration - Records how long the game was paused for in miliseconds.
  34015. */
  34016. this.pauseDuration = 0;
  34017. /**
  34018. * @property {number} timeToCall - The value that setTimeout needs to work out when to next update
  34019. */
  34020. this.timeToCall = 0;
  34021. /**
  34022. * @property {number} lastTime - Internal value used by timeToCall as part of the setTimeout loop
  34023. */
  34024. this.lastTime = 0;
  34025. /**
  34026. * @property {Phaser.Timer} events - This is a Phaser.Timer object bound to the master clock to which you can add timed events.
  34027. */
  34028. this.events = new Phaser.Timer(this.game, false);
  34029. /**
  34030. * @property {number} _started - The time at which the Game instance started.
  34031. * @private
  34032. */
  34033. this._started = 0;
  34034. /**
  34035. * @property {number} _timeLastSecond - The time (in ms) that the last second counter ticked over.
  34036. * @private
  34037. */
  34038. this._timeLastSecond = 0;
  34039. /**
  34040. * @property {number} _pauseStarted - The time the game started being paused.
  34041. * @private
  34042. */
  34043. this._pauseStarted = 0;
  34044. /**
  34045. * @property {boolean} _justResumed - Internal value used to recover from the game pause state.
  34046. * @private
  34047. */
  34048. this._justResumed = false;
  34049. /**
  34050. * @property {array} _timers - Internal store of Phaser.Timer objects.
  34051. * @private
  34052. */
  34053. this._timers = [];
  34054. /**
  34055. * @property {number} _len - Temp. array length variable.
  34056. * @private
  34057. */
  34058. this._len = 0;
  34059. /**
  34060. * @property {number} _i - Temp. array counter variable.
  34061. * @private
  34062. */
  34063. this._i = 0;
  34064. };
  34065. Phaser.Time.prototype = {
  34066. /**
  34067. * Called automatically by Phaser.Game after boot. Should not be called directly.
  34068. *
  34069. * @method Phaser.Time#boot
  34070. * @protected
  34071. */
  34072. boot: function () {
  34073. this._started = Date.now();
  34074. this.events.start();
  34075. },
  34076. /**
  34077. * Adds an existing Phaser.Timer object to the Timer pool.
  34078. *
  34079. * @method Phaser.Time#add
  34080. * @param {Phaser.Timer} timer - An existing Phaser.Timer object.
  34081. * @return {Phaser.Timer} The given Phaser.Timer object.
  34082. */
  34083. add: function (timer) {
  34084. this._timers.push(timer);
  34085. return timer;
  34086. },
  34087. /**
  34088. * Creates a new stand-alone Phaser.Timer object.
  34089. *
  34090. * @method Phaser.Time#create
  34091. * @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).
  34092. * @return {Phaser.Timer} The Timer object that was created.
  34093. */
  34094. create: function (autoDestroy) {
  34095. if (typeof autoDestroy === 'undefined') { autoDestroy = true; }
  34096. var timer = new Phaser.Timer(this.game, autoDestroy);
  34097. this._timers.push(timer);
  34098. return timer;
  34099. },
  34100. /**
  34101. * Remove all Timer objects, regardless of their state. Also clears all Timers from the Time.events timer.
  34102. *
  34103. * @method Phaser.Time#removeAll
  34104. */
  34105. removeAll: function () {
  34106. for (var i = 0; i < this._timers.length; i++)
  34107. {
  34108. this._timers[i].destroy();
  34109. }
  34110. this._timers = [];
  34111. this.events.removeAll();
  34112. },
  34113. /**
  34114. * Updates the game clock and if enabled the advanced timing data. This is called automatically by Phaser.Game.
  34115. *
  34116. * @method Phaser.Time#update
  34117. * @protected
  34118. * @param {number} time - The current timestamp.
  34119. */
  34120. update: function (time) {
  34121. this.now = time;
  34122. this.timeToCall = this.game.math.max(0, 16 - (time - this.lastTime));
  34123. this.elapsed = this.now - this.time;
  34124. // spike-dislike
  34125. if (this.elapsed > this.timeCap)
  34126. {
  34127. // For some reason the time between now and the last time the game was updated was larger than our timeCap
  34128. // This can happen if the Stage.disableVisibilityChange is true and you swap tabs, which makes the raf pause.
  34129. // In this case we'll drop to some default values to stop the game timers going nuts.
  34130. this.elapsed = 1 / 60;
  34131. }
  34132. // Calculate physics elapsed, ensure it's > 0, use 1/60 as a fallback
  34133. this.physicsElapsed = this.elapsed / 1000 || 1 / 60;
  34134. if (this.deltaCap > 0 && this.physicsElapsed > this.deltaCap)
  34135. {
  34136. this.physicsElapsed = this.deltaCap;
  34137. }
  34138. if (this.advancedTiming)
  34139. {
  34140. this.msMin = this.game.math.min(this.msMin, this.elapsed);
  34141. this.msMax = this.game.math.max(this.msMax, this.elapsed);
  34142. this.frames++;
  34143. if (this.now > this._timeLastSecond + 1000)
  34144. {
  34145. this.fps = Math.round((this.frames * 1000) / (this.now - this._timeLastSecond));
  34146. this.fpsMin = this.game.math.min(this.fpsMin, this.fps);
  34147. this.fpsMax = this.game.math.max(this.fpsMax, this.fps);
  34148. this._timeLastSecond = this.now;
  34149. this.frames = 0;
  34150. }
  34151. }
  34152. this.time = this.now;
  34153. this.lastTime = time + this.timeToCall;
  34154. // Paused but still running?
  34155. if (!this.game.paused)
  34156. {
  34157. // Our internal Phaser.Timer
  34158. this.events.update(this.now);
  34159. // Any game level timers
  34160. this._i = 0;
  34161. this._len = this._timers.length;
  34162. while (this._i < this._len)
  34163. {
  34164. if (this._timers[this._i].update(this.now))
  34165. {
  34166. this._i++;
  34167. }
  34168. else
  34169. {
  34170. this._timers.splice(this._i, 1);
  34171. this._len--;
  34172. }
  34173. }
  34174. }
  34175. },
  34176. /**
  34177. * Called when the game enters a paused state.
  34178. *
  34179. * @method Phaser.Time#gamePaused
  34180. * @private
  34181. */
  34182. gamePaused: function () {
  34183. this._pauseStarted = this.now;
  34184. this.events.pause();
  34185. var i = this._timers.length;
  34186. while (i--)
  34187. {
  34188. this._timers[i]._pause();
  34189. }
  34190. },
  34191. /**
  34192. * Called when the game resumes from a paused state.
  34193. *
  34194. * @method Phaser.Time#gameResumed
  34195. * @private
  34196. */
  34197. gameResumed: function () {
  34198. // Level out the elapsed timer to avoid spikes
  34199. this.time = this.now = Date.now();
  34200. this.pauseDuration = this.time - this._pauseStarted;
  34201. this.events.resume();
  34202. var i = this._timers.length;
  34203. while (i--)
  34204. {
  34205. this._timers[i]._resume();
  34206. }
  34207. },
  34208. /**
  34209. * The number of seconds that have elapsed since the game was started.
  34210. *
  34211. * @method Phaser.Time#totalElapsedSeconds
  34212. * @return {number} The number of seconds that have elapsed since the game was started.
  34213. */
  34214. totalElapsedSeconds: function() {
  34215. return (this.now - this._started) * 0.001;
  34216. },
  34217. /**
  34218. * How long has passed since the given time.
  34219. *
  34220. * @method Phaser.Time#elapsedSince
  34221. * @param {number} since - The time you want to measure against.
  34222. * @return {number} The difference between the given time and now.
  34223. */
  34224. elapsedSince: function (since) {
  34225. return this.now - since;
  34226. },
  34227. /**
  34228. * How long has passed since the given time (in seconds).
  34229. *
  34230. * @method Phaser.Time#elapsedSecondsSince
  34231. * @param {number} since - The time you want to measure (in seconds).
  34232. * @return {number} Duration between given time and now (in seconds).
  34233. */
  34234. elapsedSecondsSince: function (since) {
  34235. return (this.now - since) * 0.001;
  34236. },
  34237. /**
  34238. * Resets the private _started value to now and removes all currently running Timers.
  34239. *
  34240. * @method Phaser.Time#reset
  34241. */
  34242. reset: function () {
  34243. this._started = this.now;
  34244. this.removeAll();
  34245. }
  34246. };
  34247. Phaser.Time.prototype.constructor = Phaser.Time;
  34248. /**
  34249. * @author Richard Davey <rich@photonstorm.com>
  34250. * @copyright 2014 Photon Storm Ltd.
  34251. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  34252. */
  34253. /**
  34254. * A Timer is a way to create small re-usable or disposable objects that do nothing but wait for a specific moment in time, and then dispatch an event.
  34255. * You can add as many events to a Timer as you like, each with their own delays. A Timer uses milliseconds as its unit of time. There are 1000 ms in 1 second.
  34256. * So if you want to fire an event every quarter of a second you'd need to set the delay to 250.
  34257. *
  34258. * @class Phaser.Timer
  34259. * @classdesc A Timer is a way to create small re-usable or disposable objects that do nothing but wait for a specific moment in time, and then dispatch an event.
  34260. * @constructor
  34261. * @param {Phaser.Game} game A reference to the currently running game.
  34262. * @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).
  34263. */
  34264. Phaser.Timer = function (game, autoDestroy) {
  34265. if (typeof autoDestroy === 'undefined') { autoDestroy = true; }
  34266. /**
  34267. * @property {Phaser.Game} game - Local reference to game.
  34268. */
  34269. this.game = game;
  34270. /**
  34271. * @property {boolean} running - True if the Timer is actively running. Do not switch this boolean, if you wish to pause the timer then use Timer.pause() instead.
  34272. * @default
  34273. */
  34274. this.running = false;
  34275. /**
  34276. * @property {boolean} autoDestroy - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events).
  34277. */
  34278. this.autoDestroy = autoDestroy;
  34279. /**
  34280. * @property {boolean} expired - An expired Timer is one in which all of its events have been dispatched and none are pending.
  34281. * @readonly
  34282. * @default
  34283. */
  34284. this.expired = false;
  34285. /**
  34286. * @property {number} elapsed - Elapsed time since the last frame (in ms).
  34287. * @protected
  34288. */
  34289. this.elapsed = 0;
  34290. /**
  34291. * @property {array<Phaser.TimerEvent>} events - An array holding all of this timers Phaser.TimerEvent objects. Use the methods add, repeat and loop to populate it.
  34292. */
  34293. this.events = [];
  34294. /**
  34295. * @property {Phaser.Signal} onComplete - This signal will be dispatched when this Timer has completed, meaning there are no more events in the queue.
  34296. */
  34297. this.onComplete = new Phaser.Signal();
  34298. /**
  34299. * @property {number} nextTick - The time the next tick will occur.
  34300. * @readonly
  34301. * @protected
  34302. */
  34303. this.nextTick = 0;
  34304. /**
  34305. * @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.
  34306. */
  34307. this.timeCap = 1000;
  34308. /**
  34309. * @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.
  34310. * @readonly
  34311. * @default
  34312. */
  34313. this.paused = false;
  34314. /**
  34315. * @property {boolean} _codePaused - Was the Timer paused by code or by Game focus loss?
  34316. * @private
  34317. */
  34318. this._codePaused = false;
  34319. /**
  34320. * @property {number} _started - The time at which this Timer instance started running.
  34321. * @private
  34322. * @default
  34323. */
  34324. this._started = 0;
  34325. /**
  34326. * @property {number} _pauseStarted - The time the game started being paused.
  34327. * @private
  34328. */
  34329. this._pauseStarted = 0;
  34330. /**
  34331. * @property {number} _pauseTotal - Total paused time.
  34332. * @private
  34333. */
  34334. this._pauseTotal = 0;
  34335. /**
  34336. * @property {number} _now - The current start-time adjusted time.
  34337. * @private
  34338. */
  34339. this._now = Date.now();
  34340. /**
  34341. * @property {number} _len - Temp. array length variable.
  34342. * @private
  34343. */
  34344. this._len = 0;
  34345. /**
  34346. * @property {number} _marked - Temp. counter variable.
  34347. * @private
  34348. */
  34349. this._marked = 0;
  34350. /**
  34351. * @property {number} _i - Temp. array counter variable.
  34352. * @private
  34353. */
  34354. this._i = 0;
  34355. /**
  34356. * @property {number} _diff - Internal cache var.
  34357. * @private
  34358. */
  34359. this._diff = 0;
  34360. /**
  34361. * @property {number} _newTick - Internal cache var.
  34362. * @private
  34363. */
  34364. this._newTick = 0;
  34365. };
  34366. /**
  34367. * @constant
  34368. * @type {number}
  34369. */
  34370. Phaser.Timer.MINUTE = 60000;
  34371. /**
  34372. * @constant
  34373. * @type {number}
  34374. */
  34375. Phaser.Timer.SECOND = 1000;
  34376. /**
  34377. * @constant
  34378. * @type {number}
  34379. */
  34380. Phaser.Timer.HALF = 500;
  34381. /**
  34382. * @constant
  34383. * @type {number}
  34384. */
  34385. Phaser.Timer.QUARTER = 250;
  34386. Phaser.Timer.prototype = {
  34387. /**
  34388. * Creates a new TimerEvent on this Timer. Use the methods add, repeat or loop instead of this.
  34389. * @method Phaser.Timer#create
  34390. * @private
  34391. * @param {number} delay - The number of milliseconds that should elapse before the Timer will call the given callback.
  34392. * @param {boolean} loop - Should the event loop or not?
  34393. * @param {number} repeatCount - The number of times the event will repeat.
  34394. * @param {function} callback - The callback that will be called when the Timer event occurs.
  34395. * @param {object} callbackContext - The context in which the callback will be called.
  34396. * @param {array} arguments - The values to be sent to your callback function when it is called.
  34397. * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
  34398. */
  34399. create: function (delay, loop, repeatCount, callback, callbackContext, args) {
  34400. var tick = delay;
  34401. if (this._now === 0)
  34402. {
  34403. tick += this.game.time.now;
  34404. }
  34405. else
  34406. {
  34407. tick += this._now;
  34408. }
  34409. var event = new Phaser.TimerEvent(this, delay, tick, repeatCount, loop, callback, callbackContext, args);
  34410. this.events.push(event);
  34411. this.order();
  34412. this.expired = false;
  34413. return event;
  34414. },
  34415. /**
  34416. * Adds a new Event to this Timer. The event will fire after the given amount of 'delay' in milliseconds has passed, once the Timer has started running.
  34417. * Call Timer.start() once you have added all of the Events you require for this Timer. The delay is in relation to when the Timer starts, not the time it was added.
  34418. * If the Timer is already running the delay will be calculated based on the timers current time.
  34419. *
  34420. * @method Phaser.Timer#add
  34421. * @param {number} delay - The number of milliseconds that should elapse before the Timer will call the given callback.
  34422. * @param {function} callback - The callback that will be called when the Timer event occurs.
  34423. * @param {object} callbackContext - The context in which the callback will be called.
  34424. * @param {...*} arguments - The values to be sent to your callback function when it is called.
  34425. * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
  34426. */
  34427. add: function (delay, callback, callbackContext) {
  34428. return this.create(delay, false, 0, callback, callbackContext, Array.prototype.splice.call(arguments, 3));
  34429. },
  34430. /**
  34431. * Adds a new TimerEvent that will always play through once and then repeat for the given number of iterations.
  34432. * The event will fire after the given amount of 'delay' milliseconds has passed once the Timer has started running.
  34433. * Call Timer.start() once you have added all of the Events you require for this Timer. The delay is in relation to when the Timer starts, not the time it was added.
  34434. * If the Timer is already running the delay will be calculated based on the timers current time.
  34435. *
  34436. * @method Phaser.Timer#repeat
  34437. * @param {number} delay - The number of milliseconds that should elapse before the Timer will call the given callback.
  34438. * @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.
  34439. * @param {function} callback - The callback that will be called when the Timer event occurs.
  34440. * @param {object} callbackContext - The context in which the callback will be called.
  34441. * @param {...*} arguments - The values to be sent to your callback function when it is called.
  34442. * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
  34443. */
  34444. repeat: function (delay, repeatCount, callback, callbackContext) {
  34445. return this.create(delay, false, repeatCount, callback, callbackContext, Array.prototype.splice.call(arguments, 4));
  34446. },
  34447. /**
  34448. * Adds a new looped Event to this Timer that will repeat forever or until the Timer is stopped.
  34449. * The event will fire after the given amount of 'delay' milliseconds has passed once the Timer has started running.
  34450. * Call Timer.start() once you have added all of the Events you require for this Timer. The delay is in relation to when the Timer starts, not the time it was added.
  34451. * If the Timer is already running the delay will be calculated based on the timers current time.
  34452. *
  34453. * @method Phaser.Timer#loop
  34454. * @param {number} delay - The number of milliseconds that should elapse before the Timer will call the given callback.
  34455. * @param {function} callback - The callback that will be called when the Timer event occurs.
  34456. * @param {object} callbackContext - The context in which the callback will be called.
  34457. * @param {...*} arguments - The values to be sent to your callback function when it is called.
  34458. * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
  34459. */
  34460. loop: function (delay, callback, callbackContext) {
  34461. return this.create(delay, true, 0, callback, callbackContext, Array.prototype.splice.call(arguments, 3));
  34462. },
  34463. /**
  34464. * Starts this Timer running.
  34465. * @method Phaser.Timer#start
  34466. * @param {number} [delay=0] - The number of milliseconds that should elapse before the Timer will start.
  34467. */
  34468. start: function (delay) {
  34469. if (this.running)
  34470. {
  34471. return;
  34472. }
  34473. this._started = this.game.time.now + (delay || 0);
  34474. this.running = true;
  34475. for (var i = 0; i < this.events.length; i++)
  34476. {
  34477. this.events[i].tick = this.events[i].delay + this._started;
  34478. }
  34479. },
  34480. /**
  34481. * Stops this Timer from running. Does not cause it to be destroyed if autoDestroy is set to true.
  34482. * @method Phaser.Timer#stop
  34483. * @param {boolean} [clearEvents=true] - If true all the events in Timer will be cleared, otherwise they will remain.
  34484. */
  34485. stop: function (clearEvents) {
  34486. this.running = false;
  34487. if (typeof clearEvents === 'undefined') { clearEvents = true; }
  34488. if (clearEvents)
  34489. {
  34490. this.events.length = 0;
  34491. }
  34492. },
  34493. /**
  34494. * Removes a pending TimerEvent from the queue.
  34495. * @param {Phaser.TimerEvent} event - The event to remove from the queue.
  34496. * @method Phaser.Timer#remove
  34497. */
  34498. remove: function (event) {
  34499. for (var i = 0; i < this.events.length; i++)
  34500. {
  34501. if (this.events[i] === event)
  34502. {
  34503. this.events[i].pendingDelete = true;
  34504. return true;
  34505. }
  34506. }
  34507. return false;
  34508. },
  34509. /**
  34510. * Orders the events on this Timer so they are in tick order. This is called automatically when new events are created.
  34511. * @method Phaser.Timer#order
  34512. */
  34513. order: function () {
  34514. if (this.events.length > 0)
  34515. {
  34516. // Sort the events so the one with the lowest tick is first
  34517. this.events.sort(this.sortHandler);
  34518. this.nextTick = this.events[0].tick;
  34519. }
  34520. },
  34521. /**
  34522. * Sort handler used by Phaser.Timer.order.
  34523. * @method Phaser.Timer#sortHandler
  34524. * @protected
  34525. */
  34526. sortHandler: function (a, b) {
  34527. if (a.tick < b.tick)
  34528. {
  34529. return -1;
  34530. }
  34531. else if (a.tick > b.tick)
  34532. {
  34533. return 1;
  34534. }
  34535. return 0;
  34536. },
  34537. /**
  34538. * Clears any events from the Timer which have pendingDelete set to true and then resets the private _len and _i values.
  34539. *
  34540. * @method Phaser.Timer#clearPendingEvents
  34541. */
  34542. clearPendingEvents: function () {
  34543. this._i = this.events.length;
  34544. while (this._i--)
  34545. {
  34546. if (this.events[this._i].pendingDelete)
  34547. {
  34548. this.events.splice(this._i, 1);
  34549. }
  34550. }
  34551. this._len = this.events.length;
  34552. this._i = 0;
  34553. },
  34554. /**
  34555. * The main Timer update event, called automatically by Phaser.Time.update.
  34556. *
  34557. * @method Phaser.Timer#update
  34558. * @protected
  34559. * @param {number} time - The time from the core game clock.
  34560. * @return {boolean} True if there are still events waiting to be dispatched, otherwise false if this Timer can be destroyed.
  34561. */
  34562. update: function (time) {
  34563. if (this.paused)
  34564. {
  34565. return true;
  34566. }
  34567. this.elapsed = time - this._now;
  34568. this._now = time;
  34569. // spike-dislike
  34570. if (this.elapsed > this.timeCap)
  34571. {
  34572. // For some reason the time between now and the last time the game was updated was larger than our timeCap.
  34573. // This can happen if the Stage.disableVisibilityChange is true and you swap tabs, which makes the raf pause.
  34574. // In this case we need to adjust the TimerEvents and nextTick.
  34575. this.adjustEvents(time - this.elapsed);
  34576. }
  34577. this._marked = 0;
  34578. // Clears events marked for deletion and resets _len and _i to 0.
  34579. this.clearPendingEvents();
  34580. if (this.running && this._now >= this.nextTick && this._len > 0)
  34581. {
  34582. while (this._i < this._len && this.running)
  34583. {
  34584. if (this._now >= this.events[this._i].tick)
  34585. {
  34586. // (now + delay) - (time difference from last tick to now)
  34587. this._newTick = (this._now + this.events[this._i].delay) - (this._now - this.events[this._i].tick);
  34588. if (this._newTick < 0)
  34589. {
  34590. this._newTick = this._now + this.events[this._i].delay;
  34591. }
  34592. if (this.events[this._i].loop === true)
  34593. {
  34594. this.events[this._i].tick = this._newTick;
  34595. this.events[this._i].callback.apply(this.events[this._i].callbackContext, this.events[this._i].args);
  34596. }
  34597. else if (this.events[this._i].repeatCount > 0)
  34598. {
  34599. this.events[this._i].repeatCount--;
  34600. this.events[this._i].tick = this._newTick;
  34601. this.events[this._i].callback.apply(this.events[this._i].callbackContext, this.events[this._i].args);
  34602. }
  34603. else
  34604. {
  34605. this._marked++;
  34606. this.events[this._i].pendingDelete = true;
  34607. this.events[this._i].callback.apply(this.events[this._i].callbackContext, this.events[this._i].args);
  34608. }
  34609. this._i++;
  34610. }
  34611. else
  34612. {
  34613. break;
  34614. }
  34615. }
  34616. // Are there any events left?
  34617. if (this.events.length > this._marked)
  34618. {
  34619. this.order();
  34620. }
  34621. else
  34622. {
  34623. this.expired = true;
  34624. this.onComplete.dispatch(this);
  34625. }
  34626. }
  34627. if (this.expired && this.autoDestroy)
  34628. {
  34629. return false;
  34630. }
  34631. else
  34632. {
  34633. return true;
  34634. }
  34635. },
  34636. /**
  34637. * Pauses the Timer and all events in the queue.
  34638. * @method Phaser.Timer#pause
  34639. */
  34640. pause: function () {
  34641. if (!this.running)
  34642. {
  34643. return;
  34644. }
  34645. this._codePaused = true;
  34646. if (this.paused)
  34647. {
  34648. return;
  34649. }
  34650. this._pauseStarted = this.game.time.now;
  34651. this.paused = true;
  34652. // stop the game by paicha
  34653. game.raf.stop();
  34654. },
  34655. /**
  34656. * This is called by the core Game loop. Do not call it directly, instead use Timer.pause.
  34657. * @method Phaser.Timer#_pause
  34658. * @private
  34659. */
  34660. _pause: function () {
  34661. if (this.paused || !this.running)
  34662. {
  34663. return;
  34664. }
  34665. this._pauseStarted = this.game.time.now;
  34666. this.paused = true;
  34667. },
  34668. /**
  34669. * Adjusts the time of all pending events and the nextTick by the given baseTime.
  34670. *
  34671. * @method Phaser.Timer#adjustEvents
  34672. */
  34673. adjustEvents: function (baseTime) {
  34674. for (var i = 0; i < this.events.length; i++)
  34675. {
  34676. if (!this.events[i].pendingDelete)
  34677. {
  34678. // Work out how long there would have been from when the game paused until the events next tick
  34679. var t = this.events[i].tick - baseTime;
  34680. if (t < 0)
  34681. {
  34682. t = 0;
  34683. }
  34684. // Add the difference on to the time now
  34685. this.events[i].tick = this._now + t;
  34686. }
  34687. }
  34688. var d = this.nextTick - baseTime;
  34689. if (d < 0)
  34690. {
  34691. this.nextTick = this._now;
  34692. }
  34693. else
  34694. {
  34695. this.nextTick = this._now + d;
  34696. }
  34697. },
  34698. /**
  34699. * Resumes the Timer and updates all pending events.
  34700. *
  34701. * @method Phaser.Timer#resume
  34702. */
  34703. resume: function () {
  34704. if (!this.paused)
  34705. {
  34706. return;
  34707. }
  34708. var now = this.game.time.now;
  34709. this._pauseTotal += now - this._now;
  34710. this._now = now;
  34711. this.adjustEvents(this._pauseStarted);
  34712. this.paused = false;
  34713. this._codePaused = false;
  34714. // resume the game by paicha
  34715. game.raf.start();
  34716. },
  34717. /**
  34718. * This is called by the core Game loop. Do not call it directly, instead use Timer.pause.
  34719. * @method Phaser.Timer#_resume
  34720. * @private
  34721. */
  34722. _resume: function () {
  34723. if (this._codePaused)
  34724. {
  34725. return;
  34726. }
  34727. else
  34728. {
  34729. this.resume();
  34730. }
  34731. },
  34732. /**
  34733. * Removes all Events from this Timer and all callbacks linked to onComplete, but leaves the Timer running.
  34734. * The onComplete callbacks won't be called.
  34735. *
  34736. * @method Phaser.Timer#removeAll
  34737. */
  34738. removeAll: function () {
  34739. this.onComplete.removeAll();
  34740. this.events.length = 0;
  34741. this._len = 0;
  34742. this._i = 0;
  34743. },
  34744. /**
  34745. * Destroys this Timer. Any pending Events are not dispatched.
  34746. * The onComplete callbacks won't be called.
  34747. *
  34748. * @method Phaser.Timer#destroy
  34749. */
  34750. destroy: function () {
  34751. this.onComplete.removeAll();
  34752. this.running = false;
  34753. this.events = [];
  34754. this._len = 0;
  34755. this._i = 0;
  34756. }
  34757. };
  34758. /**
  34759. * @name Phaser.Timer#next
  34760. * @property {number} next - The time at which the next event will occur.
  34761. * @readonly
  34762. */
  34763. Object.defineProperty(Phaser.Timer.prototype, "next", {
  34764. get: function () {
  34765. return this.nextTick;
  34766. }
  34767. });
  34768. /**
  34769. * @name Phaser.Timer#duration
  34770. * @property {number} duration - The duration in ms remaining until the next event will occur.
  34771. * @readonly
  34772. */
  34773. Object.defineProperty(Phaser.Timer.prototype, "duration", {
  34774. get: function () {
  34775. if (this.running && this.nextTick > this._now)
  34776. {
  34777. return this.nextTick - this._now;
  34778. }
  34779. else
  34780. {
  34781. return 0;
  34782. }
  34783. }
  34784. });
  34785. /**
  34786. * @name Phaser.Timer#length
  34787. * @property {number} length - The number of pending events in the queue.
  34788. * @readonly
  34789. */
  34790. Object.defineProperty(Phaser.Timer.prototype, "length", {
  34791. get: function () {
  34792. return this.events.length;
  34793. }
  34794. });
  34795. /**
  34796. * @name Phaser.Timer#ms
  34797. * @property {number} ms - The duration in milliseconds that this Timer has been running for.
  34798. * @readonly
  34799. */
  34800. Object.defineProperty(Phaser.Timer.prototype, "ms", {
  34801. get: function () {
  34802. if (this.running)
  34803. {
  34804. return this._now - this._started - this._pauseTotal;
  34805. }
  34806. else
  34807. {
  34808. return 0;
  34809. }
  34810. }
  34811. });
  34812. /**
  34813. * @name Phaser.Timer#seconds
  34814. * @property {number} seconds - The duration in seconds that this Timer has been running for.
  34815. * @readonly
  34816. */
  34817. Object.defineProperty(Phaser.Timer.prototype, "seconds", {
  34818. get: function () {
  34819. if (this.running)
  34820. {
  34821. return this.ms * 0.001;
  34822. }
  34823. else
  34824. {
  34825. return 0;
  34826. }
  34827. }
  34828. });
  34829. Phaser.Timer.prototype.constructor = Phaser.Timer;
  34830. /**
  34831. * @author Richard Davey <rich@photonstorm.com>
  34832. * @copyright 2014 Photon Storm Ltd.
  34833. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  34834. */
  34835. /**
  34836. * A TimerEvent is a single event that is processed by a Phaser.Timer. It consists of a delay, which is a value in milliseconds after which the event will fire.
  34837. * It can call a specific callback, passing in optional parameters.
  34838. *
  34839. * @class Phaser.TimerEvent
  34840. * @classdesc A TimerEvent is a single event that is processed by a Phaser.Timer. It consists of a delay, which is a value in milliseconds after which the event will fire.
  34841. * @constructor
  34842. * @param {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to.
  34843. * @param {number} delay - The delay in ms at which this TimerEvent fires.
  34844. * @param {number} tick - The tick is the next game clock time that this event will fire at.
  34845. * @param {number} repeatCount - If this TimerEvent repeats it will do so this many times.
  34846. * @param {boolean} loop - True if this TimerEvent loops, otherwise false.
  34847. * @param {function} callback - The callback that will be called when the TimerEvent occurs.
  34848. * @param {object} callbackContext - The context in which the callback will be called.
  34849. * @param {array} arguments - The values to be passed to the callback.
  34850. */
  34851. Phaser.TimerEvent = function (timer, delay, tick, repeatCount, loop, callback, callbackContext, args) {
  34852. /**
  34853. * @property {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to.
  34854. */
  34855. this.timer = timer;
  34856. /**
  34857. * @property {number} delay - The delay in ms at which this TimerEvent fires.
  34858. */
  34859. this.delay = delay;
  34860. /**
  34861. * @property {number} tick - The tick is the next game clock time that this event will fire at.
  34862. */
  34863. this.tick = tick;
  34864. /**
  34865. * @property {number} repeatCount - If this TimerEvent repeats it will do so this many times.
  34866. */
  34867. this.repeatCount = repeatCount - 1;
  34868. /**
  34869. * @property {boolean} loop - True if this TimerEvent loops, otherwise false.
  34870. */
  34871. this.loop = loop;
  34872. /**
  34873. * @property {function} callback - The callback that will be called when the TimerEvent occurs.
  34874. */
  34875. this.callback = callback;
  34876. /**
  34877. * @property {object} callbackContext - The context in which the callback will be called.
  34878. */
  34879. this.callbackContext = callbackContext;
  34880. /**
  34881. * @property {array} arguments - The values to be passed to the callback.
  34882. */
  34883. this.args = args;
  34884. /**
  34885. * @property {boolean} pendingDelete - A flag that controls if the TimerEvent is pending deletion.
  34886. * @protected
  34887. */
  34888. this.pendingDelete = false;
  34889. };
  34890. Phaser.TimerEvent.prototype.constructor = Phaser.TimerEvent;
  34891. /**
  34892. * @author Richard Davey <rich@photonstorm.com>
  34893. * @copyright 2014 Photon Storm Ltd.
  34894. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  34895. */
  34896. /**
  34897. * The Animation Manager is used to add, play and update Phaser Animations.
  34898. * Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance.
  34899. *
  34900. * @class Phaser.AnimationManager
  34901. * @constructor
  34902. * @param {Phaser.Sprite} sprite - A reference to the Game Object that owns this AnimationManager.
  34903. */
  34904. Phaser.AnimationManager = function (sprite) {
  34905. /**
  34906. * @property {Phaser.Sprite} sprite - A reference to the parent Sprite that owns this AnimationManager.
  34907. */
  34908. this.sprite = sprite;
  34909. /**
  34910. * @property {Phaser.Game} game - A reference to the currently running Game.
  34911. */
  34912. this.game = sprite.game;
  34913. /**
  34914. * @property {Phaser.Frame} currentFrame - The currently displayed Frame of animation, if any.
  34915. * @default
  34916. */
  34917. this.currentFrame = null;
  34918. /**
  34919. * @property {Phaser.Animation} currentAnim - The currently displayed animation, if any.
  34920. * @default
  34921. */
  34922. this.currentAnim = null;
  34923. /**
  34924. * @property {boolean} updateIfVisible - Should the animation data continue to update even if the Sprite.visible is set to false.
  34925. * @default
  34926. */
  34927. this.updateIfVisible = true;
  34928. /**
  34929. * @property {boolean} isLoaded - Set to true once animation data has been loaded.
  34930. * @default
  34931. */
  34932. this.isLoaded = false;
  34933. /**
  34934. * @property {Phaser.FrameData} _frameData - A temp. var for holding the currently playing Animations FrameData.
  34935. * @private
  34936. * @default
  34937. */
  34938. this._frameData = null;
  34939. /**
  34940. * @property {object} _anims - An internal object that stores all of the Animation instances.
  34941. * @private
  34942. */
  34943. this._anims = {};
  34944. /**
  34945. * @property {object} _outputFrames - An internal object to help avoid gc.
  34946. * @private
  34947. */
  34948. this._outputFrames = [];
  34949. };
  34950. Phaser.AnimationManager.prototype = {
  34951. /**
  34952. * Loads FrameData into the internal temporary vars and resets the frame index to zero.
  34953. * This is called automatically when a new Sprite is created.
  34954. *
  34955. * @method Phaser.AnimationManager#loadFrameData
  34956. * @private
  34957. * @param {Phaser.FrameData} frameData - The FrameData set to load.
  34958. * @param {string|number} frame - The frame to default to.
  34959. * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false`
  34960. */
  34961. loadFrameData: function (frameData, frame) {
  34962. if (this.isLoaded)
  34963. {
  34964. // We need to update the frameData that the animations are using
  34965. for (var anim in this._anims)
  34966. {
  34967. this._anims[anim].updateFrameData(frameData);
  34968. }
  34969. }
  34970. this._frameData = frameData;
  34971. if (typeof frame === 'undefined' || frame === null)
  34972. {
  34973. this.frame = 0;
  34974. }
  34975. else
  34976. {
  34977. if (typeof frame === 'string')
  34978. {
  34979. this.frameName = frame;
  34980. }
  34981. else
  34982. {
  34983. this.frame = frame;
  34984. }
  34985. }
  34986. this.isLoaded = true;
  34987. if (this._frameData)
  34988. {
  34989. return true;
  34990. }
  34991. else
  34992. {
  34993. return false;
  34994. }
  34995. },
  34996. /**
  34997. * Adds a new animation under the given key. Optionally set the frames, frame rate and loop.
  34998. * Animations added in this way are played back with the play function.
  34999. *
  35000. * @method Phaser.AnimationManager#add
  35001. * @param {string} name - The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk".
  35002. * @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.
  35003. * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second.
  35004. * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once.
  35005. * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings?
  35006. * @return {Phaser.Animation} The Animation object that was created.
  35007. */
  35008. add: function (name, frames, frameRate, loop, useNumericIndex) {
  35009. if (this._frameData === null)
  35010. {
  35011. console.warn('No FrameData available for Phaser.Animation ' + name);
  35012. return;
  35013. }
  35014. frames = frames || [];
  35015. frameRate = frameRate || 60;
  35016. if (typeof loop === 'undefined') { loop = false; }
  35017. // If they didn't set the useNumericIndex then let's at least try and guess it
  35018. if (typeof useNumericIndex === 'undefined')
  35019. {
  35020. if (frames && typeof frames[0] === 'number')
  35021. {
  35022. useNumericIndex = true;
  35023. }
  35024. else
  35025. {
  35026. useNumericIndex = false;
  35027. }
  35028. }
  35029. // Create the signals the AnimationManager will emit
  35030. if (this.sprite.events.onAnimationStart === null)
  35031. {
  35032. this.sprite.events.onAnimationStart = new Phaser.Signal();
  35033. this.sprite.events.onAnimationComplete = new Phaser.Signal();
  35034. this.sprite.events.onAnimationLoop = new Phaser.Signal();
  35035. }
  35036. this._outputFrames.length = 0;
  35037. this._frameData.getFrameIndexes(frames, useNumericIndex, this._outputFrames);
  35038. this._anims[name] = new Phaser.Animation(this.game, this.sprite, name, this._frameData, this._outputFrames, frameRate, loop);
  35039. this.currentAnim = this._anims[name];
  35040. this.currentFrame = this.currentAnim.currentFrame;
  35041. // this.sprite.setFrame(this.currentFrame);
  35042. // CHECK WE STILL NEED THIS - PRETTY SURE IT DOESN'T ACTUALLY DO ANYTHING!
  35043. if (this.sprite.__tilePattern)
  35044. {
  35045. // this.__tilePattern = false;
  35046. this.sprite.__tilePattern = false;
  35047. this.tilingTexture = false;
  35048. }
  35049. return this._anims[name];
  35050. },
  35051. /**
  35052. * Check whether the frames in the given array are valid and exist.
  35053. *
  35054. * @method Phaser.AnimationManager#validateFrames
  35055. * @param {Array} frames - An array of frames to be validated.
  35056. * @param {boolean} [useNumericIndex=true] - Validate the frames based on their numeric index (true) or string index (false)
  35057. * @return {boolean} True if all given Frames are valid, otherwise false.
  35058. */
  35059. validateFrames: function (frames, useNumericIndex) {
  35060. if (typeof useNumericIndex == 'undefined') { useNumericIndex = true; }
  35061. for (var i = 0; i < frames.length; i++)
  35062. {
  35063. if (useNumericIndex === true)
  35064. {
  35065. if (frames[i] > this._frameData.total)
  35066. {
  35067. return false;
  35068. }
  35069. }
  35070. else
  35071. {
  35072. if (this._frameData.checkFrameName(frames[i]) === false)
  35073. {
  35074. return false;
  35075. }
  35076. }
  35077. }
  35078. return true;
  35079. },
  35080. /**
  35081. * Play an animation based on the given key. The animation should previously have been added via sprite.animations.add()
  35082. * If the requested animation is already playing this request will be ignored. If you need to reset an already running animation do so directly on the Animation object itself.
  35083. *
  35084. * @method Phaser.AnimationManager#play
  35085. * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump".
  35086. * @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.
  35087. * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
  35088. * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
  35089. * @return {Phaser.Animation} A reference to playing Animation instance.
  35090. */
  35091. play: function (name, frameRate, loop, killOnComplete) {
  35092. if (this._anims[name])
  35093. {
  35094. if (this.currentAnim === this._anims[name])
  35095. {
  35096. if (this.currentAnim.isPlaying === false)
  35097. {
  35098. this.currentAnim.paused = false;
  35099. return this.currentAnim.play(frameRate, loop, killOnComplete);
  35100. }
  35101. return this.currentAnim;
  35102. }
  35103. else
  35104. {
  35105. if (this.currentAnim && this.currentAnim.isPlaying)
  35106. {
  35107. this.currentAnim.stop();
  35108. }
  35109. this.currentAnim = this._anims[name];
  35110. this.currentAnim.paused = false;
  35111. this.currentFrame = this.currentAnim.currentFrame;
  35112. return this.currentAnim.play(frameRate, loop, killOnComplete);
  35113. }
  35114. }
  35115. },
  35116. /**
  35117. * Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped.
  35118. * The currentAnim property of the AnimationManager is automatically set to the animation given.
  35119. *
  35120. * @method Phaser.AnimationManager#stop
  35121. * @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.
  35122. * @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)
  35123. */
  35124. stop: function (name, resetFrame) {
  35125. if (typeof resetFrame == 'undefined') { resetFrame = false; }
  35126. if (typeof name == 'string')
  35127. {
  35128. if (this._anims[name])
  35129. {
  35130. this.currentAnim = this._anims[name];
  35131. this.currentAnim.stop(resetFrame);
  35132. }
  35133. }
  35134. else
  35135. {
  35136. if (this.currentAnim)
  35137. {
  35138. this.currentAnim.stop(resetFrame);
  35139. }
  35140. }
  35141. },
  35142. /**
  35143. * The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events.
  35144. *
  35145. * @method Phaser.AnimationManager#update
  35146. * @protected
  35147. * @return {boolean} True if a new animation frame has been set, otherwise false.
  35148. */
  35149. update: function () {
  35150. if (this.updateIfVisible && !this.sprite.visible)
  35151. {
  35152. return false;
  35153. }
  35154. if (this.currentAnim && this.currentAnim.update() === true)
  35155. {
  35156. this.currentFrame = this.currentAnim.currentFrame;
  35157. return true;
  35158. }
  35159. return false;
  35160. },
  35161. /**
  35162. * Advances by the given number of frames in the current animation, taking the loop value into consideration.
  35163. *
  35164. * @method Phaser.AnimationManager#next
  35165. * @param {number} [quantity=1] - The number of frames to advance.
  35166. */
  35167. next: function (quantity) {
  35168. if (this.currentAnim)
  35169. {
  35170. this.currentAnim.next(quantity);
  35171. this.currentFrame = this.currentAnim.currentFrame;
  35172. }
  35173. },
  35174. /**
  35175. * Moves backwards the given number of frames in the current animation, taking the loop value into consideration.
  35176. *
  35177. * @method Phaser.AnimationManager#previous
  35178. * @param {number} [quantity=1] - The number of frames to move back.
  35179. */
  35180. previous: function (quantity) {
  35181. if (this.currentAnim)
  35182. {
  35183. this.currentAnim.previous(quantity);
  35184. this.currentFrame = this.currentAnim.currentFrame;
  35185. }
  35186. },
  35187. /**
  35188. * Returns an animation that was previously added by name.
  35189. *
  35190. * @method Phaser.AnimationManager#getAnimation
  35191. * @param {string} name - The name of the animation to be returned, e.g. "fire".
  35192. * @return {Phaser.Animation} The Animation instance, if found, otherwise null.
  35193. */
  35194. getAnimation: function (name) {
  35195. if (typeof name === 'string')
  35196. {
  35197. if (this._anims[name])
  35198. {
  35199. return this._anims[name];
  35200. }
  35201. }
  35202. return null;
  35203. },
  35204. /**
  35205. * Refreshes the current frame data back to the parent Sprite and also resets the texture data.
  35206. *
  35207. * @method Phaser.AnimationManager#refreshFrame
  35208. */
  35209. refreshFrame: function () {
  35210. this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
  35211. if (this.sprite.__tilePattern)
  35212. {
  35213. this.__tilePattern = false;
  35214. this.tilingTexture = false;
  35215. }
  35216. },
  35217. /**
  35218. * Destroys all references this AnimationManager contains.
  35219. * Iterates through the list of animations stored in this manager and calls destroy on each of them.
  35220. *
  35221. * @method Phaser.AnimationManager#destroy
  35222. */
  35223. destroy: function () {
  35224. var anim = null;
  35225. for (var anim in this._anims)
  35226. {
  35227. if (this._anims.hasOwnProperty(anim))
  35228. {
  35229. this._anims[anim].destroy();
  35230. }
  35231. }
  35232. this._anims = {};
  35233. this._frameData = null;
  35234. this._frameIndex = 0;
  35235. this.currentAnim = null;
  35236. this.currentFrame = null;
  35237. }
  35238. };
  35239. Phaser.AnimationManager.prototype.constructor = Phaser.AnimationManager;
  35240. /**
  35241. * @name Phaser.AnimationManager#frameData
  35242. * @property {Phaser.FrameData} frameData - The current animations FrameData.
  35243. * @readonly
  35244. */
  35245. Object.defineProperty(Phaser.AnimationManager.prototype, 'frameData', {
  35246. get: function () {
  35247. return this._frameData;
  35248. }
  35249. });
  35250. /**
  35251. * @name Phaser.AnimationManager#frameTotal
  35252. * @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded.
  35253. * @readonly
  35254. */
  35255. Object.defineProperty(Phaser.AnimationManager.prototype, 'frameTotal', {
  35256. get: function () {
  35257. if (this._frameData)
  35258. {
  35259. return this._frameData.total;
  35260. }
  35261. else
  35262. {
  35263. return -1;
  35264. }
  35265. }
  35266. });
  35267. /**
  35268. * @name Phaser.AnimationManager#paused
  35269. * @property {boolean} paused - Gets and sets the paused state of the current animation.
  35270. */
  35271. Object.defineProperty(Phaser.AnimationManager.prototype, 'paused', {
  35272. get: function () {
  35273. return this.currentAnim.isPaused;
  35274. },
  35275. set: function (value) {
  35276. this.currentAnim.paused = value;
  35277. }
  35278. });
  35279. /**
  35280. * @name Phaser.AnimationManager#frame
  35281. * @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
  35282. */
  35283. Object.defineProperty(Phaser.AnimationManager.prototype, 'frame', {
  35284. get: function () {
  35285. if (this.currentFrame)
  35286. {
  35287. return this._frameIndex;
  35288. }
  35289. },
  35290. set: function (value) {
  35291. if (typeof value === 'number' && this._frameData && this._frameData.getFrame(value) !== null)
  35292. {
  35293. this.currentFrame = this._frameData.getFrame(value);
  35294. if (this.currentFrame)
  35295. {
  35296. this._frameIndex = value;
  35297. this.sprite.setFrame(this.currentFrame);
  35298. if (this.sprite.__tilePattern)
  35299. {
  35300. this.__tilePattern = false;
  35301. this.tilingTexture = false;
  35302. }
  35303. }
  35304. }
  35305. }
  35306. });
  35307. /**
  35308. * @name Phaser.AnimationManager#frameName
  35309. * @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display.
  35310. */
  35311. Object.defineProperty(Phaser.AnimationManager.prototype, 'frameName', {
  35312. get: function () {
  35313. if (this.currentFrame)
  35314. {
  35315. return this.currentFrame.name;
  35316. }
  35317. },
  35318. set: function (value) {
  35319. if (typeof value === 'string' && this._frameData && this._frameData.getFrameByName(value) !== null)
  35320. {
  35321. this.currentFrame = this._frameData.getFrameByName(value);
  35322. if (this.currentFrame)
  35323. {
  35324. this._frameIndex = this.currentFrame.index;
  35325. this.sprite.setFrame(this.currentFrame);
  35326. if (this.sprite.__tilePattern)
  35327. {
  35328. this.__tilePattern = false;
  35329. this.tilingTexture = false;
  35330. }
  35331. }
  35332. }
  35333. else
  35334. {
  35335. console.warn('Cannot set frameName: ' + value);
  35336. }
  35337. }
  35338. });
  35339. /**
  35340. * @author Richard Davey <rich@photonstorm.com>
  35341. * @copyright 2014 Photon Storm Ltd.
  35342. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  35343. */
  35344. /**
  35345. * An Animation instance contains a single animation and the controls to play it.
  35346. * It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite.
  35347. *
  35348. * @class Phaser.Animation
  35349. * @constructor
  35350. * @param {Phaser.Game} game - A reference to the currently running game.
  35351. * @param {Phaser.Sprite} parent - A reference to the owner of this Animation.
  35352. * @param {string} name - The unique name for this animation, used in playback commands.
  35353. * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation.
  35354. * @param {(Array.<number>|Array.<string>)} frames - An array of numbers or strings indicating which frames to play in which order.
  35355. * @param {number} delay - The time between each frame of the animation, given in ms.
  35356. * @param {boolean} loop - Should this animation loop when it reaches the end or play through once.
  35357. */
  35358. Phaser.Animation = function (game, parent, name, frameData, frames, delay, loop) {
  35359. /**
  35360. * @property {Phaser.Game} game - A reference to the currently running Game.
  35361. */
  35362. this.game = game;
  35363. /**
  35364. * @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation.
  35365. * @private
  35366. */
  35367. this._parent = parent;
  35368. /**
  35369. * @property {Phaser.FrameData} _frameData - The FrameData the Animation uses.
  35370. * @private
  35371. */
  35372. this._frameData = frameData;
  35373. /**
  35374. * @property {string} name - The user defined name given to this Animation.
  35375. */
  35376. this.name = name;
  35377. /**
  35378. * @property {array} _frames
  35379. * @private
  35380. */
  35381. this._frames = [];
  35382. this._frames = this._frames.concat(frames);
  35383. /**
  35384. * @property {number} delay - The delay in ms between each frame of the Animation.
  35385. */
  35386. this.delay = 1000 / delay;
  35387. /**
  35388. * @property {boolean} loop - The loop state of the Animation.
  35389. */
  35390. this.loop = loop;
  35391. /**
  35392. * @property {number} loopCount - The number of times the animation has looped since it was last started.
  35393. */
  35394. this.loopCount = 0;
  35395. /**
  35396. * @property {boolean} killOnComplete - Should the parent of this Animation be killed when the animation completes?
  35397. * @default
  35398. */
  35399. this.killOnComplete = false;
  35400. /**
  35401. * @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback.
  35402. * @default
  35403. */
  35404. this.isFinished = false;
  35405. /**
  35406. * @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback.
  35407. * @default
  35408. */
  35409. this.isPlaying = false;
  35410. /**
  35411. * @property {boolean} isPaused - The paused state of the Animation.
  35412. * @default
  35413. */
  35414. this.isPaused = false;
  35415. /**
  35416. * @property {boolean} _pauseStartTime - The time the animation paused.
  35417. * @private
  35418. * @default
  35419. */
  35420. this._pauseStartTime = 0;
  35421. /**
  35422. * @property {number} _frameIndex
  35423. * @private
  35424. * @default
  35425. */
  35426. this._frameIndex = 0;
  35427. /**
  35428. * @property {number} _frameDiff
  35429. * @private
  35430. * @default
  35431. */
  35432. this._frameDiff = 0;
  35433. /**
  35434. * @property {number} _frameSkip
  35435. * @private
  35436. * @default
  35437. */
  35438. this._frameSkip = 1;
  35439. /**
  35440. * @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation.
  35441. */
  35442. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  35443. /**
  35444. * @property {Phaser.Signal} onStart - This event is dispatched when this Animation starts playback.
  35445. */
  35446. this.onStart = new Phaser.Signal();
  35447. /**
  35448. * @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 onAnimationLoop instead.
  35449. */
  35450. this.onComplete = new Phaser.Signal();
  35451. /**
  35452. * @property {Phaser.Signal} onLoop - This event is dispatched when this Animation loops.
  35453. */
  35454. this.onLoop = new Phaser.Signal();
  35455. // Set-up some event listeners
  35456. this.game.onPause.add(this.onPause, this);
  35457. this.game.onResume.add(this.onResume, this);
  35458. };
  35459. Phaser.Animation.prototype = {
  35460. /**
  35461. * Plays this animation.
  35462. *
  35463. * @method Phaser.Animation#play
  35464. * @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.
  35465. * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
  35466. * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
  35467. * @return {Phaser.Animation} - A reference to this Animation instance.
  35468. */
  35469. play: function (frameRate, loop, killOnComplete) {
  35470. if (typeof frameRate === 'number')
  35471. {
  35472. // If they set a new frame rate then use it, otherwise use the one set on creation
  35473. this.delay = 1000 / frameRate;
  35474. }
  35475. if (typeof loop === 'boolean')
  35476. {
  35477. // If they set a new loop value then use it, otherwise use the one set on creation
  35478. this.loop = loop;
  35479. }
  35480. if (typeof killOnComplete !== 'undefined')
  35481. {
  35482. // Remove the parent sprite once the animation has finished?
  35483. this.killOnComplete = killOnComplete;
  35484. }
  35485. this.isPlaying = true;
  35486. this.isFinished = false;
  35487. this.paused = false;
  35488. this.loopCount = 0;
  35489. this._timeLastFrame = this.game.time.now;
  35490. this._timeNextFrame = this.game.time.now + this.delay;
  35491. this._frameIndex = 0;
  35492. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  35493. this._parent.setFrame(this.currentFrame);
  35494. // TODO: Double check if required
  35495. if (this._parent.__tilePattern)
  35496. {
  35497. this._parent.__tilePattern = false;
  35498. this._parent.tilingTexture = false;
  35499. }
  35500. this._parent.events.onAnimationStart.dispatch(this._parent, this);
  35501. this.onStart.dispatch(this._parent, this);
  35502. return this;
  35503. },
  35504. /**
  35505. * Sets this animation back to the first frame and restarts the animation.
  35506. *
  35507. * @method Phaser.Animation#restart
  35508. */
  35509. restart: function () {
  35510. this.isPlaying = true;
  35511. this.isFinished = false;
  35512. this.paused = false;
  35513. this.loopCount = 0;
  35514. this._timeLastFrame = this.game.time.now;
  35515. this._timeNextFrame = this.game.time.now + this.delay;
  35516. this._frameIndex = 0;
  35517. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  35518. this._parent.setFrame(this.currentFrame);
  35519. this.onStart.dispatch(this._parent, this);
  35520. },
  35521. /**
  35522. * Sets this animations playback to a given frame with the given ID.
  35523. *
  35524. * @method Phaser.Animation#setFrame
  35525. * @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.
  35526. * @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.
  35527. */
  35528. setFrame: function(frameId, useLocalFrameIndex) {
  35529. var frameIndex;
  35530. if (typeof useLocalFrameIndex === 'undefined')
  35531. {
  35532. useLocalFrameIndex = false;
  35533. }
  35534. // Find the index to the desired frame.
  35535. if (typeof frameId === "string")
  35536. {
  35537. for (var i = 0; i < this._frames.length; i++)
  35538. {
  35539. if (this._frameData.getFrame(this._frames[i]).name === frameId)
  35540. {
  35541. frameIndex = i;
  35542. }
  35543. }
  35544. }
  35545. else if (typeof frameId === "number")
  35546. {
  35547. if (useLocalFrameIndex)
  35548. {
  35549. frameIndex = frameId;
  35550. }
  35551. else
  35552. {
  35553. for (var i = 0; i < this._frames.length; i++)
  35554. {
  35555. if (this.frames[i] === frameIndex)
  35556. {
  35557. frameIndex = i;
  35558. }
  35559. }
  35560. }
  35561. }
  35562. if (frameIndex)
  35563. {
  35564. // Set the current frame index to the found index. Subtract 1 so that it animates to the desired frame on update.
  35565. this._frameIndex = frameIndex - 1;
  35566. // Make the animation update at next update
  35567. this._timeNextFrame = this.game.time.now;
  35568. this.update();
  35569. }
  35570. },
  35571. /**
  35572. * 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.
  35573. * If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored.
  35574. *
  35575. * @method Phaser.Animation#stop
  35576. * @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation.
  35577. * @param {boolean} [dispatchComplete=false] - Dispatch the Animation.onComplete and parent.onAnimationComplete events?
  35578. */
  35579. stop: function (resetFrame, dispatchComplete) {
  35580. if (typeof resetFrame === 'undefined') { resetFrame = false; }
  35581. if (typeof dispatchComplete === 'undefined') { dispatchComplete = false; }
  35582. this.isPlaying = false;
  35583. this.isFinished = true;
  35584. this.paused = false;
  35585. if (resetFrame)
  35586. {
  35587. this.currentFrame = this._frameData.getFrame(this._frames[0]);
  35588. this._parent.setFrame(this.currentFrame);
  35589. }
  35590. if (dispatchComplete)
  35591. {
  35592. this._parent.events.onAnimationComplete.dispatch(this._parent, this);
  35593. this.onComplete.dispatch(this._parent, this);
  35594. }
  35595. },
  35596. /**
  35597. * Called when the Game enters a paused state.
  35598. *
  35599. * @method Phaser.Animation#onPause
  35600. */
  35601. onPause: function () {
  35602. if (this.isPlaying)
  35603. {
  35604. this._frameDiff = this._timeNextFrame - this.game.time.now;
  35605. }
  35606. },
  35607. /**
  35608. * Called when the Game resumes from a paused state.
  35609. *
  35610. * @method Phaser.Animation#onResume
  35611. */
  35612. onResume: function () {
  35613. if (this.isPlaying)
  35614. {
  35615. this._timeNextFrame = this.game.time.now + this._frameDiff;
  35616. }
  35617. },
  35618. /**
  35619. * Updates this animation. Called automatically by the AnimationManager.
  35620. *
  35621. * @method Phaser.Animation#update
  35622. */
  35623. update: function () {
  35624. if (this.isPaused)
  35625. {
  35626. return false;
  35627. }
  35628. if (this.isPlaying && this.game.time.now >= this._timeNextFrame)
  35629. {
  35630. this._frameSkip = 1;
  35631. // Lagging?
  35632. this._frameDiff = this.game.time.now - this._timeNextFrame;
  35633. this._timeLastFrame = this.game.time.now;
  35634. if (this._frameDiff > this.delay)
  35635. {
  35636. // We need to skip a frame, work out how many
  35637. this._frameSkip = Math.floor(this._frameDiff / this.delay);
  35638. this._frameDiff -= (this._frameSkip * this.delay);
  35639. }
  35640. // And what's left now?
  35641. this._timeNextFrame = this.game.time.now + (this.delay - this._frameDiff);
  35642. this._frameIndex += this._frameSkip;
  35643. if (this._frameIndex >= this._frames.length)
  35644. {
  35645. if (this.loop)
  35646. {
  35647. this._frameIndex %= this._frames.length;
  35648. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  35649. this.loopCount++;
  35650. this._parent.events.onAnimationLoop.dispatch(this._parent, this);
  35651. this.onLoop.dispatch(this._parent, this);
  35652. }
  35653. else
  35654. {
  35655. this.complete();
  35656. }
  35657. }
  35658. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  35659. if (this.currentFrame)
  35660. {
  35661. this._parent.setFrame(this.currentFrame);
  35662. if (this._parent.__tilePattern)
  35663. {
  35664. this._parent.__tilePattern = false;
  35665. this._parent.tilingTexture = false;
  35666. }
  35667. }
  35668. return true;
  35669. }
  35670. return false;
  35671. },
  35672. /**
  35673. * Advances by the given number of frames in the Animation, taking the loop value into consideration.
  35674. *
  35675. * @method Phaser.Animation#next
  35676. * @param {number} [quantity=1] - The number of frames to advance.
  35677. */
  35678. next: function (quantity) {
  35679. if (typeof quantity === 'undefined') { quantity = 1; }
  35680. var frame = this._frameIndex + quantity;
  35681. if (frame >= this._frames.length)
  35682. {
  35683. if (this.loop)
  35684. {
  35685. frame %= this._frames.length;
  35686. }
  35687. else
  35688. {
  35689. frame = this._frames.length - 1;
  35690. }
  35691. }
  35692. if (frame !== this._frameIndex)
  35693. {
  35694. this._frameIndex = frame;
  35695. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  35696. if (this.currentFrame)
  35697. {
  35698. this._parent.setFrame(this.currentFrame);
  35699. if (this._parent.__tilePattern)
  35700. {
  35701. this._parent.__tilePattern = false;
  35702. this._parent.tilingTexture = false;
  35703. }
  35704. }
  35705. }
  35706. },
  35707. /**
  35708. * Moves backwards the given number of frames in the Animation, taking the loop value into consideration.
  35709. *
  35710. * @method Phaser.Animation#previous
  35711. * @param {number} [quantity=1] - The number of frames to move back.
  35712. */
  35713. previous: function (quantity) {
  35714. if (typeof quantity === 'undefined') { quantity = 1; }
  35715. var frame = this._frameIndex - quantity;
  35716. if (frame < 0)
  35717. {
  35718. if (this.loop)
  35719. {
  35720. frame = this._frames.length + frame;
  35721. }
  35722. else
  35723. {
  35724. frame++;
  35725. }
  35726. }
  35727. if (frame !== this._frameIndex)
  35728. {
  35729. this._frameIndex = frame;
  35730. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  35731. if (this.currentFrame)
  35732. {
  35733. this._parent.setFrame(this.currentFrame);
  35734. if (this._parent.__tilePattern)
  35735. {
  35736. this._parent.__tilePattern = false;
  35737. this._parent.tilingTexture = false;
  35738. }
  35739. }
  35740. }
  35741. },
  35742. /**
  35743. * Changes the FrameData object this Animation is using.
  35744. *
  35745. * @method Phaser.Animation#updateFrameData
  35746. * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation.
  35747. */
  35748. updateFrameData: function (frameData) {
  35749. this._frameData = frameData;
  35750. this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex % this._frames.length]) : null;
  35751. },
  35752. /**
  35753. * Cleans up this animation ready for deletion. Nulls all values and references.
  35754. *
  35755. * @method Phaser.Animation#destroy
  35756. */
  35757. destroy: function () {
  35758. this.game.onPause.remove(this.onPause, this);
  35759. this.game.onResume.remove(this.onResume, this);
  35760. this.game = null;
  35761. this._parent = null;
  35762. this._frames = null;
  35763. this._frameData = null;
  35764. this.currentFrame = null;
  35765. this.isPlaying = false;
  35766. this.onStart.dispose();
  35767. this.onLoop.dispose();
  35768. this.onComplete.dispose();
  35769. },
  35770. /**
  35771. * Called internally when the animation finishes playback.
  35772. * Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event.
  35773. *
  35774. * @method Phaser.Animation#complete
  35775. */
  35776. complete: function () {
  35777. this.isPlaying = false;
  35778. this.isFinished = true;
  35779. this.paused = false;
  35780. this._parent.events.onAnimationComplete.dispatch(this._parent, this);
  35781. this.onComplete.dispatch(this._parent, this);
  35782. if (this.killOnComplete)
  35783. {
  35784. this._parent.kill();
  35785. }
  35786. }
  35787. };
  35788. Phaser.Animation.prototype.constructor = Phaser.Animation;
  35789. /**
  35790. * @name Phaser.Animation#paused
  35791. * @property {boolean} paused - Gets and sets the paused state of this Animation.
  35792. */
  35793. Object.defineProperty(Phaser.Animation.prototype, 'paused', {
  35794. get: function () {
  35795. return this.isPaused;
  35796. },
  35797. set: function (value) {
  35798. this.isPaused = value;
  35799. if (value)
  35800. {
  35801. // Paused
  35802. this._pauseStartTime = this.game.time.now;
  35803. }
  35804. else
  35805. {
  35806. // Un-paused
  35807. if (this.isPlaying)
  35808. {
  35809. this._timeNextFrame = this.game.time.now + this.delay;
  35810. }
  35811. }
  35812. }
  35813. });
  35814. /**
  35815. * @name Phaser.Animation#frameTotal
  35816. * @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded.
  35817. * @readonly
  35818. */
  35819. Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', {
  35820. get: function () {
  35821. return this._frames.length;
  35822. }
  35823. });
  35824. /**
  35825. * @name Phaser.Animation#frame
  35826. * @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
  35827. */
  35828. Object.defineProperty(Phaser.Animation.prototype, 'frame', {
  35829. get: function () {
  35830. if (this.currentFrame !== null)
  35831. {
  35832. return this.currentFrame.index;
  35833. }
  35834. else
  35835. {
  35836. return this._frameIndex;
  35837. }
  35838. },
  35839. set: function (value) {
  35840. this.currentFrame = this._frameData.getFrame(this._frames[value]);
  35841. if (this.currentFrame !== null)
  35842. {
  35843. this._frameIndex = value;
  35844. this._parent.setFrame(this.currentFrame);
  35845. }
  35846. }
  35847. });
  35848. /**
  35849. * @name Phaser.Animation#speed
  35850. * @property {number} speed - Gets or sets the current speed of the animation, the time between each frame of the animation, given in ms. Takes effect from the NEXT frame. Minimum value is 1.
  35851. */
  35852. Object.defineProperty(Phaser.Animation.prototype, 'speed', {
  35853. get: function () {
  35854. return Math.round(1000 / this.delay);
  35855. },
  35856. set: function (value) {
  35857. if (value >= 1)
  35858. {
  35859. this.delay = 1000 / value;
  35860. }
  35861. }
  35862. });
  35863. /**
  35864. * Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers.
  35865. * For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large'
  35866. * You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4);
  35867. *
  35868. * @method Phaser.Animation.generateFrameNames
  35869. * @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'.
  35870. * @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1.
  35871. * @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34.
  35872. * @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the prefix would be '-large'.
  35873. * @param {number} [zeroPad=0] - The number of zeroes to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4.
  35874. * @return {array} An array of framenames.
  35875. */
  35876. Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) {
  35877. if (typeof suffix == 'undefined') { suffix = ''; }
  35878. var output = [];
  35879. var frame = '';
  35880. if (start < stop)
  35881. {
  35882. for (var i = start; i <= stop; i++)
  35883. {
  35884. if (typeof zeroPad == 'number')
  35885. {
  35886. // str, len, pad, dir
  35887. frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1);
  35888. }
  35889. else
  35890. {
  35891. frame = i.toString();
  35892. }
  35893. frame = prefix + frame + suffix;
  35894. output.push(frame);
  35895. }
  35896. }
  35897. else
  35898. {
  35899. for (var i = start; i >= stop; i--)
  35900. {
  35901. if (typeof zeroPad == 'number')
  35902. {
  35903. // str, len, pad, dir
  35904. frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1);
  35905. }
  35906. else
  35907. {
  35908. frame = i.toString();
  35909. }
  35910. frame = prefix + frame + suffix;
  35911. output.push(frame);
  35912. }
  35913. }
  35914. return output;
  35915. };
  35916. /**
  35917. * @author Richard Davey <rich@photonstorm.com>
  35918. * @copyright 2014 Photon Storm Ltd.
  35919. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  35920. */
  35921. /**
  35922. * A Frame is a single frame of an animation and is part of a FrameData collection.
  35923. *
  35924. * @class Phaser.Frame
  35925. * @constructor
  35926. * @param {number} index - The index of this Frame within the FrameData set it is being added to.
  35927. * @param {number} x - X position of the frame within the texture image.
  35928. * @param {number} y - Y position of the frame within the texture image.
  35929. * @param {number} width - Width of the frame within the texture image.
  35930. * @param {number} height - Height of the frame within the texture image.
  35931. * @param {string} name - The name of the frame. In Texture Atlas data this is usually set to the filename.
  35932. * @param {string} uuid - Internal UUID key.
  35933. */
  35934. Phaser.Frame = function (index, x, y, width, height, name, uuid) {
  35935. /**
  35936. * @property {number} index - The index of this Frame within the FrameData set it is being added to.
  35937. */
  35938. this.index = index;
  35939. /**
  35940. * @property {number} x - X position within the image to cut from.
  35941. */
  35942. this.x = x;
  35943. /**
  35944. * @property {number} y - Y position within the image to cut from.
  35945. */
  35946. this.y = y;
  35947. /**
  35948. * @property {number} width - Width of the frame.
  35949. */
  35950. this.width = width;
  35951. /**
  35952. * @property {number} height - Height of the frame.
  35953. */
  35954. this.height = height;
  35955. /**
  35956. * @property {string} name - Useful for Texture Atlas files (is set to the filename value).
  35957. */
  35958. this.name = name;
  35959. /**
  35960. * @property {string} uuid - DEPRECATED: A link to the PIXI.TextureCache entry.
  35961. */
  35962. this.uuid = uuid;
  35963. /**
  35964. * @property {number} centerX - Center X position within the image to cut from.
  35965. */
  35966. this.centerX = Math.floor(width / 2);
  35967. /**
  35968. * @property {number} centerY - Center Y position within the image to cut from.
  35969. */
  35970. this.centerY = Math.floor(height / 2);
  35971. /**
  35972. * @property {number} distance - The distance from the top left to the bottom-right of this Frame.
  35973. */
  35974. this.distance = Phaser.Math.distance(0, 0, width, height);
  35975. /**
  35976. * @property {boolean} rotated - Rotated? (not yet implemented)
  35977. * @default
  35978. */
  35979. this.rotated = false;
  35980. /**
  35981. * @property {string} rotationDirection - Either 'cw' or 'ccw', rotation is always 90 degrees.
  35982. * @default 'cw'
  35983. */
  35984. this.rotationDirection = 'cw';
  35985. /**
  35986. * @property {boolean} trimmed - Was it trimmed when packed?
  35987. * @default
  35988. */
  35989. this.trimmed = false;
  35990. /**
  35991. * @property {number} sourceSizeW - Width of the original sprite.
  35992. */
  35993. this.sourceSizeW = width;
  35994. /**
  35995. * @property {number} sourceSizeH - Height of the original sprite.
  35996. */
  35997. this.sourceSizeH = height;
  35998. /**
  35999. * @property {number} spriteSourceSizeX - X position of the trimmed sprite inside original sprite.
  36000. * @default
  36001. */
  36002. this.spriteSourceSizeX = 0;
  36003. /**
  36004. * @property {number} spriteSourceSizeY - Y position of the trimmed sprite inside original sprite.
  36005. * @default
  36006. */
  36007. this.spriteSourceSizeY = 0;
  36008. /**
  36009. * @property {number} spriteSourceSizeW - Width of the trimmed sprite.
  36010. * @default
  36011. */
  36012. this.spriteSourceSizeW = 0;
  36013. /**
  36014. * @property {number} spriteSourceSizeH - Height of the trimmed sprite.
  36015. * @default
  36016. */
  36017. this.spriteSourceSizeH = 0;
  36018. /**
  36019. * @property {number} right - The right of the Frame (x + width).
  36020. */
  36021. this.right = this.x + this.width;
  36022. /**
  36023. * @property {number} bottom - The bottom of the frame (y + height).
  36024. */
  36025. this.bottom = this.y + this.height;
  36026. };
  36027. Phaser.Frame.prototype = {
  36028. /**
  36029. * If the frame was trimmed when added to the Texture Atlas this records the trim and source data.
  36030. *
  36031. * @method Phaser.Frame#setTrim
  36032. * @param {boolean} trimmed - If this frame was trimmed or not.
  36033. * @param {number} actualWidth - The width of the frame before being trimmed.
  36034. * @param {number} actualHeight - The height of the frame before being trimmed.
  36035. * @param {number} destX - The destination X position of the trimmed frame for display.
  36036. * @param {number} destY - The destination Y position of the trimmed frame for display.
  36037. * @param {number} destWidth - The destination width of the trimmed frame for display.
  36038. * @param {number} destHeight - The destination height of the trimmed frame for display.
  36039. */
  36040. setTrim: function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) {
  36041. this.trimmed = trimmed;
  36042. if (trimmed)
  36043. {
  36044. this.sourceSizeW = actualWidth;
  36045. this.sourceSizeH = actualHeight;
  36046. this.centerX = Math.floor(actualWidth / 2);
  36047. this.centerY = Math.floor(actualHeight / 2);
  36048. this.spriteSourceSizeX = destX;
  36049. this.spriteSourceSizeY = destY;
  36050. this.spriteSourceSizeW = destWidth;
  36051. this.spriteSourceSizeH = destHeight;
  36052. }
  36053. },
  36054. /**
  36055. * Returns a Rectangle set to the dimensions of this Frame.
  36056. *
  36057. * @method Phaser.Frame#getRect
  36058. * @param {Phaser.Rectangle} [out] - A rectangle to copy the frame dimensions to.
  36059. * @return {Phaser.Rectangle} A rectangle.
  36060. */
  36061. getRect: function (out) {
  36062. if (typeof out === 'undefined')
  36063. {
  36064. out = new Phaser.Rectangle(this.x, this.y, this.width, this.height);
  36065. }
  36066. else
  36067. {
  36068. out.setTo(this.x, this.y, this.width, this.height);
  36069. }
  36070. return out;
  36071. }
  36072. };
  36073. Phaser.Frame.prototype.constructor = Phaser.Frame;
  36074. /**
  36075. * @author Richard Davey <rich@photonstorm.com>
  36076. * @copyright 2014 Photon Storm Ltd.
  36077. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  36078. */
  36079. /**
  36080. * FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser.
  36081. *
  36082. * @class Phaser.FrameData
  36083. * @constructor
  36084. */
  36085. Phaser.FrameData = function () {
  36086. /**
  36087. * @property {Array} _frames - Local array of frames.
  36088. * @private
  36089. */
  36090. this._frames = [];
  36091. /**
  36092. * @property {Array} _frameNames - Local array of frame names for name to index conversions.
  36093. * @private
  36094. */
  36095. this._frameNames = [];
  36096. };
  36097. Phaser.FrameData.prototype = {
  36098. /**
  36099. * Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly.
  36100. *
  36101. * @method Phaser.FrameData#addFrame
  36102. * @param {Phaser.Frame} frame - The frame to add to this FrameData set.
  36103. * @return {Phaser.Frame} The frame that was just added.
  36104. */
  36105. addFrame: function (frame) {
  36106. frame.index = this._frames.length;
  36107. this._frames.push(frame);
  36108. if (frame.name !== '')
  36109. {
  36110. this._frameNames[frame.name] = frame.index;
  36111. }
  36112. return frame;
  36113. },
  36114. /**
  36115. * Get a Frame by its numerical index.
  36116. *
  36117. * @method Phaser.FrameData#getFrame
  36118. * @param {number} index - The index of the frame you want to get.
  36119. * @return {Phaser.Frame} The frame, if found.
  36120. */
  36121. getFrame: function (index) {
  36122. if (index > this._frames.length)
  36123. {
  36124. index = 0;
  36125. }
  36126. return this._frames[index];
  36127. },
  36128. /**
  36129. * Get a Frame by its frame name.
  36130. *
  36131. * @method Phaser.FrameData#getFrameByName
  36132. * @param {string} name - The name of the frame you want to get.
  36133. * @return {Phaser.Frame} The frame, if found.
  36134. */
  36135. getFrameByName: function (name) {
  36136. if (typeof this._frameNames[name] === 'number')
  36137. {
  36138. return this._frames[this._frameNames[name]];
  36139. }
  36140. return null;
  36141. },
  36142. /**
  36143. * Check if there is a Frame with the given name.
  36144. *
  36145. * @method Phaser.FrameData#checkFrameName
  36146. * @param {string} name - The name of the frame you want to check.
  36147. * @return {boolean} True if the frame is found, otherwise false.
  36148. */
  36149. checkFrameName: function (name) {
  36150. if (this._frameNames[name] == null)
  36151. {
  36152. return false;
  36153. }
  36154. return true;
  36155. },
  36156. /**
  36157. * Returns a range of frames based on the given start and end frame indexes and returns them in an Array.
  36158. *
  36159. * @method Phaser.FrameData#getFrameRange
  36160. * @param {number} start - The starting frame index.
  36161. * @param {number} end - The ending frame index.
  36162. * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
  36163. * @return {Array} An array of Frames between the start and end index values, or an empty array if none were found.
  36164. */
  36165. getFrameRange: function (start, end, output) {
  36166. if (typeof output === "undefined") { output = []; }
  36167. for (var i = start; i <= end; i++)
  36168. {
  36169. output.push(this._frames[i]);
  36170. }
  36171. return output;
  36172. },
  36173. /**
  36174. * Returns all of the Frames in this FrameData set where the frame index is found in the input array.
  36175. * The frames are returned in the output array, or if none is provided in a new Array object.
  36176. *
  36177. * @method Phaser.FrameData#getFrames
  36178. * @param {Array} frames - An Array containing the indexes of the frames to retrieve. If the array is empty then all frames in the FrameData are returned.
  36179. * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false)
  36180. * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
  36181. * @return {Array} An array of all Frames in this FrameData set matching the given names or IDs.
  36182. */
  36183. getFrames: function (frames, useNumericIndex, output) {
  36184. if (typeof useNumericIndex === "undefined") { useNumericIndex = true; }
  36185. if (typeof output === "undefined") { output = []; }
  36186. if (typeof frames === "undefined" || frames.length === 0)
  36187. {
  36188. // No input array, so we loop through all frames
  36189. for (var i = 0; i < this._frames.length; i++)
  36190. {
  36191. // We only need the indexes
  36192. output.push(this._frames[i]);
  36193. }
  36194. }
  36195. else
  36196. {
  36197. // Input array given, loop through that instead
  36198. for (var i = 0, len = frames.length; i < len; i++)
  36199. {
  36200. // Does the input array contain names or indexes?
  36201. if (useNumericIndex)
  36202. {
  36203. // The actual frame
  36204. output.push(this.getFrame(frames[i]));
  36205. }
  36206. else
  36207. {
  36208. // The actual frame
  36209. output.push(this.getFrameByName(frames[i]));
  36210. }
  36211. }
  36212. }
  36213. return output;
  36214. },
  36215. /**
  36216. * Returns all of the Frame indexes in this FrameData set.
  36217. * The frames indexes are returned in the output array, or if none is provided in a new Array object.
  36218. *
  36219. * @method Phaser.FrameData#getFrameIndexes
  36220. * @param {Array} frames - An Array containing the indexes of the frames to retrieve. If the array is empty then all frames in the FrameData are returned.
  36221. * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false)
  36222. * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
  36223. * @return {Array} An array of all Frame indexes matching the given names or IDs.
  36224. */
  36225. getFrameIndexes: function (frames, useNumericIndex, output) {
  36226. if (typeof useNumericIndex === "undefined") { useNumericIndex = true; }
  36227. if (typeof output === "undefined") { output = []; }
  36228. if (typeof frames === "undefined" || frames.length === 0)
  36229. {
  36230. // No frames array, so we loop through all frames
  36231. for (var i = 0, len = this._frames.length; i < len; i++)
  36232. {
  36233. output.push(this._frames[i].index);
  36234. }
  36235. }
  36236. else
  36237. {
  36238. // Input array given, loop through that instead
  36239. for (var i = 0, len = frames.length; i < len; i++)
  36240. {
  36241. // Does the frames array contain names or indexes?
  36242. if (useNumericIndex)
  36243. {
  36244. output.push(frames[i]);
  36245. }
  36246. else
  36247. {
  36248. if (this.getFrameByName(frames[i]))
  36249. {
  36250. output.push(this.getFrameByName(frames[i]).index);
  36251. }
  36252. }
  36253. }
  36254. }
  36255. return output;
  36256. }
  36257. };
  36258. Phaser.FrameData.prototype.constructor = Phaser.FrameData;
  36259. /**
  36260. * @name Phaser.FrameData#total
  36261. * @property {number} total - The total number of frames in this FrameData set.
  36262. * @readonly
  36263. */
  36264. Object.defineProperty(Phaser.FrameData.prototype, "total", {
  36265. get: function () {
  36266. return this._frames.length;
  36267. }
  36268. });
  36269. /**
  36270. * @author Richard Davey <rich@photonstorm.com>
  36271. * @copyright 2014 Photon Storm Ltd.
  36272. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  36273. */
  36274. /**
  36275. * Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations.
  36276. *
  36277. * @class Phaser.AnimationParser
  36278. */
  36279. Phaser.AnimationParser = {
  36280. /**
  36281. * Parse a Sprite Sheet and extract the animation frame data from it.
  36282. *
  36283. * @method Phaser.AnimationParser.spriteSheet
  36284. * @param {Phaser.Game} game - A reference to the currently running game.
  36285. * @param {string} key - The Game.Cache asset key of the Sprite Sheet image.
  36286. * @param {number} frameWidth - The fixed width of each frame of the animation.
  36287. * @param {number} frameHeight - The fixed height of each frame of the animation.
  36288. * @param {number} [frameMax=-1] - The total number of animation frames to extact from the Sprite Sheet. The default value of -1 means "extract all frames".
  36289. * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here.
  36290. * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here.
  36291. * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
  36292. */
  36293. spriteSheet: function (game, key, frameWidth, frameHeight, frameMax, margin, spacing) {
  36294. // How big is our image?
  36295. var img = game.cache.getImage(key);
  36296. if (img == null)
  36297. {
  36298. return null;
  36299. }
  36300. var width = img.width;
  36301. var height = img.height;
  36302. if (frameWidth <= 0)
  36303. {
  36304. frameWidth = Math.floor(-width / Math.min(-1, frameWidth));
  36305. }
  36306. if (frameHeight <= 0)
  36307. {
  36308. frameHeight = Math.floor(-height / Math.min(-1, frameHeight));
  36309. }
  36310. var row = Math.floor((width - margin) / (frameWidth + spacing));
  36311. var column = Math.floor((height - margin) / (frameHeight + spacing));
  36312. var total = row * column;
  36313. if (frameMax !== -1)
  36314. {
  36315. total = frameMax;
  36316. }
  36317. // Zero or smaller than frame sizes?
  36318. if (width === 0 || height === 0 || width < frameWidth || height < frameHeight || total === 0)
  36319. {
  36320. console.warn("Phaser.AnimationParser.spriteSheet: '" + key + "'s width/height zero or width/height < given frameWidth/frameHeight");
  36321. return null;
  36322. }
  36323. // Let's create some frames then
  36324. var data = new Phaser.FrameData();
  36325. var x = margin;
  36326. var y = margin;
  36327. for (var i = 0; i < total; i++)
  36328. {
  36329. var uuid = game.rnd.uuid();
  36330. // uuid needed?
  36331. data.addFrame(new Phaser.Frame(i, x, y, frameWidth, frameHeight, '', uuid));
  36332. PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[key], {
  36333. x: x,
  36334. y: y,
  36335. width: frameWidth,
  36336. height: frameHeight
  36337. });
  36338. x += frameWidth + spacing;
  36339. if (x + frameWidth > width)
  36340. {
  36341. x = margin;
  36342. y += frameHeight + spacing;
  36343. }
  36344. }
  36345. return data;
  36346. },
  36347. /**
  36348. * Parse the JSON data and extract the animation frame data from it.
  36349. *
  36350. * @method Phaser.AnimationParser.JSONData
  36351. * @param {Phaser.Game} game - A reference to the currently running game.
  36352. * @param {Object} json - The JSON data from the Texture Atlas. Must be in Array format.
  36353. * @param {string} cacheKey - The Game.Cache asset key of the texture image.
  36354. * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
  36355. */
  36356. JSONData: function (game, json, cacheKey) {
  36357. // Malformed?
  36358. if (!json['frames'])
  36359. {
  36360. console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array");
  36361. console.log(json);
  36362. return;
  36363. }
  36364. // Let's create some frames then
  36365. var data = new Phaser.FrameData();
  36366. // By this stage frames is a fully parsed array
  36367. var frames = json['frames'];
  36368. var newFrame;
  36369. for (var i = 0; i < frames.length; i++)
  36370. {
  36371. var uuid = game.rnd.uuid();
  36372. newFrame = data.addFrame(new Phaser.Frame(
  36373. i,
  36374. frames[i].frame.x,
  36375. frames[i].frame.y,
  36376. frames[i].frame.w,
  36377. frames[i].frame.h,
  36378. frames[i].filename,
  36379. uuid
  36380. ));
  36381. PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[cacheKey], {
  36382. x: frames[i].frame.x,
  36383. y: frames[i].frame.y,
  36384. width: frames[i].frame.w,
  36385. height: frames[i].frame.h
  36386. });
  36387. if (frames[i].trimmed)
  36388. {
  36389. newFrame.setTrim(
  36390. frames[i].trimmed,
  36391. frames[i].sourceSize.w,
  36392. frames[i].sourceSize.h,
  36393. frames[i].spriteSourceSize.x,
  36394. frames[i].spriteSourceSize.y,
  36395. frames[i].spriteSourceSize.w,
  36396. frames[i].spriteSourceSize.h
  36397. );
  36398. }
  36399. }
  36400. return data;
  36401. },
  36402. /**
  36403. * Parse the JSON data and extract the animation frame data from it.
  36404. *
  36405. * @method Phaser.AnimationParser.JSONDataHash
  36406. * @param {Phaser.Game} game - A reference to the currently running game.
  36407. * @param {Object} json - The JSON data from the Texture Atlas. Must be in JSON Hash format.
  36408. * @param {string} cacheKey - The Game.Cache asset key of the texture image.
  36409. * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
  36410. */
  36411. JSONDataHash: function (game, json, cacheKey) {
  36412. // Malformed?
  36413. if (!json['frames'])
  36414. {
  36415. console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object");
  36416. console.log(json);
  36417. return;
  36418. }
  36419. // Let's create some frames then
  36420. var data = new Phaser.FrameData();
  36421. // By this stage frames is a fully parsed array
  36422. var frames = json['frames'];
  36423. var newFrame;
  36424. var i = 0;
  36425. for (var key in frames)
  36426. {
  36427. var uuid = game.rnd.uuid();
  36428. newFrame = data.addFrame(new Phaser.Frame(
  36429. i,
  36430. frames[key].frame.x,
  36431. frames[key].frame.y,
  36432. frames[key].frame.w,
  36433. frames[key].frame.h,
  36434. key,
  36435. uuid
  36436. ));
  36437. PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[cacheKey], {
  36438. x: frames[key].frame.x,
  36439. y: frames[key].frame.y,
  36440. width: frames[key].frame.w,
  36441. height: frames[key].frame.h
  36442. });
  36443. if (frames[key].trimmed)
  36444. {
  36445. newFrame.setTrim(
  36446. frames[key].trimmed,
  36447. frames[key].sourceSize.w,
  36448. frames[key].sourceSize.h,
  36449. frames[key].spriteSourceSize.x,
  36450. frames[key].spriteSourceSize.y,
  36451. frames[key].spriteSourceSize.w,
  36452. frames[key].spriteSourceSize.h
  36453. );
  36454. }
  36455. i++;
  36456. }
  36457. return data;
  36458. },
  36459. /**
  36460. * Parse the XML data and extract the animation frame data from it.
  36461. *
  36462. * @method Phaser.AnimationParser.XMLData
  36463. * @param {Phaser.Game} game - A reference to the currently running game.
  36464. * @param {Object} xml - The XML data from the Texture Atlas. Must be in Starling XML format.
  36465. * @param {string} cacheKey - The Game.Cache asset key of the texture image.
  36466. * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
  36467. */
  36468. XMLData: function (game, xml, cacheKey) {
  36469. // Malformed?
  36470. if (!xml.getElementsByTagName('TextureAtlas'))
  36471. {
  36472. console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing <TextureAtlas> tag");
  36473. return;
  36474. }
  36475. // Let's create some frames then
  36476. var data = new Phaser.FrameData();
  36477. var frames = xml.getElementsByTagName('SubTexture');
  36478. var newFrame;
  36479. var uuid;
  36480. var name;
  36481. var frame;
  36482. var x;
  36483. var y;
  36484. var width;
  36485. var height;
  36486. var frameX;
  36487. var frameY;
  36488. var frameWidth;
  36489. var frameHeight;
  36490. for (var i = 0; i < frames.length; i++)
  36491. {
  36492. uuid = game.rnd.uuid();
  36493. frame = frames[i].attributes;
  36494. name = frame.name.nodeValue;
  36495. x = parseInt(frame.x.nodeValue, 10);
  36496. y = parseInt(frame.y.nodeValue, 10);
  36497. width = parseInt(frame.width.nodeValue, 10);
  36498. height = parseInt(frame.height.nodeValue, 10);
  36499. frameX = null;
  36500. frameY = null;
  36501. if (frame.frameX)
  36502. {
  36503. frameX = Math.abs(parseInt(frame.frameX.nodeValue, 10));
  36504. frameY = Math.abs(parseInt(frame.frameY.nodeValue, 10));
  36505. frameWidth = parseInt(frame.frameWidth.nodeValue, 10);
  36506. frameHeight = parseInt(frame.frameHeight.nodeValue, 10);
  36507. }
  36508. newFrame = data.addFrame(new Phaser.Frame(i, x, y, width, height, name, uuid));
  36509. PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[cacheKey], {
  36510. x: x,
  36511. y: y,
  36512. width: width,
  36513. height: height
  36514. });
  36515. // Trimmed?
  36516. if (frameX !== null || frameY !== null)
  36517. {
  36518. newFrame.setTrim(true, width, height, frameX, frameY, frameWidth, frameHeight);
  36519. }
  36520. }
  36521. return data;
  36522. }
  36523. };
  36524. /**
  36525. * @author Richard Davey <rich@photonstorm.com>
  36526. * @copyright 2014 Photon Storm Ltd.
  36527. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  36528. */
  36529. /**
  36530. * Phaser.Cache constructor.
  36531. *
  36532. * @class Phaser.Cache
  36533. * @classdesc A game only has one instance of a Cache and it is used to store all externally loaded assets such as images, sounds and data files as a result of Loader calls. Cached items use string based keys for look-up.
  36534. * @constructor
  36535. * @param {Phaser.Game} game - A reference to the currently running game.
  36536. */
  36537. Phaser.Cache = function (game) {
  36538. /**
  36539. * @property {Phaser.Game} game - Local reference to game.
  36540. */
  36541. this.game = game;
  36542. /**
  36543. * @property {object} game - Canvas key-value container.
  36544. * @private
  36545. */
  36546. this._canvases = {};
  36547. /**
  36548. * @property {object} _images - Image key-value container.
  36549. * @private
  36550. */
  36551. this._images = {};
  36552. /**
  36553. * @property {object} _textures - RenderTexture key-value container.
  36554. * @private
  36555. */
  36556. this._textures = {};
  36557. /**
  36558. * @property {object} _sounds - Sound key-value container.
  36559. * @private
  36560. */
  36561. this._sounds = {};
  36562. /**
  36563. * @property {object} _text - Text key-value container.
  36564. * @private
  36565. */
  36566. this._text = {};
  36567. /**
  36568. * @property {object} _text - Text key-value container.
  36569. * @private
  36570. */
  36571. this._json = {};
  36572. /**
  36573. * @property {object} _physics - Physics data key-value container.
  36574. * @private
  36575. */
  36576. this._physics = {};
  36577. /**
  36578. * @property {object} _tilemaps - Tilemap key-value container.
  36579. * @private
  36580. */
  36581. this._tilemaps = {};
  36582. /**
  36583. * @property {object} _binary - Binary file key-value container.
  36584. * @private
  36585. */
  36586. this._binary = {};
  36587. /**
  36588. * @property {object} _bitmapDatas - BitmapData key-value container.
  36589. * @private
  36590. */
  36591. this._bitmapDatas = {};
  36592. /**
  36593. * @property {object} _bitmapFont - BitmapFont key-value container.
  36594. * @private
  36595. */
  36596. this._bitmapFont = {};
  36597. this.addDefaultImage();
  36598. this.addMissingImage();
  36599. /**
  36600. * @property {Phaser.Signal} onSoundUnlock - This event is dispatched when the sound system is unlocked via a touch event on cellular devices.
  36601. */
  36602. this.onSoundUnlock = new Phaser.Signal();
  36603. /**
  36604. * @property {array} _cacheMap - Const to cache object look-up array.
  36605. */
  36606. this._cacheMap = [];
  36607. this._cacheMap[Phaser.Cache.CANVAS] = this._canvases;
  36608. this._cacheMap[Phaser.Cache.IMAGE] = this._images;
  36609. this._cacheMap[Phaser.Cache.TEXTURE] = this._textures;
  36610. this._cacheMap[Phaser.Cache.SOUND] = this._sounds;
  36611. this._cacheMap[Phaser.Cache.TEXT] = this._text;
  36612. this._cacheMap[Phaser.Cache.PHYSICS] = this._physics;
  36613. this._cacheMap[Phaser.Cache.TILEMAP] = this._tilemaps;
  36614. this._cacheMap[Phaser.Cache.BINARY] = this._binary;
  36615. this._cacheMap[Phaser.Cache.BITMAPDATA] = this._bitmapDatas;
  36616. this._cacheMap[Phaser.Cache.BITMAPFONT] = this._bitmapFont;
  36617. this._cacheMap[Phaser.Cache.JSON] = this._json;
  36618. };
  36619. /**
  36620. * @constant
  36621. * @type {number}
  36622. */
  36623. Phaser.Cache.CANVAS = 1;
  36624. /**
  36625. * @constant
  36626. * @type {number}
  36627. */
  36628. Phaser.Cache.IMAGE = 2;
  36629. /**
  36630. * @constant
  36631. * @type {number}
  36632. */
  36633. Phaser.Cache.TEXTURE = 3;
  36634. /**
  36635. * @constant
  36636. * @type {number}
  36637. */
  36638. Phaser.Cache.SOUND = 4;
  36639. /**
  36640. * @constant
  36641. * @type {number}
  36642. */
  36643. Phaser.Cache.TEXT = 5;
  36644. /**
  36645. * @constant
  36646. * @type {number}
  36647. */
  36648. Phaser.Cache.PHYSICS = 6;
  36649. /**
  36650. * @constant
  36651. * @type {number}
  36652. */
  36653. Phaser.Cache.TILEMAP = 7;
  36654. /**
  36655. * @constant
  36656. * @type {number}
  36657. */
  36658. Phaser.Cache.BINARY = 8;
  36659. /**
  36660. * @constant
  36661. * @type {number}
  36662. */
  36663. Phaser.Cache.BITMAPDATA = 9;
  36664. /**
  36665. * @constant
  36666. * @type {number}
  36667. */
  36668. Phaser.Cache.BITMAPFONT = 10;
  36669. /**
  36670. * @constant
  36671. * @type {number}
  36672. */
  36673. Phaser.Cache.JSON = 11;
  36674. Phaser.Cache.prototype = {
  36675. /**
  36676. * Add a new canvas object in to the cache.
  36677. *
  36678. * @method Phaser.Cache#addCanvas
  36679. * @param {string} key - Asset key for this canvas.
  36680. * @param {HTMLCanvasElement} canvas - Canvas DOM element.
  36681. * @param {CanvasRenderingContext2D} context - Render context of this canvas.
  36682. */
  36683. addCanvas: function (key, canvas, context) {
  36684. this._canvases[key] = { canvas: canvas, context: context };
  36685. },
  36686. /**
  36687. * Add a binary object in to the cache.
  36688. *
  36689. * @method Phaser.Cache#addBinary
  36690. * @param {string} key - Asset key for this binary data.
  36691. * @param {object} binaryData - The binary object to be addded to the cache.
  36692. */
  36693. addBinary: function (key, binaryData) {
  36694. this._binary[key] = binaryData;
  36695. },
  36696. /**
  36697. * Add a BitmapData object in to the cache.
  36698. *
  36699. * @method Phaser.Cache#addBitmapData
  36700. * @param {string} key - Asset key for this BitmapData.
  36701. * @param {Phaser.BitmapData} bitmapData - The BitmapData object to be addded to the cache.
  36702. * @return {Phaser.BitmapData} The BitmapData object to be addded to the cache.
  36703. */
  36704. addBitmapData: function (key, bitmapData) {
  36705. this._bitmapDatas[key] = bitmapData;
  36706. return bitmapData;
  36707. },
  36708. /**
  36709. * Add a new Phaser.RenderTexture in to the cache.
  36710. *
  36711. * @method Phaser.Cache#addRenderTexture
  36712. * @param {string} key - The unique key by which you will reference this object.
  36713. * @param {Phaser.Texture} texture - The texture to use as the base of the RenderTexture.
  36714. */
  36715. addRenderTexture: function (key, texture) {
  36716. var frame = new Phaser.Frame(0, 0, 0, texture.width, texture.height, '', '');
  36717. this._textures[key] = { texture: texture, frame: frame };
  36718. },
  36719. /**
  36720. * Add a new sprite sheet in to the cache.
  36721. *
  36722. * @method Phaser.Cache#addSpriteSheet
  36723. * @param {string} key - The unique key by which you will reference this object.
  36724. * @param {string} url - URL of this sprite sheet file.
  36725. * @param {object} data - Extra sprite sheet data.
  36726. * @param {number} frameWidth - Width of the sprite sheet.
  36727. * @param {number} frameHeight - Height of the sprite sheet.
  36728. * @param {number} [frameMax=-1] - How many frames stored in the sprite sheet. If -1 then it divides the whole sheet evenly.
  36729. * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here.
  36730. * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here.
  36731. */
  36732. addSpriteSheet: function (key, url, data, frameWidth, frameHeight, frameMax, margin, spacing) {
  36733. this._images[key] = { url: url, data: data, spriteSheet: true, frameWidth: frameWidth, frameHeight: frameHeight, margin: margin, spacing: spacing };
  36734. PIXI.BaseTextureCache[key] = new PIXI.BaseTexture(data);
  36735. PIXI.TextureCache[key] = new PIXI.Texture(PIXI.BaseTextureCache[key]);
  36736. this._images[key].frameData = Phaser.AnimationParser.spriteSheet(this.game, key, frameWidth, frameHeight, frameMax, margin, spacing);
  36737. },
  36738. /**
  36739. * Add a new tilemap to the Cache.
  36740. *
  36741. * @method Phaser.Cache#addTilemap
  36742. * @param {string} key - The unique key by which you will reference this object.
  36743. * @param {string} url - URL of the tilemap image.
  36744. * @param {object} mapData - The tilemap data object (either a CSV or JSON file).
  36745. * @param {number} format - The format of the tilemap data.
  36746. */
  36747. addTilemap: function (key, url, mapData, format) {
  36748. this._tilemaps[key] = { url: url, data: mapData, format: format };
  36749. },
  36750. /**
  36751. * Add a new texture atlas to the Cache.
  36752. *
  36753. * @method Phaser.Cache#addTextureAtlas
  36754. * @param {string} key - The unique key by which you will reference this object.
  36755. * @param {string} url - URL of this texture atlas file.
  36756. * @param {object} data - Extra texture atlas data.
  36757. * @param {object} atlasData - Texture atlas frames data.
  36758. * @param {number} format - The format of the texture atlas.
  36759. */
  36760. addTextureAtlas: function (key, url, data, atlasData, format) {
  36761. this._images[key] = { url: url, data: data, spriteSheet: true };
  36762. PIXI.BaseTextureCache[key] = new PIXI.BaseTexture(data);
  36763. PIXI.TextureCache[key] = new PIXI.Texture(PIXI.BaseTextureCache[key]);
  36764. if (format == Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY)
  36765. {
  36766. this._images[key].frameData = Phaser.AnimationParser.JSONData(this.game, atlasData, key);
  36767. }
  36768. else if (format == Phaser.Loader.TEXTURE_ATLAS_JSON_HASH)
  36769. {
  36770. this._images[key].frameData = Phaser.AnimationParser.JSONDataHash(this.game, atlasData, key);
  36771. }
  36772. else if (format == Phaser.Loader.TEXTURE_ATLAS_XML_STARLING)
  36773. {
  36774. this._images[key].frameData = Phaser.AnimationParser.XMLData(this.game, atlasData, key);
  36775. }
  36776. },
  36777. /**
  36778. * Add a new Bitmap Font to the Cache.
  36779. *
  36780. * @method Phaser.Cache#addBitmapFont
  36781. * @param {string} key - The unique key by which you will reference this object.
  36782. * @param {string} url - URL of this font xml file.
  36783. * @param {object} data - Extra font data.
  36784. * @param {object} xmlData - Texture atlas frames data.
  36785. * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here.
  36786. * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here.
  36787. */
  36788. addBitmapFont: function (key, url, data, xmlData, xSpacing, ySpacing) {
  36789. this._images[key] = { url: url, data: data, spriteSheet: true };
  36790. PIXI.BaseTextureCache[key] = new PIXI.BaseTexture(data);
  36791. PIXI.TextureCache[key] = new PIXI.Texture(PIXI.BaseTextureCache[key]);
  36792. Phaser.LoaderParser.bitmapFont(this.game, xmlData, key, xSpacing, ySpacing);
  36793. },
  36794. /**
  36795. * Add a new physics data object to the Cache.
  36796. *
  36797. * @method Phaser.Cache#addTilemap
  36798. * @param {string} key - The unique key by which you will reference this object.
  36799. * @param {string} url - URL of the physics json data.
  36800. * @param {object} JSONData - The physics data object (a JSON file).
  36801. * @param {number} format - The format of the physics data.
  36802. */
  36803. addPhysicsData: function (key, url, JSONData, format) {
  36804. this._physics[key] = { url: url, data: JSONData, format: format };
  36805. },
  36806. /**
  36807. * Adds a default image to be used in special cases such as WebGL Filters. Is mapped to the key __default.
  36808. *
  36809. * @method Phaser.Cache#addDefaultImage
  36810. * @protected
  36811. */
  36812. addDefaultImage: function () {
  36813. var img = new Image();
  36814. img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==";
  36815. this._images['__default'] = { url: null, data: img, spriteSheet: false };
  36816. this._images['__default'].frame = new Phaser.Frame(0, 0, 0, 32, 32, '', '');
  36817. PIXI.BaseTextureCache['__default'] = new PIXI.BaseTexture(img);
  36818. PIXI.TextureCache['__default'] = new PIXI.Texture(PIXI.BaseTextureCache['__default']);
  36819. },
  36820. /**
  36821. * Adds an image to be used when a key is wrong / missing. Is mapped to the key __missing.
  36822. *
  36823. * @method Phaser.Cache#addMissingImage
  36824. * @protected
  36825. */
  36826. addMissingImage: function () {
  36827. var img = new Image();
  36828. img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==";
  36829. this._images['__missing'] = { url: null, data: img, spriteSheet: false };
  36830. this._images['__missing'].frame = new Phaser.Frame(0, 0, 0, 32, 32, '', '');
  36831. PIXI.BaseTextureCache['__missing'] = new PIXI.BaseTexture(img);
  36832. PIXI.TextureCache['__missing'] = new PIXI.Texture(PIXI.BaseTextureCache['__missing']);
  36833. },
  36834. /**
  36835. * Add a new text data.
  36836. *
  36837. * @method Phaser.Cache#addText
  36838. * @param {string} key - Asset key for the text data.
  36839. * @param {string} url - URL of this text data file.
  36840. * @param {object} data - Extra text data.
  36841. */
  36842. addText: function (key, url, data) {
  36843. this._text[key] = { url: url, data: data };
  36844. },
  36845. /**
  36846. * Add a new json object into the cache.
  36847. *
  36848. * @method Phaser.Cache#addJSON
  36849. * @param {string} key - Asset key for the text data.
  36850. * @param {string} url - URL of this text data file.
  36851. * @param {object} data - Extra text data.
  36852. */
  36853. addJSON: function (key, url, data) {
  36854. this._json[key] = { url: url, data: data };
  36855. },
  36856. /**
  36857. * Adds an Image file into the Cache. The file must have already been loaded, typically via Phaser.Loader.
  36858. *
  36859. * @method Phaser.Cache#addImage
  36860. * @param {string} key - The unique key by which you will reference this object.
  36861. * @param {string} url - URL of this image file.
  36862. * @param {object} data - Extra image data.
  36863. */
  36864. addImage: function (key, url, data) {
  36865. this._images[key] = { url: url, data: data, spriteSheet: false };
  36866. this._images[key].frame = new Phaser.Frame(0, 0, 0, data.width, data.height, key, this.game.rnd.uuid());
  36867. PIXI.BaseTextureCache[key] = new PIXI.BaseTexture(data);
  36868. PIXI.TextureCache[key] = new PIXI.Texture(PIXI.BaseTextureCache[key]);
  36869. },
  36870. /**
  36871. * Adds a Sound file into the Cache. The file must have already been loaded, typically via Phaser.Loader.
  36872. *
  36873. * @method Phaser.Cache#addSound
  36874. * @param {string} key - Asset key for the sound.
  36875. * @param {string} url - URL of this sound file.
  36876. * @param {object} data - Extra sound data.
  36877. * @param {boolean} webAudio - True if the file is using web audio.
  36878. * @param {boolean} audioTag - True if the file is using legacy HTML audio.
  36879. */
  36880. addSound: function (key, url, data, webAudio, audioTag) {
  36881. webAudio = webAudio || true;
  36882. audioTag = audioTag || false;
  36883. var decoded = false;
  36884. if (audioTag)
  36885. {
  36886. decoded = true;
  36887. }
  36888. this._sounds[key] = { url: url, data: data, isDecoding: false, decoded: decoded, webAudio: webAudio, audioTag: audioTag, locked: this.game.sound.touchLocked };
  36889. },
  36890. /**
  36891. * Reload a Sound file from the server.
  36892. *
  36893. * @method Phaser.Cache#reloadSound
  36894. * @param {string} key - Asset key for the sound.
  36895. */
  36896. reloadSound: function (key) {
  36897. var _this = this;
  36898. if (this._sounds[key])
  36899. {
  36900. this._sounds[key].data.src = this._sounds[key].url;
  36901. this._sounds[key].data.addEventListener('canplaythrough', function () {
  36902. return _this.reloadSoundComplete(key);
  36903. }, false);
  36904. this._sounds[key].data.load();
  36905. }
  36906. },
  36907. /**
  36908. * Fires the onSoundUnlock event when the sound has completed reloading.
  36909. *
  36910. * @method Phaser.Cache#reloadSoundComplete
  36911. * @param {string} key - Asset key for the sound.
  36912. */
  36913. reloadSoundComplete: function (key) {
  36914. if (this._sounds[key])
  36915. {
  36916. this._sounds[key].locked = false;
  36917. this.onSoundUnlock.dispatch(key);
  36918. }
  36919. },
  36920. /**
  36921. * Updates the sound object in the cache.
  36922. *
  36923. * @method Phaser.Cache#updateSound
  36924. * @param {string} key - Asset key for the sound.
  36925. */
  36926. updateSound: function (key, property, value) {
  36927. if (this._sounds[key])
  36928. {
  36929. this._sounds[key][property] = value;
  36930. }
  36931. },
  36932. /**
  36933. * Add a new decoded sound.
  36934. *
  36935. * @method Phaser.Cache#decodedSound
  36936. * @param {string} key - Asset key for the sound.
  36937. * @param {object} data - Extra sound data.
  36938. */
  36939. decodedSound: function (key, data) {
  36940. this._sounds[key].data = data;
  36941. this._sounds[key].decoded = true;
  36942. this._sounds[key].isDecoding = false;
  36943. },
  36944. /**
  36945. * Get a canvas object from the cache by its key.
  36946. *
  36947. * @method Phaser.Cache#getCanvas
  36948. * @param {string} key - Asset key of the canvas to retrieve from the Cache.
  36949. * @return {object} The canvas object.
  36950. */
  36951. getCanvas: function (key) {
  36952. if (this._canvases[key])
  36953. {
  36954. return this._canvases[key].canvas;
  36955. }
  36956. else
  36957. {
  36958. console.warn('Phaser.Cache.getCanvas: Invalid key: "' + key + '"');
  36959. }
  36960. },
  36961. /**
  36962. * Get a BitmapData object from the cache by its key.
  36963. *
  36964. * @method Phaser.Cache#getBitmapData
  36965. * @param {string} key - Asset key of the BitmapData object to retrieve from the Cache.
  36966. * @return {Phaser.BitmapData} The requested BitmapData object if found, or null if not.
  36967. */
  36968. getBitmapData: function (key) {
  36969. if (this._bitmapDatas[key])
  36970. {
  36971. return this._bitmapDatas[key];
  36972. }
  36973. else
  36974. {
  36975. console.warn('Phaser.Cache.getBitmapData: Invalid key: "' + key + '"');
  36976. }
  36977. },
  36978. /**
  36979. * Get a BitmapFont object from the cache by its key.
  36980. *
  36981. * @method Phaser.Cache#getBitmapFont
  36982. * @param {string} key - Asset key of the BitmapFont object to retrieve from the Cache.
  36983. * @return {Phaser.BitmapFont} The requested BitmapFont object if found, or null if not.
  36984. */
  36985. getBitmapFont: function (key) {
  36986. if (this._bitmapFont[key])
  36987. {
  36988. return this._bitmapFont[key];
  36989. }
  36990. else
  36991. {
  36992. console.warn('Phaser.Cache.getBitmapFont: Invalid key: "' + key + '"');
  36993. }
  36994. },
  36995. /**
  36996. * Get a physics data object from the cache by its key. You can get either the entire data set, a single object or a single fixture of an object from it.
  36997. *
  36998. * @method Phaser.Cache#getPhysicsData
  36999. * @param {string} key - Asset key of the physics data object to retrieve from the Cache.
  37000. * @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.
  37001. * @param {string} fixtureKey - Fixture key of fixture inside an object. This key can be set per fixture with the Phaser Exporter.
  37002. * @return {object} The requested physics object data if found.
  37003. */
  37004. getPhysicsData: function (key, object, fixtureKey) {
  37005. if (typeof object === 'undefined' || object === null)
  37006. {
  37007. // Get 'em all
  37008. if (this._physics[key])
  37009. {
  37010. return this._physics[key].data;
  37011. }
  37012. else
  37013. {
  37014. console.warn('Phaser.Cache.getPhysicsData: Invalid key: "' + key + '"');
  37015. }
  37016. }
  37017. else
  37018. {
  37019. if (this._physics[key] && this._physics[key].data[object])
  37020. {
  37021. var fixtures = this._physics[key].data[object];
  37022. //try to find a fixture by it's fixture key if given
  37023. if (fixtures && fixtureKey)
  37024. {
  37025. for (var fixture in fixtures)
  37026. {
  37027. // This contains the fixture data of a polygon or a circle
  37028. fixture = fixtures[fixture];
  37029. // Test the key
  37030. if (fixture.fixtureKey === fixtureKey)
  37031. {
  37032. return fixture;
  37033. }
  37034. }
  37035. // We did not find the requested fixture
  37036. console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "' + fixtureKey + ' in ' + key + '"');
  37037. }
  37038. else
  37039. {
  37040. return fixtures;
  37041. }
  37042. }
  37043. else
  37044. {
  37045. console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "' + key + ' / ' + object + '"');
  37046. }
  37047. }
  37048. return null;
  37049. },
  37050. /**
  37051. * Checks if a key for the given cache object type exists.
  37052. *
  37053. * @method Phaser.Cache#checkKey
  37054. * @param {number} type - The Cache type to check against. I.e. Phaser.Cache.CANVAS, Phaser.Cache.IMAGE, Phaser.Cache.JSON, etc.
  37055. * @param {string} key - Asset key of the image to check is in the Cache.
  37056. * @return {boolean} True if the key exists, otherwise false.
  37057. */
  37058. checkKey: function (type, key) {
  37059. if (this._cacheMap[type][key])
  37060. {
  37061. return true;
  37062. }
  37063. return false;
  37064. },
  37065. /**
  37066. * Checks if the given key exists in the Canvas Cache.
  37067. *
  37068. * @method Phaser.Cache#checkCanvasKey
  37069. * @param {string} key - Asset key of the image to check is in the Cache.
  37070. * @return {boolean} True if the key exists, otherwise false.
  37071. */
  37072. checkCanvasKey: function (key) {
  37073. return this.checkKey(Phaser.Cache.CANVAS, key);
  37074. },
  37075. /**
  37076. * Checks if the given key exists in the Image Cache. Note that this also includes Texture Atlases, Sprite Sheets and Retro Fonts.
  37077. *
  37078. * @method Phaser.Cache#checkImageKey
  37079. * @param {string} key - Asset key of the image to check is in the Cache.
  37080. * @return {boolean} True if the key exists, otherwise false.
  37081. */
  37082. checkImageKey: function (key) {
  37083. return this.checkKey(Phaser.Cache.IMAGE, key);
  37084. },
  37085. /**
  37086. * Checks if the given key exists in the Texture Cache.
  37087. *
  37088. * @method Phaser.Cache#checkTextureKey
  37089. * @param {string} key - Asset key of the image to check is in the Cache.
  37090. * @return {boolean} True if the key exists, otherwise false.
  37091. */
  37092. checkTextureKey: function (key) {
  37093. return this.checkKey(Phaser.Cache.TEXTURE, key);
  37094. },
  37095. /**
  37096. * Checks if the given key exists in the Sound Cache.
  37097. *
  37098. * @method Phaser.Cache#checkSoundKey
  37099. * @param {string} key - Asset key of the image to check is in the Cache.
  37100. * @return {boolean} True if the key exists, otherwise false.
  37101. */
  37102. checkSoundKey: function (key) {
  37103. return this.checkKey(Phaser.Cache.SOUND, key);
  37104. },
  37105. /**
  37106. * Checks if the given key exists in the Text Cache.
  37107. *
  37108. * @method Phaser.Cache#checkTextKey
  37109. * @param {string} key - Asset key of the image to check is in the Cache.
  37110. * @return {boolean} True if the key exists, otherwise false.
  37111. */
  37112. checkTextKey: function (key) {
  37113. return this.checkKey(Phaser.Cache.TEXT, key);
  37114. },
  37115. /**
  37116. * Checks if the given key exists in the Physics Cache.
  37117. *
  37118. * @method Phaser.Cache#checkPhysicsKey
  37119. * @param {string} key - Asset key of the image to check is in the Cache.
  37120. * @return {boolean} True if the key exists, otherwise false.
  37121. */
  37122. checkPhysicsKey: function (key) {
  37123. return this.checkKey(Phaser.Cache.PHYSICS, key);
  37124. },
  37125. /**
  37126. * Checks if the given key exists in the Tilemap Cache.
  37127. *
  37128. * @method Phaser.Cache#checkTilemapKey
  37129. * @param {string} key - Asset key of the image to check is in the Cache.
  37130. * @return {boolean} True if the key exists, otherwise false.
  37131. */
  37132. checkTilemapKey: function (key) {
  37133. return this.checkKey(Phaser.Cache.TILEMAP, key);
  37134. },
  37135. /**
  37136. * Checks if the given key exists in the Binary Cache.
  37137. *
  37138. * @method Phaser.Cache#checkBinaryKey
  37139. * @param {string} key - Asset key of the image to check is in the Cache.
  37140. * @return {boolean} True if the key exists, otherwise false.
  37141. */
  37142. checkBinaryKey: function (key) {
  37143. return this.checkKey(Phaser.Cache.BINARY, key);
  37144. },
  37145. /**
  37146. * Checks if the given key exists in the BitmapData Cache.
  37147. *
  37148. * @method Phaser.Cache#checkBitmapDataKey
  37149. * @param {string} key - Asset key of the image to check is in the Cache.
  37150. * @return {boolean} True if the key exists, otherwise false.
  37151. */
  37152. checkBitmapDataKey: function (key) {
  37153. return this.checkKey(Phaser.Cache.BITMAPDATA, key);
  37154. },
  37155. /**
  37156. * Checks if the given key exists in the BitmapFont Cache.
  37157. *
  37158. * @method Phaser.Cache#checkBitmapFontKey
  37159. * @param {string} key - Asset key of the image to check is in the Cache.
  37160. * @return {boolean} True if the key exists, otherwise false.
  37161. */
  37162. checkBitmapFontKey: function (key) {
  37163. return this.checkKey(Phaser.Cache.BITMAPFONT, key);
  37164. },
  37165. /**
  37166. * Checks if the given key exists in the JSON Cache.
  37167. *
  37168. * @method Phaser.Cache#checkJSONKey
  37169. * @param {string} key - Asset key of the image to check is in the Cache.
  37170. * @return {boolean} True if the key exists, otherwise false.
  37171. */
  37172. checkJSONKey: function (key) {
  37173. return this.checkKey(Phaser.Cache.JSON, key);
  37174. },
  37175. /**
  37176. * Get image data by key.
  37177. *
  37178. * @method Phaser.Cache#getImage
  37179. * @param {string} key - Asset key of the image to retrieve from the Cache.
  37180. * @return {object} The image data.
  37181. */
  37182. getImage: function (key) {
  37183. if (this._images[key])
  37184. {
  37185. return this._images[key].data;
  37186. }
  37187. else
  37188. {
  37189. console.warn('Phaser.Cache.getImage: Invalid key: "' + key + '"');
  37190. }
  37191. },
  37192. /**
  37193. * Get tilemap data by key.
  37194. *
  37195. * @method Phaser.Cache#getTilemapData
  37196. * @param {string} key - Asset key of the tilemap data to retrieve from the Cache.
  37197. * @return {Object} The raw tilemap data in CSV or JSON format.
  37198. */
  37199. getTilemapData: function (key) {
  37200. if (this._tilemaps[key])
  37201. {
  37202. return this._tilemaps[key];
  37203. }
  37204. else
  37205. {
  37206. console.warn('Phaser.Cache.getTilemapData: Invalid key: "' + key + '"');
  37207. }
  37208. },
  37209. /**
  37210. * Get frame data by key.
  37211. *
  37212. * @method Phaser.Cache#getFrameData
  37213. * @param {string} key - Asset key of the frame data to retrieve from the Cache.
  37214. * @return {Phaser.FrameData} The frame data.
  37215. */
  37216. getFrameData: function (key) {
  37217. if (this._images[key] && this._images[key].frameData)
  37218. {
  37219. return this._images[key].frameData;
  37220. }
  37221. return null;
  37222. },
  37223. /**
  37224. * Replaces a set of frameData with a new Phaser.FrameData object.
  37225. *
  37226. * @method Phaser.Cache#updateFrameData
  37227. * @param {string} key - The unique key by which you will reference this object.
  37228. * @param {number} frameData - The new FrameData.
  37229. */
  37230. updateFrameData: function (key, frameData) {
  37231. if (this._images[key])
  37232. {
  37233. this._images[key].spriteSheet = true;
  37234. this._images[key].frameData = frameData;
  37235. }
  37236. },
  37237. /**
  37238. * Get a single frame out of a frameData set by key.
  37239. *
  37240. * @method Phaser.Cache#getFrameByIndex
  37241. * @param {string} key - Asset key of the frame data to retrieve from the Cache.
  37242. * @return {Phaser.Frame} The frame object.
  37243. */
  37244. getFrameByIndex: function (key, frame) {
  37245. if (this._images[key] && this._images[key].frameData)
  37246. {
  37247. return this._images[key].frameData.getFrame(frame);
  37248. }
  37249. return null;
  37250. },
  37251. /**
  37252. * Get a single frame out of a frameData set by key.
  37253. *
  37254. * @method Phaser.Cache#getFrameByName
  37255. * @param {string} key - Asset key of the frame data to retrieve from the Cache.
  37256. * @return {Phaser.Frame} The frame object.
  37257. */
  37258. getFrameByName: function (key, frame) {
  37259. if (this._images[key] && this._images[key].frameData)
  37260. {
  37261. return this._images[key].frameData.getFrameByName(frame);
  37262. }
  37263. return null;
  37264. },
  37265. /**
  37266. * Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image.
  37267. *
  37268. * @method Phaser.Cache#getFrame
  37269. * @param {string} key - Asset key of the frame data to retrieve from the Cache.
  37270. * @return {Phaser.Frame} The frame data.
  37271. */
  37272. getFrame: function (key) {
  37273. if (this._images[key] && this._images[key].spriteSheet === false)
  37274. {
  37275. return this._images[key].frame;
  37276. }
  37277. return null;
  37278. },
  37279. /**
  37280. * Get a single texture frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image.
  37281. *
  37282. * @method Phaser.Cache#getTextureFrame
  37283. * @param {string} key - Asset key of the frame to retrieve from the Cache.
  37284. * @return {Phaser.Frame} The frame data.
  37285. */
  37286. getTextureFrame: function (key) {
  37287. if (this._textures[key])
  37288. {
  37289. return this._textures[key].frame;
  37290. }
  37291. return null;
  37292. },
  37293. /**
  37294. * Get a RenderTexture by key.
  37295. *
  37296. * @method Phaser.Cache#getTexture
  37297. * @param {string} key - Asset key of the RenderTexture to retrieve from the Cache.
  37298. * @return {Phaser.RenderTexture} The RenderTexture object.
  37299. */
  37300. getTexture: function (key) {
  37301. if (this._textures[key])
  37302. {
  37303. return this._textures[key];
  37304. }
  37305. else
  37306. {
  37307. console.warn('Phaser.Cache.getTexture: Invalid key: "' + key + '"');
  37308. }
  37309. },
  37310. /**
  37311. * Get sound by key.
  37312. *
  37313. * @method Phaser.Cache#getSound
  37314. * @param {string} key - Asset key of the sound to retrieve from the Cache.
  37315. * @return {Phaser.Sound} The sound object.
  37316. */
  37317. getSound: function (key) {
  37318. if (this._sounds[key])
  37319. {
  37320. return this._sounds[key];
  37321. }
  37322. else
  37323. {
  37324. console.warn('Phaser.Cache.getSound: Invalid key: "' + key + '"');
  37325. }
  37326. },
  37327. /**
  37328. * Get sound data by key.
  37329. *
  37330. * @method Phaser.Cache#getSoundData
  37331. * @param {string} key - Asset key of the sound to retrieve from the Cache.
  37332. * @return {object} The sound data.
  37333. */
  37334. getSoundData: function (key) {
  37335. if (this._sounds[key])
  37336. {
  37337. return this._sounds[key].data;
  37338. }
  37339. else
  37340. {
  37341. console.warn('Phaser.Cache.getSoundData: Invalid key: "' + key + '"');
  37342. }
  37343. },
  37344. /**
  37345. * Check if the given sound has finished decoding.
  37346. *
  37347. * @method Phaser.Cache#isSoundDecoded
  37348. * @param {string} key - Asset key of the sound in the Cache.
  37349. * @return {boolean} The decoded state of the Sound object.
  37350. */
  37351. isSoundDecoded: function (key) {
  37352. if (this._sounds[key])
  37353. {
  37354. return this._sounds[key].decoded;
  37355. }
  37356. },
  37357. /**
  37358. * Check if the given sound is ready for playback. A sound is considered ready when it has finished decoding and the device is no longer touch locked.
  37359. *
  37360. * @method Phaser.Cache#isSoundReady
  37361. * @param {string} key - Asset key of the sound in the Cache.
  37362. * @return {boolean} True if the sound is decoded and the device is not touch locked.
  37363. */
  37364. isSoundReady: function (key) {
  37365. return (this._sounds[key] && this._sounds[key].decoded && this.game.sound.touchLocked === false);
  37366. },
  37367. /**
  37368. * Check whether an image asset is sprite sheet or not.
  37369. *
  37370. * @method Phaser.Cache#isSpriteSheet
  37371. * @param {string} key - Asset key of the sprite sheet you want.
  37372. * @return {boolean} True if the image is a sprite sheet.
  37373. */
  37374. isSpriteSheet: function (key) {
  37375. if (this._images[key])
  37376. {
  37377. return this._images[key].spriteSheet;
  37378. }
  37379. return false;
  37380. },
  37381. /**
  37382. * Get text data by key.
  37383. *
  37384. * @method Phaser.Cache#getText
  37385. * @param {string} key - Asset key of the text data to retrieve from the Cache.
  37386. * @return {object} The text data.
  37387. */
  37388. getText: function (key) {
  37389. if (this._text[key])
  37390. {
  37391. return this._text[key].data;
  37392. }
  37393. else
  37394. {
  37395. console.warn('Phaser.Cache.getText: Invalid key: "' + key + '"');
  37396. }
  37397. },
  37398. /**
  37399. * Get a JSON object by key from the cache.
  37400. *
  37401. * @method Phaser.Cache#getJSON
  37402. * @param {string} key - Asset key of the json object to retrieve from the Cache.
  37403. * @return {object} The JSON object.
  37404. */
  37405. getJSON: function (key) {
  37406. if (this._json[key])
  37407. {
  37408. return this._json[key].data;
  37409. }
  37410. else
  37411. {
  37412. console.warn('Phaser.Cache.getJSON: Invalid key: "' + key + '"');
  37413. }
  37414. },
  37415. /**
  37416. * Get binary data by key.
  37417. *
  37418. * @method Phaser.Cache#getBinary
  37419. * @param {string} key - Asset key of the binary data object to retrieve from the Cache.
  37420. * @return {object} The binary data object.
  37421. */
  37422. getBinary: function (key) {
  37423. if (this._binary[key])
  37424. {
  37425. return this._binary[key];
  37426. }
  37427. else
  37428. {
  37429. console.warn('Phaser.Cache.getBinary: Invalid key: "' + key + '"');
  37430. }
  37431. },
  37432. /**
  37433. * Gets all keys used by the Cache for the given data type.
  37434. *
  37435. * @method Phaser.Cache#getKeys
  37436. * @param {number} [type=Phaser.Cache.IMAGE] - The type of Cache keys you wish to get. Can be Cache.CANVAS, Cache.IMAGE, Cache.SOUND, etc.
  37437. * @return {Array} The array of item keys.
  37438. */
  37439. getKeys: function (type) {
  37440. var array = null;
  37441. switch (type)
  37442. {
  37443. case Phaser.Cache.CANVAS:
  37444. array = this._canvases;
  37445. break;
  37446. case Phaser.Cache.IMAGE:
  37447. array = this._images;
  37448. break;
  37449. case Phaser.Cache.TEXTURE:
  37450. array = this._textures;
  37451. break;
  37452. case Phaser.Cache.SOUND:
  37453. array = this._sounds;
  37454. break;
  37455. case Phaser.Cache.TEXT:
  37456. array = this._text;
  37457. break;
  37458. case Phaser.Cache.PHYSICS:
  37459. array = this._physics;
  37460. break;
  37461. case Phaser.Cache.TILEMAP:
  37462. array = this._tilemaps;
  37463. break;
  37464. case Phaser.Cache.BINARY:
  37465. array = this._binary;
  37466. break;
  37467. case Phaser.Cache.BITMAPDATA:
  37468. array = this._bitmapDatas;
  37469. break;
  37470. case Phaser.Cache.BITMAPFONT:
  37471. array = this._bitmapFont;
  37472. break;
  37473. case Phaser.Cache.JSON:
  37474. array = this._json;
  37475. break;
  37476. }
  37477. if (!array)
  37478. {
  37479. return;
  37480. }
  37481. var output = [];
  37482. for (var item in array)
  37483. {
  37484. if (item !== '__default' && item !== '__missing')
  37485. {
  37486. output.push(item);
  37487. }
  37488. }
  37489. return output;
  37490. },
  37491. /**
  37492. * Removes a canvas from the cache.
  37493. *
  37494. * @method Phaser.Cache#removeCanvas
  37495. * @param {string} key - Key of the asset you want to remove.
  37496. */
  37497. removeCanvas: function (key) {
  37498. delete this._canvases[key];
  37499. },
  37500. /**
  37501. * Removes an image from the cache.
  37502. *
  37503. * @method Phaser.Cache#removeImage
  37504. * @param {string} key - Key of the asset you want to remove.
  37505. */
  37506. removeImage: function (key) {
  37507. delete this._images[key];
  37508. },
  37509. /**
  37510. * Removes a sound from the cache.
  37511. *
  37512. * @method Phaser.Cache#removeSound
  37513. * @param {string} key - Key of the asset you want to remove.
  37514. */
  37515. removeSound: function (key) {
  37516. delete this._sounds[key];
  37517. },
  37518. /**
  37519. * Removes a text from the cache.
  37520. *
  37521. * @method Phaser.Cache#removeText
  37522. * @param {string} key - Key of the asset you want to remove.
  37523. */
  37524. removeText: function (key) {
  37525. delete this._text[key];
  37526. },
  37527. /**
  37528. * Removes a json object from the cache.
  37529. *
  37530. * @method Phaser.Cache#removeJSON
  37531. * @param {string} key - Key of the asset you want to remove.
  37532. */
  37533. removeJSON: function (key) {
  37534. delete this._json[key];
  37535. },
  37536. /**
  37537. * Removes a physics data file from the cache.
  37538. *
  37539. * @method Phaser.Cache#removePhysics
  37540. * @param {string} key - Key of the asset you want to remove.
  37541. */
  37542. removePhysics: function (key) {
  37543. delete this._physics[key];
  37544. },
  37545. /**
  37546. * Removes a tilemap from the cache.
  37547. *
  37548. * @method Phaser.Cache#removeTilemap
  37549. * @param {string} key - Key of the asset you want to remove.
  37550. */
  37551. removeTilemap: function (key) {
  37552. delete this._tilemaps[key];
  37553. },
  37554. /**
  37555. * Removes a binary file from the cache.
  37556. *
  37557. * @method Phaser.Cache#removeBinary
  37558. * @param {string} key - Key of the asset you want to remove.
  37559. */
  37560. removeBinary: function (key) {
  37561. delete this._binary[key];
  37562. },
  37563. /**
  37564. * Removes a bitmap data from the cache.
  37565. *
  37566. * @method Phaser.Cache#removeBitmapData
  37567. * @param {string} key - Key of the asset you want to remove.
  37568. */
  37569. removeBitmapData: function (key) {
  37570. delete this._bitmapDatas[key];
  37571. },
  37572. /**
  37573. * Removes a bitmap font from the cache.
  37574. *
  37575. * @method Phaser.Cache#removeBitmapFont
  37576. * @param {string} key - Key of the asset you want to remove.
  37577. */
  37578. removeBitmapFont: function (key) {
  37579. delete this._bitmapFont[key];
  37580. },
  37581. /**
  37582. * Clears the cache. Removes every local cache object reference.
  37583. *
  37584. * @method Phaser.Cache#destroy
  37585. */
  37586. destroy: function () {
  37587. for (var item in this._canvases)
  37588. {
  37589. delete this._canvases[item];
  37590. }
  37591. for (var item in this._images)
  37592. {
  37593. if (item !== '__default' && item !== '__missing')
  37594. {
  37595. delete this._images[item];
  37596. }
  37597. }
  37598. for (var item in this._sounds)
  37599. {
  37600. delete this._sounds[item];
  37601. }
  37602. for (var item in this._text)
  37603. {
  37604. delete this._text[item];
  37605. }
  37606. for (var item in this._json)
  37607. {
  37608. delete this._json[item];
  37609. }
  37610. for (var item in this._textures)
  37611. {
  37612. delete this._textures[item];
  37613. }
  37614. for (var item in this._physics)
  37615. {
  37616. delete this._physics[item];
  37617. }
  37618. for (var item in this._tilemaps)
  37619. {
  37620. delete this._tilemaps[item];
  37621. }
  37622. for (var item in this._binary)
  37623. {
  37624. delete this._binary[item];
  37625. }
  37626. for (var item in this._bitmapDatas)
  37627. {
  37628. delete this._bitmapDatas[item];
  37629. }
  37630. for (var item in this._bitmapFont)
  37631. {
  37632. delete this._bitmapFont[item];
  37633. }
  37634. }
  37635. };
  37636. Phaser.Cache.prototype.constructor = Phaser.Cache;
  37637. /* jshint wsh:true */
  37638. /**
  37639. * @author Richard Davey <rich@photonstorm.com>
  37640. * @copyright 2014 Photon Storm Ltd.
  37641. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  37642. */
  37643. /**
  37644. * Phaser loader constructor.
  37645. * The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files.
  37646. * It uses a combination of Image() loading and xhr and provides progress and completion callbacks.
  37647. * @class Phaser.Loader
  37648. * @classdesc The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files.
  37649. * It uses a combination of Image() loading and xhr and provides progress and completion callbacks.
  37650. * @constructor
  37651. * @param {Phaser.Game} game - A reference to the currently running game.
  37652. */
  37653. Phaser.Loader = function (game) {
  37654. /**
  37655. * @property {Phaser.Game} game - Local reference to game.
  37656. */
  37657. this.game = game;
  37658. /**
  37659. * @property {boolean} isLoading - True if the Loader is in the process of loading the queue.
  37660. * @default
  37661. */
  37662. this.isLoading = false;
  37663. /**
  37664. * @property {boolean} hasLoaded - True if all assets in the queue have finished loading.
  37665. * @default
  37666. */
  37667. this.hasLoaded = false;
  37668. /**
  37669. * @property {number} progress - The rounded load progress percentage value (from 0 to 100)
  37670. * @default
  37671. */
  37672. this.progress = 0;
  37673. /**
  37674. * @property {number} progressFloat - The non-rounded load progress value (from 0.0 to 100.0)
  37675. * @default
  37676. */
  37677. this.progressFloat = 0;
  37678. /**
  37679. * You can optionally link a sprite to the preloader.
  37680. * If you do so the Sprites width or height will be cropped based on the percentage loaded.
  37681. * @property {Phaser.Sprite|Phaser.Image} preloadSprite
  37682. * @default
  37683. */
  37684. this.preloadSprite = null;
  37685. /**
  37686. * @property {boolean|string} crossOrigin - The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'.
  37687. * @default
  37688. */
  37689. this.crossOrigin = false;
  37690. /**
  37691. * If you want to append a URL before the path of any asset you can set this here.
  37692. * Useful if you need to allow an asset url to be configured outside of the game code.
  37693. * MUST have / on the end of it!
  37694. * @property {string} baseURL
  37695. * @default
  37696. */
  37697. this.baseURL = '';
  37698. /**
  37699. * @property {Phaser.Signal} onLoadStart - This event is dispatched when the loading process starts, before the first file has been requested.
  37700. */
  37701. this.onLoadStart = new Phaser.Signal();
  37702. /**
  37703. * @property {Phaser.Signal} onFileStart - This event is dispatched immediately before a file starts loading. It's possible the file may still error (404, etc) after this event is sent.
  37704. */
  37705. this.onFileStart = new Phaser.Signal();
  37706. /**
  37707. * @property {Phaser.Signal} onFileComplete - This event is dispatched when a file completes loading successfully.
  37708. */
  37709. this.onFileComplete = new Phaser.Signal();
  37710. /**
  37711. * @property {Phaser.Signal} onFileError - This event is dispatched when a file errors as a result of the load request.
  37712. */
  37713. this.onFileError = new Phaser.Signal();
  37714. /**
  37715. * @property {Phaser.Signal} onLoadComplete - This event is dispatched when the final file in the load queue has either loaded or failed.
  37716. */
  37717. this.onLoadComplete = new Phaser.Signal();
  37718. /**
  37719. * @property {Phaser.Signal} onPackComplete - This event is dispatched when an asset pack has either loaded or failed.
  37720. */
  37721. this.onPackComplete = new Phaser.Signal();
  37722. /**
  37723. * @property {array} _packList - Contains all the assets packs.
  37724. * @private
  37725. */
  37726. this._packList = [];
  37727. /**
  37728. * @property {number} _packIndex - The index of the current asset pack.
  37729. * @private
  37730. */
  37731. this._packIndex = 0;
  37732. /**
  37733. * @property {array} _fileList - Contains all the assets file infos.
  37734. * @private
  37735. */
  37736. this._fileList = [];
  37737. /**
  37738. * @property {number} _fileIndex - The index of the current file being loaded.
  37739. * @private
  37740. */
  37741. this._fileIndex = 0;
  37742. /**
  37743. * @property {number} _progressChunk - Indicates the size of 1 file in terms of a percentage out of 100.
  37744. * @private
  37745. * @default
  37746. */
  37747. this._progressChunk = 0;
  37748. /**
  37749. * @property {XMLHttpRequest} - An XMLHttpRequest object used for loading text and audio data.
  37750. * @private
  37751. */
  37752. this._xhr = new XMLHttpRequest();
  37753. /**
  37754. * @property {XDomainRequest} - An ajax request used specifically by IE9 for CORs loading issues.
  37755. * @private
  37756. */
  37757. this._ajax = null;
  37758. };
  37759. /**
  37760. * @constant
  37761. * @type {number}
  37762. */
  37763. Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY = 0;
  37764. /**
  37765. * @constant
  37766. * @type {number}
  37767. */
  37768. Phaser.Loader.TEXTURE_ATLAS_JSON_HASH = 1;
  37769. /**
  37770. * @constant
  37771. * @type {number}
  37772. */
  37773. Phaser.Loader.TEXTURE_ATLAS_XML_STARLING = 2;
  37774. /**
  37775. * @constant
  37776. * @type {number}
  37777. */
  37778. Phaser.Loader.PHYSICS_LIME_CORONA_JSON = 3;
  37779. /**
  37780. * @constant
  37781. * @type {number}
  37782. */
  37783. Phaser.Loader.PHYSICS_PHASER_JSON = 4;
  37784. Phaser.Loader.prototype = {
  37785. /**
  37786. * You can set a Sprite to be a "preload" sprite by passing it to this method.
  37787. * A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time.
  37788. * This allows you to easily make loading bars for games. Note that Sprite.visible = true will be set when calling this.
  37789. * Note: The Sprite should use a single image and not use a texture that is part of a Texture Atlas or Sprite Sheet.
  37790. *
  37791. * @method Phaser.Loader#setPreloadSprite
  37792. * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite or image that will be cropped during the load.
  37793. * @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.
  37794. */
  37795. setPreloadSprite: function (sprite, direction) {
  37796. direction = direction || 0;
  37797. this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, rect: null };
  37798. if (direction === 0)
  37799. {
  37800. // Horizontal rect
  37801. this.preloadSprite.rect = new Phaser.Rectangle(0, 0, 1, sprite.height);
  37802. }
  37803. else
  37804. {
  37805. // Vertical rect
  37806. this.preloadSprite.rect = new Phaser.Rectangle(0, 0, sprite.width, 1);
  37807. }
  37808. sprite.crop(this.preloadSprite.rect);
  37809. sprite.visible = true;
  37810. },
  37811. /**
  37812. * Check whether asset exists with a specific key.
  37813. * Use Phaser.Cache to access loaded assets, e.g. Phaser.Cache#checkImageKey
  37814. *
  37815. * @method Phaser.Loader#checkKeyExists
  37816. * @param {string} type - The type asset you want to check.
  37817. * @param {string} key - Key of the asset you want to check.
  37818. * @return {boolean} Return true if exists, otherwise return false.
  37819. */
  37820. checkKeyExists: function (type, key) {
  37821. if (this._fileList.length > 0)
  37822. {
  37823. for (var i = 0; i < this._fileList.length; i++)
  37824. {
  37825. if (this._fileList[i].type === type && this._fileList[i].key === key)
  37826. {
  37827. return true;
  37828. }
  37829. }
  37830. }
  37831. return false;
  37832. },
  37833. /**
  37834. * Gets the fileList index for the given key.
  37835. *
  37836. * @method Phaser.Loader#getAssetIndex
  37837. * @param {string} type - The type asset you want to check.
  37838. * @param {string} key - Key of the asset you want to check.
  37839. * @return {number} The index of this key in the filelist, or -1 if not found.
  37840. */
  37841. getAssetIndex: function (type, key) {
  37842. if (this._fileList.length > 0)
  37843. {
  37844. for (var i = 0; i < this._fileList.length; i++)
  37845. {
  37846. if (this._fileList[i].type === type && this._fileList[i].key === key)
  37847. {
  37848. return i;
  37849. }
  37850. }
  37851. }
  37852. return -1;
  37853. },
  37854. /**
  37855. * Gets the asset that is queued for load.
  37856. *
  37857. * @method Phaser.Loader#getAsset
  37858. * @param {string} type - The type asset you want to check.
  37859. * @param {string} key - Key of the asset you want to check.
  37860. * @return {any} Returns an object if found that has 2 properties: index and file. Otherwise false.
  37861. */
  37862. getAsset: function (type, key) {
  37863. if (this._fileList.length > 0)
  37864. {
  37865. for (var i = 0; i < this._fileList.length; i++)
  37866. {
  37867. if (this._fileList[i].type === type && this._fileList[i].key === key)
  37868. {
  37869. return { index: i, file: this._fileList[i] };
  37870. }
  37871. }
  37872. }
  37873. return false;
  37874. },
  37875. /**
  37876. * Reset loader, this will remove the load queue.
  37877. *
  37878. * @method Phaser.Loader#reset
  37879. */
  37880. reset: function () {
  37881. this.preloadSprite = null;
  37882. this.isLoading = false;
  37883. this._packList.length = 0;
  37884. this._packIndex = 0;
  37885. this._fileList.length = 0;
  37886. this._fileIndex = 0;
  37887. },
  37888. /**
  37889. * Internal function that adds a new entry to the file list. Do not call directly.
  37890. *
  37891. * @method Phaser.Loader#addToFileList
  37892. * @protected
  37893. * @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
  37894. * @param {string} key - The unique Cache ID key of this resource.
  37895. * @param {string} url - The URL the asset will be loaded from.
  37896. * @param {object} properties - Any additional properties needed to load the file.
  37897. */
  37898. addToFileList: function (type, key, url, properties) {
  37899. var entry = {
  37900. type: type,
  37901. key: key,
  37902. url: url,
  37903. data: null,
  37904. error: false,
  37905. loaded: false
  37906. };
  37907. if (typeof properties !== "undefined")
  37908. {
  37909. for (var prop in properties)
  37910. {
  37911. entry[prop] = properties[prop];
  37912. }
  37913. }
  37914. if (this.checkKeyExists(type, key) === false)
  37915. {
  37916. this._fileList.push(entry);
  37917. }
  37918. },
  37919. /**
  37920. * Internal function that replaces an existing entry in the file list with a new one. Do not call directly.
  37921. *
  37922. * @method Phaser.Loader#replaceInFileList
  37923. * @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
  37924. * @param {string} key - The unique Cache ID key of this resource.
  37925. * @param {string} url - The URL the asset will be loaded from.
  37926. * @param {object} properties - Any additional properties needed to load the file.
  37927. * @protected
  37928. */
  37929. replaceInFileList: function (type, key, url, properties) {
  37930. var entry = {
  37931. type: type,
  37932. key: key,
  37933. url: url,
  37934. data: null,
  37935. error: false,
  37936. loaded: false
  37937. };
  37938. if (typeof properties !== "undefined")
  37939. {
  37940. for (var prop in properties)
  37941. {
  37942. entry[prop] = properties[prop];
  37943. }
  37944. }
  37945. var index = this.getAssetIndex(type, key);
  37946. if (index === -1)
  37947. {
  37948. this._fileList.push(entry);
  37949. }
  37950. else
  37951. {
  37952. this._fileList[index] = entry;
  37953. }
  37954. },
  37955. /**
  37956. * Add an image to the Loader.
  37957. *
  37958. * @method Phaser.Loader#pack
  37959. * @param {string} key - Unique asset key of this image file.
  37960. * @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.
  37961. * @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
  37962. * @param {object} [callbackContext] - Some Loader operations, like Binary and Script require a context for their callbacks. Pass the context here.
  37963. * @return {Phaser.Loader} This Loader instance.
  37964. */
  37965. pack: function (key, url, data, callbackContext) {
  37966. if (typeof url === "undefined") { url = null; }
  37967. if (typeof data === "undefined") { data = null; }
  37968. if (typeof callbackContext === "undefined") { callbackContext = this; }
  37969. if (url === null && data === null)
  37970. {
  37971. console.warn('Phaser.Loader.pack - Both url and data are null. One must be set.');
  37972. return this;
  37973. }
  37974. // A data object has been given
  37975. if (data)
  37976. {
  37977. if (typeof data === 'string')
  37978. {
  37979. data = JSON.parse(data);
  37980. }
  37981. }
  37982. this._packList.push( { key: key, url: url, data: data, loaded: false, error: false, callbackContext: callbackContext } );
  37983. return this;
  37984. },
  37985. /**
  37986. * Add an image to the Loader.
  37987. *
  37988. * @method Phaser.Loader#image
  37989. * @param {string} key - Unique asset key of this image file.
  37990. * @param {string} url - URL of image file.
  37991. * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
  37992. * @return {Phaser.Loader} This Loader instance.
  37993. */
  37994. image: function (key, url, overwrite) {
  37995. if (typeof overwrite === "undefined") { overwrite = false; }
  37996. if (overwrite)
  37997. {
  37998. this.replaceInFileList('image', key, url);
  37999. }
  38000. else
  38001. {
  38002. this.addToFileList('image', key, url);
  38003. }
  38004. return this;
  38005. },
  38006. /**
  38007. * Add a text file to the Loader.
  38008. *
  38009. * @method Phaser.Loader#text
  38010. * @param {string} key - Unique asset key of the text file.
  38011. * @param {string} url - URL of the text file.
  38012. * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
  38013. * @return {Phaser.Loader} This Loader instance.
  38014. */
  38015. text: function (key, url, overwrite) {
  38016. if (typeof overwrite === "undefined") { overwrite = false; }
  38017. if (overwrite)
  38018. {
  38019. this.replaceInFileList('text', key, url);
  38020. }
  38021. else
  38022. {
  38023. this.addToFileList('text', key, url);
  38024. }
  38025. return this;
  38026. },
  38027. /**
  38028. * Add a json file to the Loader.
  38029. *
  38030. * @method Phaser.Loader#json
  38031. * @param {string} key - Unique asset key of the json file.
  38032. * @param {string} url - URL of the json file.
  38033. * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
  38034. * @return {Phaser.Loader} This Loader instance.
  38035. */
  38036. json: function (key, url, overwrite) {
  38037. if (typeof overwrite === "undefined") { overwrite = false; }
  38038. if (overwrite)
  38039. {
  38040. this.replaceInFileList('json', key, url);
  38041. }
  38042. else
  38043. {
  38044. this.addToFileList('json', key, url);
  38045. }
  38046. return this;
  38047. },
  38048. /**
  38049. * Add a JavaScript file to the Loader. Once loaded the JavaScript file will be automatically turned into a script tag (and executed), so be careful what you load!
  38050. * You can also specify a callback. This will be executed as soon as the script tag has been created.
  38051. *
  38052. * @method Phaser.Loader#script
  38053. * @param {string} key - Unique asset key of the script file.
  38054. * @param {string} url - URL of the JavaScript file.
  38055. * @param {function} [callback] - Optional callback that will be called after the script tag has loaded, so you can perform additional processing.
  38056. * @param {function} [callbackContext] - The context under which the callback will be applied. If not specified it will use the callback itself as the context.
  38057. * @return {Phaser.Loader} This Loader instance.
  38058. */
  38059. script: function (key, url, callback, callbackContext) {
  38060. if (typeof callback === 'undefined') { callback = false; }
  38061. if (callback !== false && typeof callbackContext === 'undefined') { callbackContext = callback; }
  38062. this.addToFileList('script', key, url, { callback: callback, callbackContext: callbackContext });
  38063. return this;
  38064. },
  38065. /**
  38066. * Add a binary file to the Loader. It will be loaded via xhr with a responseType of "arraybuffer". You can specify an optional callback to process the file after load.
  38067. * When the callback is called it will be passed 2 parameters: the key of the file and the file data.
  38068. * WARNING: If you specify a callback, the file data will be set to whatever your callback returns. So always return the data object, even if you didn't modify it.
  38069. *
  38070. * @method Phaser.Loader#binary
  38071. * @param {string} key - Unique asset key of the binary file.
  38072. * @param {string} url - URL of the binary file.
  38073. * @param {function} [callback] - Optional callback that will be passed the file after loading, so you can perform additional processing on it.
  38074. * @param {function} [callbackContext] - The context under which the callback will be applied. If not specified it will use the callback itself as the context.
  38075. * @return {Phaser.Loader} This Loader instance.
  38076. */
  38077. binary: function (key, url, callback, callbackContext) {
  38078. if (typeof callback === 'undefined') { callback = false; }
  38079. if (callback !== false && typeof callbackContext === 'undefined') { callbackContext = callback; }
  38080. this.addToFileList('binary', key, url, { callback: callback, callbackContext: callbackContext });
  38081. return this;
  38082. },
  38083. /**
  38084. * Add a new sprite sheet to the loader.
  38085. *
  38086. * @method Phaser.Loader#spritesheet
  38087. * @param {string} key - Unique asset key of the sheet file.
  38088. * @param {string} url - URL of the sheet file.
  38089. * @param {number} frameWidth - Width of each single frame.
  38090. * @param {number} frameHeight - Height of each single frame.
  38091. * @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames.
  38092. * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here.
  38093. * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here.
  38094. * @return {Phaser.Loader} This Loader instance.
  38095. */
  38096. spritesheet: function (key, url, frameWidth, frameHeight, frameMax, margin, spacing) {
  38097. if (typeof frameMax === "undefined") { frameMax = -1; }
  38098. if (typeof margin === "undefined") { margin = 0; }
  38099. if (typeof spacing === "undefined") { spacing = 0; }
  38100. this.addToFileList('spritesheet', key, url, { frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax, margin: margin, spacing: spacing });
  38101. return this;
  38102. },
  38103. /**
  38104. * Add a new audio file to the loader.
  38105. *
  38106. * @method Phaser.Loader#audio
  38107. * @param {string} key - Unique asset key of the audio file.
  38108. * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'jump.mp3', 'jump.ogg', 'jump.m4a' ] or a single string containing just one URL.
  38109. * @param {boolean} autoDecode - When using Web Audio the audio files can either be decoded at load time or run-time. They can't be played until they are decoded, but this let's you control when that happens. Decoding is a non-blocking async process.
  38110. * @return {Phaser.Loader} This Loader instance.
  38111. */
  38112. audio: function (key, urls, autoDecode) {
  38113. if (typeof autoDecode === "undefined") { autoDecode = true; }
  38114. this.addToFileList('audio', key, urls, { buffer: null, autoDecode: autoDecode });
  38115. return this;
  38116. },
  38117. /**
  38118. * Add a new tilemap loading request.
  38119. *
  38120. * @method Phaser.Loader#tilemap
  38121. * @param {string} key - Unique asset key of the tilemap data.
  38122. * @param {string} [url] - The url of the map data file (csv/json)
  38123. * @param {object} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for map data instead.
  38124. * @param {number} [format=Phaser.Tilemap.CSV] - The format of the map data. Either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON.
  38125. * @return {Phaser.Loader} This Loader instance.
  38126. */
  38127. tilemap: function (key, url, data, format) {
  38128. if (typeof url === "undefined") { url = null; }
  38129. if (typeof data === "undefined") { data = null; }
  38130. if (typeof format === "undefined") { format = Phaser.Tilemap.CSV; }
  38131. if (url == null && data == null)
  38132. {
  38133. console.warn('Phaser.Loader.tilemap - Both url and data are null. One must be set.');
  38134. return this;
  38135. }
  38136. // A map data object has been given
  38137. if (data)
  38138. {
  38139. switch (format)
  38140. {
  38141. // A csv string or object has been given
  38142. case Phaser.Tilemap.CSV:
  38143. break;
  38144. // An xml string or object has been given
  38145. case Phaser.Tilemap.TILED_JSON:
  38146. if (typeof data === 'string')
  38147. {
  38148. data = JSON.parse(data);
  38149. }
  38150. break;
  38151. }
  38152. this.game.cache.addTilemap(key, null, data, format);
  38153. }
  38154. else
  38155. {
  38156. this.addToFileList('tilemap', key, url, { format: format });
  38157. }
  38158. return this;
  38159. },
  38160. /**
  38161. * Add a new physics data object loading request.
  38162. * The data must be in Lime + Corona JSON format. Physics Editor by code'n'web exports in this format natively.
  38163. *
  38164. * @method Phaser.Loader#physics
  38165. * @param {string} key - Unique asset key of the physics json data.
  38166. * @param {string} [url] - The url of the map data file (csv/json)
  38167. * @param {object} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for physics data instead.
  38168. * @param {string} [format=Phaser.Physics.LIME_CORONA_JSON] - The format of the physics data.
  38169. * @return {Phaser.Loader} This Loader instance.
  38170. */
  38171. physics: function (key, url, data, format) {
  38172. if (typeof url === "undefined") { url = null; }
  38173. if (typeof data === "undefined") { data = null; }
  38174. if (typeof format === "undefined") { format = Phaser.Physics.LIME_CORONA_JSON; }
  38175. if (url == null && data == null)
  38176. {
  38177. console.warn('Phaser.Loader.physics - Both url and data are null. One must be set.');
  38178. return this;
  38179. }
  38180. // A map data object has been given
  38181. if (data)
  38182. {
  38183. if (typeof data === 'string')
  38184. {
  38185. data = JSON.parse(data);
  38186. }
  38187. this.game.cache.addPhysicsData(key, null, data, format);
  38188. }
  38189. else
  38190. {
  38191. this.addToFileList('physics', key, url, { format: format });
  38192. }
  38193. return this;
  38194. },
  38195. /**
  38196. * Add a new bitmap font loading request.
  38197. *
  38198. * @method Phaser.Loader#bitmapFont
  38199. * @param {string} key - Unique asset key of the bitmap font.
  38200. * @param {string} textureURL - The url of the font image file.
  38201. * @param {string} [xmlURL] - The url of the font data file (xml/fnt)
  38202. * @param {object} [xmlData] - An optional XML data object.
  38203. * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here.
  38204. * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here.
  38205. * @return {Phaser.Loader} This Loader instance.
  38206. */
  38207. bitmapFont: function (key, textureURL, xmlURL, xmlData, xSpacing, ySpacing) {
  38208. if (typeof xmlURL === "undefined") { xmlURL = null; }
  38209. if (typeof xmlData === "undefined") { xmlData = null; }
  38210. if (typeof xSpacing === "undefined") { xSpacing = 0; }
  38211. if (typeof ySpacing === "undefined") { ySpacing = 0; }
  38212. // A URL to a json/xml file has been given
  38213. if (xmlURL)
  38214. {
  38215. this.addToFileList('bitmapfont', key, textureURL, { xmlURL: xmlURL, xSpacing: xSpacing, ySpacing: ySpacing });
  38216. }
  38217. else
  38218. {
  38219. // An xml string or object has been given
  38220. if (typeof xmlData === 'string')
  38221. {
  38222. var xml;
  38223. try {
  38224. if (window['DOMParser'])
  38225. {
  38226. var domparser = new DOMParser();
  38227. xml = domparser.parseFromString(xmlData, "text/xml");
  38228. }
  38229. else
  38230. {
  38231. xml = new ActiveXObject("Microsoft.XMLDOM");
  38232. xml.async = 'false';
  38233. xml.loadXML(xmlData);
  38234. }
  38235. }
  38236. catch (e)
  38237. {
  38238. xml = undefined;
  38239. }
  38240. if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length)
  38241. {
  38242. throw new Error("Phaser.Loader. Invalid Bitmap Font XML given");
  38243. }
  38244. else
  38245. {
  38246. this.addToFileList('bitmapfont', key, textureURL, { xmlURL: null, xmlData: xml, xSpacing: xSpacing, ySpacing: ySpacing });
  38247. }
  38248. }
  38249. }
  38250. return this;
  38251. },
  38252. /**
  38253. * Add a new texture atlas to the loader. This atlas uses the JSON Array data format.
  38254. *
  38255. * @method Phaser.Loader#atlasJSONArray
  38256. * @param {string} key - Unique asset key of the texture atlas file.
  38257. * @param {string} textureURL - The url of the texture atlas image file.
  38258. * @param {string} [atlasURL] - The url of the texture atlas data file (json/xml). You don't need this if you are passing an atlasData object instead.
  38259. * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL.
  38260. * @return {Phaser.Loader} This Loader instance.
  38261. */
  38262. atlasJSONArray: function (key, textureURL, atlasURL, atlasData) {
  38263. return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY);
  38264. },
  38265. /**
  38266. * Add a new texture atlas to the loader. This atlas uses the JSON Hash data format.
  38267. *
  38268. * @method Phaser.Loader#atlasJSONHash
  38269. * @param {string} key - Unique asset key of the texture atlas file.
  38270. * @param {string} textureURL - The url of the texture atlas image file.
  38271. * @param {string} [atlasURL] - The url of the texture atlas data file (json/xml). You don't need this if you are passing an atlasData object instead.
  38272. * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL.
  38273. * @return {Phaser.Loader} This Loader instance.
  38274. */
  38275. atlasJSONHash: function (key, textureURL, atlasURL, atlasData) {
  38276. return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH);
  38277. },
  38278. /**
  38279. * Add a new texture atlas to the loader. This atlas uses the Starling XML data format.
  38280. *
  38281. * @method Phaser.Loader#atlasXML
  38282. * @param {string} key - Unique asset key of the texture atlas file.
  38283. * @param {string} textureURL - The url of the texture atlas image file.
  38284. * @param {string} [atlasURL] - The url of the texture atlas data file (json/xml). You don't need this if you are passing an atlasData object instead.
  38285. * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL.
  38286. * @return {Phaser.Loader} This Loader instance.
  38287. */
  38288. atlasXML: function (key, textureURL, atlasURL, atlasData) {
  38289. return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING);
  38290. },
  38291. /**
  38292. * Add a new texture atlas to the loader.
  38293. *
  38294. * @method Phaser.Loader#atlas
  38295. * @param {string} key - Unique asset key of the texture atlas file.
  38296. * @param {string} textureURL - The url of the texture atlas image file.
  38297. * @param {string} [atlasURL] - The url of the texture atlas data file (json/xml). You don't need this if you are passing an atlasData object instead.
  38298. * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL.
  38299. * @param {number} [format] - A value describing the format of the data, the default is Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY.
  38300. * @return {Phaser.Loader} This Loader instance.
  38301. */
  38302. atlas: function (key, textureURL, atlasURL, atlasData, format) {
  38303. if (typeof atlasURL === "undefined") { atlasURL = null; }
  38304. if (typeof atlasData === "undefined") { atlasData = null; }
  38305. if (typeof format === "undefined") { format = Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY; }
  38306. // A URL to a json/xml file has been given
  38307. if (atlasURL)
  38308. {
  38309. this.addToFileList('textureatlas', key, textureURL, { atlasURL: atlasURL, format: format });
  38310. }
  38311. else
  38312. {
  38313. switch (format)
  38314. {
  38315. // A json string or object has been given
  38316. case Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY:
  38317. if (typeof atlasData === 'string')
  38318. {
  38319. atlasData = JSON.parse(atlasData);
  38320. }
  38321. break;
  38322. // An xml string or object has been given
  38323. case Phaser.Loader.TEXTURE_ATLAS_XML_STARLING:
  38324. if (typeof atlasData === 'string')
  38325. {
  38326. var xml;
  38327. try {
  38328. if (window['DOMParser'])
  38329. {
  38330. var domparser = new DOMParser();
  38331. xml = domparser.parseFromString(atlasData, "text/xml");
  38332. }
  38333. else
  38334. {
  38335. xml = new ActiveXObject("Microsoft.XMLDOM");
  38336. xml.async = 'false';
  38337. xml.loadXML(atlasData);
  38338. }
  38339. }
  38340. catch (e)
  38341. {
  38342. xml = undefined;
  38343. }
  38344. if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length)
  38345. {
  38346. throw new Error("Phaser.Loader. Invalid Texture Atlas XML given");
  38347. }
  38348. else
  38349. {
  38350. atlasData = xml;
  38351. }
  38352. }
  38353. break;
  38354. }
  38355. this.addToFileList('textureatlas', key, textureURL, { atlasURL: null, atlasData: atlasData, format: format });
  38356. }
  38357. return this;
  38358. },
  38359. /**
  38360. * Remove loading request of a file.
  38361. *
  38362. * @method Phaser.Loader#removeFile
  38363. * @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
  38364. * @param {string} key - Key of the file you want to remove.
  38365. */
  38366. removeFile: function (type, key) {
  38367. var file = this.getAsset(type, key);
  38368. if (file !== false)
  38369. {
  38370. this._fileList.splice(file.index, 1);
  38371. }
  38372. },
  38373. /**
  38374. * Remove all file loading requests.
  38375. *
  38376. * @method Phaser.Loader#removeAll
  38377. */
  38378. removeAll: function () {
  38379. this._fileList.length = 0;
  38380. },
  38381. /**
  38382. * Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so.
  38383. *
  38384. * @method Phaser.Loader#start
  38385. */
  38386. start: function () {
  38387. if (this.isLoading)
  38388. {
  38389. return;
  38390. }
  38391. if (this._packList.length > 0)
  38392. {
  38393. this._packIndex = 0;
  38394. this.loadPack();
  38395. }
  38396. else
  38397. {
  38398. this.beginLoad();
  38399. }
  38400. },
  38401. /**
  38402. * Starts off the actual loading process after the asset packs have been sorted out.
  38403. *
  38404. * @method Phaser.Loader#beginLoad
  38405. * @private
  38406. */
  38407. beginLoad: function () {
  38408. this.progress = 0;
  38409. this.progressFloat = 0;
  38410. this.hasLoaded = false;
  38411. this.isLoading = true;
  38412. this.onLoadStart.dispatch(this._fileList.length);
  38413. if (this._fileList.length > 0)
  38414. {
  38415. this._fileIndex = 0;
  38416. this._progressChunk = 100 / this._fileList.length;
  38417. this.loadFile();
  38418. }
  38419. else
  38420. {
  38421. this.progress = 100;
  38422. this.progressFloat = 100;
  38423. this.hasLoaded = true;
  38424. this.isLoading = false;
  38425. this.onLoadComplete.dispatch();
  38426. }
  38427. },
  38428. /**
  38429. * Loads the current asset pack in the queue.
  38430. *
  38431. * @method Phaser.Loader#loadPack
  38432. * @private
  38433. */
  38434. loadPack: function () {
  38435. if (!this._packList[this._packIndex])
  38436. {
  38437. console.warn('Phaser.Loader loadPackList invalid index ' + this._packIndex);
  38438. return;
  38439. }
  38440. var pack = this._packList[this._packIndex];
  38441. if (pack.data !== null)
  38442. {
  38443. this.packLoadComplete(this._packIndex, false);
  38444. }
  38445. else
  38446. {
  38447. // Load it
  38448. this.xhrLoad(this._packIndex, this.baseURL + pack.url, 'text', 'packLoadComplete', 'packLoadError');
  38449. }
  38450. },
  38451. /**
  38452. * Handle the successful loading of a JSON asset pack.
  38453. *
  38454. * @method Phaser.Loader#packLoadComplete
  38455. * @private
  38456. * @param {number} index - The index of the file in the file queue that loaded.
  38457. * @param {boolean} [parse=true] - Automatically parse the JSON data?
  38458. */
  38459. packLoadComplete: function (index, parse) {
  38460. if (typeof parse === 'undefined') { parse = true; }
  38461. if (!this._packList[index])
  38462. {
  38463. console.warn('Phaser.Loader packLoadComplete invalid index ' + index);
  38464. return;
  38465. }
  38466. var pack = this._packList[index];
  38467. pack.loaded = true;
  38468. if (parse)
  38469. {
  38470. var data = JSON.parse(this._xhr.responseText);
  38471. }
  38472. else
  38473. {
  38474. var data = this._packList[index].data;
  38475. }
  38476. if (data[pack.key])
  38477. {
  38478. var file;
  38479. for (var i = 0; i < data[pack.key].length; i++)
  38480. {
  38481. file = data[pack.key][i];
  38482. switch (file.type)
  38483. {
  38484. case "image":
  38485. this.image(file.key, file.url, file.overwrite);
  38486. break;
  38487. case "text":
  38488. this.text(file.key, file.url, file.overwrite);
  38489. break;
  38490. case "json":
  38491. this.json(file.key, file.url, file.overwrite);
  38492. break;
  38493. case "script":
  38494. this.script(file.key, file.url, file.callback, pack.callbackContext);
  38495. break;
  38496. case "binary":
  38497. this.binary(file.key, file.url, file.callback, pack.callbackContext);
  38498. break;
  38499. case "spritesheet":
  38500. this.spritesheet(file.key, file.url, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing);
  38501. break;
  38502. case "audio":
  38503. this.audio(file.key, file.urls, file.autoDecode);
  38504. break;
  38505. case "tilemap":
  38506. this.tilemap(file.key, file.url, file.data, Phaser.Tilemap[file.format]);
  38507. break;
  38508. case "physics":
  38509. this.physics(file.key, file.url, file.data, Phaser.Loader[file.format]);
  38510. break;
  38511. case "bitmapFont":
  38512. this.bitmapFont(file.key, file.textureURL, file.xmlURL, file.xmlData, file.xSpacing, file.ySpacing);
  38513. break;
  38514. case "atlasJSONArray":
  38515. this.atlasJSONArray(file.key, file.textureURL, file.atlasURL, file.atlasData);
  38516. break;
  38517. case "atlasJSONHash":
  38518. this.atlasJSONHash(file.key, file.textureURL, file.atlasURL, file.atlasData);
  38519. break;
  38520. case "atlasXML":
  38521. this.atlasXML(file.key, file.textureURL, file.atlasURL, file.atlasData);
  38522. break;
  38523. case "atlas":
  38524. this.atlas(file.key, file.textureURL, file.atlasURL, file.atlasData, Phaser.Loader[file.format]);
  38525. break;
  38526. }
  38527. }
  38528. }
  38529. this.nextPack(index, true);
  38530. },
  38531. /**
  38532. * Error occured when loading an asset pack.
  38533. *
  38534. * @method Phaser.Loader#packError
  38535. * @private
  38536. * @param {number} index - The index of the file in the file queue that errored.
  38537. */
  38538. packError: function (index) {
  38539. this._packList[index].loaded = true;
  38540. this._packList[index].error = true;
  38541. this.onFileError.dispatch(this._packList[index].key, this._packList[index]);
  38542. console.warn("Phaser.Loader error loading pack file: " + this._packList[index].key + ' from URL ' + this._packList[index].url);
  38543. this.nextPack(index, false);
  38544. },
  38545. /**
  38546. * Handle loading the next asset pack.
  38547. *
  38548. * @method Phaser.Loader#nextPack
  38549. * @private
  38550. */
  38551. nextPack: function (index, success) {
  38552. this.onPackComplete.dispatch(this._packList[index].key, success, this.totalLoadedPacks(), this._packList.length);
  38553. this._packIndex++;
  38554. if (this._packIndex < this._packList.length)
  38555. {
  38556. this.loadPack();
  38557. }
  38558. else
  38559. {
  38560. this.beginLoad();
  38561. }
  38562. },
  38563. /**
  38564. * Load files. Private method ONLY used by loader.
  38565. *
  38566. * @method Phaser.Loader#loadFile
  38567. * @private
  38568. */
  38569. loadFile: function () {
  38570. if (!this._fileList[this._fileIndex])
  38571. {
  38572. console.warn('Phaser.Loader loadFile invalid index ' + this._fileIndex);
  38573. return;
  38574. }
  38575. var file = this._fileList[this._fileIndex];
  38576. var _this = this;
  38577. this.onFileStart.dispatch(this.progress, file.key);
  38578. // Image or Data?
  38579. switch (file.type)
  38580. {
  38581. case 'image':
  38582. case 'spritesheet':
  38583. case 'textureatlas':
  38584. case 'bitmapfont':
  38585. file.data = new Image();
  38586. file.data.name = file.key;
  38587. file.data.onload = function () {
  38588. return _this.fileComplete(_this._fileIndex);
  38589. };
  38590. file.data.onerror = function () {
  38591. return _this.fileError(_this._fileIndex);
  38592. };
  38593. if (this.crossOrigin)
  38594. {
  38595. file.data.crossOrigin = this.crossOrigin;
  38596. }
  38597. file.data.src = this.baseURL + file.url;
  38598. break;
  38599. case 'audio':
  38600. file.url = this.getAudioURL(file.url);
  38601. if (file.url !== null)
  38602. {
  38603. // WebAudio or Audio Tag?
  38604. if (this.game.sound.usingWebAudio)
  38605. {
  38606. this.xhrLoad(this._fileIndex, this.baseURL + file.url, 'arraybuffer', 'fileComplete', 'fileError');
  38607. }
  38608. else if (this.game.sound.usingAudioTag)
  38609. {
  38610. if (this.game.sound.touchLocked)
  38611. {
  38612. // If audio is locked we can't do this yet, so need to queue this load request. Bum.
  38613. file.data = new Audio();
  38614. file.data.name = file.key;
  38615. file.data.preload = 'auto';
  38616. file.data.src = this.baseURL + file.url;
  38617. this.fileComplete(this._fileIndex);
  38618. }
  38619. else
  38620. {
  38621. file.data = new Audio();
  38622. file.data.name = file.key;
  38623. file.data.onerror = function () {
  38624. return _this.fileError(_this._fileIndex);
  38625. };
  38626. file.data.preload = 'auto';
  38627. file.data.src = this.baseURL + file.url;
  38628. file.data.addEventListener('canplaythrough', Phaser.GAMES[this.game.id].load.fileComplete(this._fileIndex), false);
  38629. file.data.load();
  38630. }
  38631. }
  38632. }
  38633. else
  38634. {
  38635. this.fileError(this._fileIndex);
  38636. }
  38637. break;
  38638. case 'json':
  38639. if (window.XDomainRequest)
  38640. {
  38641. this._ajax = new window.XDomainRequest();
  38642. // XDomainRequest has a few querks. Occasionally it will abort requests
  38643. // A way to avoid this is to make sure ALL callbacks are set even if not used
  38644. // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9
  38645. this._ajax.timeout = 3000;
  38646. this._ajax.onerror = function () {
  38647. return _this.dataLoadError(_this._fileIndex);
  38648. };
  38649. this._ajax.ontimeout = function () {
  38650. return _this.dataLoadError(_this._fileIndex);
  38651. };
  38652. this._ajax.onprogress = function() {};
  38653. this._ajax.onload = function(){
  38654. return _this.jsonLoadComplete(_this._fileIndex);
  38655. };
  38656. this._ajax.open('GET', this.baseURL + file.url, true);
  38657. this._ajax.send();
  38658. }
  38659. else
  38660. {
  38661. this.xhrLoad(this._fileIndex, this.baseURL + file.url, 'text', 'jsonLoadComplete', 'dataLoadError');
  38662. }
  38663. break;
  38664. case 'tilemap':
  38665. if (file.format === Phaser.Tilemap.TILED_JSON)
  38666. {
  38667. this.xhrLoad(this._fileIndex, this.baseURL + file.url, 'text', 'jsonLoadComplete', 'dataLoadError');
  38668. }
  38669. else if (file.format === Phaser.Tilemap.CSV)
  38670. {
  38671. this.xhrLoad(this._fileIndex, this.baseURL + file.url, 'text', 'csvLoadComplete', 'dataLoadError');
  38672. }
  38673. else
  38674. {
  38675. throw new Error("Phaser.Loader. Invalid Tilemap format: " + file.format);
  38676. }
  38677. break;
  38678. case 'text':
  38679. case 'script':
  38680. case 'physics':
  38681. this.xhrLoad(this._fileIndex, this.baseURL + file.url, 'text', 'fileComplete', 'fileError');
  38682. break;
  38683. case 'binary':
  38684. this.xhrLoad(this._fileIndex, this.baseURL + file.url, 'arraybuffer', 'fileComplete', 'fileError');
  38685. break;
  38686. }
  38687. },
  38688. /**
  38689. * Starts the xhr loader.
  38690. *
  38691. * @method Phaser.Loader#xhrLoad
  38692. * @private
  38693. * @param {number} index - The index of the file to load from the file list.
  38694. * @param {string} url - The URL of the file.
  38695. * @param {string} type - The xhr responseType.
  38696. * @param {string} onload - A String of the name of the local function to be called on a successful file load.
  38697. * @param {string} onerror - A String of the name of the local function to be called on a file load error.
  38698. */
  38699. xhrLoad: function (index, url, type, onload, onerror) {
  38700. this._xhr.open("GET", url, true);
  38701. this._xhr.responseType = type;
  38702. var _this = this;
  38703. this._xhr.onload = function () {
  38704. return _this[onload](index);
  38705. };
  38706. this._xhr.onerror = function () {
  38707. return _this[onerror](index);
  38708. };
  38709. this._xhr.send();
  38710. },
  38711. /**
  38712. * Private method ONLY used by loader.
  38713. *
  38714. * @method Phaser.Loader#getAudioURL
  38715. * @private
  38716. * @param {array|string} urls - Either an array of audio file URLs or a string containing a single URL path.
  38717. */
  38718. getAudioURL: function (urls) {
  38719. var extension;
  38720. if (typeof urls === 'string') { urls = [urls]; }
  38721. for (var i = 0; i < urls.length; i++)
  38722. {
  38723. extension = urls[i].toLowerCase();
  38724. extension = extension.substr((Math.max(0, extension.lastIndexOf(".")) || Infinity) + 1);
  38725. if (this.game.device.canPlayAudio(extension))
  38726. {
  38727. return urls[i];
  38728. }
  38729. }
  38730. return null;
  38731. },
  38732. /**
  38733. * Error occured when loading a file.
  38734. *
  38735. * @method Phaser.Loader#fileError
  38736. * @param {number} index - The index of the file in the file queue that errored.
  38737. */
  38738. fileError: function (index) {
  38739. this._fileList[index].loaded = true;
  38740. this._fileList[index].error = true;
  38741. this.onFileError.dispatch(this._fileList[index].key, this._fileList[index]);
  38742. console.warn("Phaser.Loader error loading file: " + this._fileList[index].key + ' from URL ' + this._fileList[index].url);
  38743. this.nextFile(index, false);
  38744. },
  38745. /**
  38746. * Called when a file is successfully loaded.
  38747. *
  38748. * @method Phaser.Loader#fileComplete
  38749. * @param {number} index - The index of the file in the file queue that loaded.
  38750. */
  38751. fileComplete: function (index) {
  38752. if (!this._fileList[index])
  38753. {
  38754. console.warn('Phaser.Loader fileComplete invalid index ' + index);
  38755. return;
  38756. }
  38757. var file = this._fileList[index];
  38758. file.loaded = true;
  38759. var loadNext = true;
  38760. switch (file.type)
  38761. {
  38762. case 'image':
  38763. this.game.cache.addImage(file.key, file.url, file.data);
  38764. break;
  38765. case 'spritesheet':
  38766. this.game.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing);
  38767. break;
  38768. case 'textureatlas':
  38769. if (file.atlasURL == null)
  38770. {
  38771. this.game.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format);
  38772. }
  38773. else
  38774. {
  38775. // Load the JSON or XML before carrying on with the next file
  38776. loadNext = false;
  38777. if (file.format == Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY || file.format == Phaser.Loader.TEXTURE_ATLAS_JSON_HASH)
  38778. {
  38779. this.xhrLoad(this._fileIndex, this.baseURL + file.atlasURL, 'text', 'jsonLoadComplete', 'dataLoadError');
  38780. }
  38781. else if (file.format == Phaser.Loader.TEXTURE_ATLAS_XML_STARLING)
  38782. {
  38783. this.xhrLoad(this._fileIndex, this.baseURL + file.atlasURL, 'text', 'xmlLoadComplete', 'dataLoadError');
  38784. }
  38785. else
  38786. {
  38787. throw new Error("Phaser.Loader. Invalid Texture Atlas format: " + file.format);
  38788. }
  38789. }
  38790. break;
  38791. case 'bitmapfont':
  38792. if (file.xmlURL == null)
  38793. {
  38794. this.game.cache.addBitmapFont(file.key, file.url, file.data, file.xmlData, file.xSpacing, file.ySpacing);
  38795. }
  38796. else
  38797. {
  38798. // Load the XML before carrying on with the next file
  38799. loadNext = false;
  38800. this.xhrLoad(this._fileIndex, this.baseURL + file.xmlURL, 'text', 'xmlLoadComplete', 'dataLoadError');
  38801. }
  38802. break;
  38803. case 'audio':
  38804. if (this.game.sound.usingWebAudio)
  38805. {
  38806. file.data = this._xhr.response;
  38807. this.game.cache.addSound(file.key, file.url, file.data, true, false);
  38808. if (file.autoDecode)
  38809. {
  38810. var that = this;
  38811. var key = file.key;
  38812. this.game.cache.updateSound(key, 'isDecoding', true);
  38813. this.game.sound.context.decodeAudioData(file.data, function (buffer) {
  38814. if (buffer)
  38815. {
  38816. that.game.cache.decodedSound(key, buffer);
  38817. that.game.sound.onSoundDecode.dispatch(key, that.game.cache.getSound(key));
  38818. }
  38819. });
  38820. }
  38821. }
  38822. else
  38823. {
  38824. file.data.removeEventListener('canplaythrough', Phaser.GAMES[this.game.id].load.fileComplete);
  38825. this.game.cache.addSound(file.key, file.url, file.data, false, true);
  38826. }
  38827. break;
  38828. case 'text':
  38829. file.data = this._xhr.responseText;
  38830. this.game.cache.addText(file.key, file.url, file.data);
  38831. break;
  38832. case 'physics':
  38833. var data = JSON.parse(this._xhr.responseText);
  38834. this.game.cache.addPhysicsData(file.key, file.url, data, file.format);
  38835. break;
  38836. case 'script':
  38837. file.data = document.createElement('script');
  38838. file.data.language = 'javascript';
  38839. file.data.type = 'text/javascript';
  38840. file.data.defer = false;
  38841. file.data.text = this._xhr.responseText;
  38842. document.head.appendChild(file.data);
  38843. if (file.callback)
  38844. {
  38845. file.data = file.callback.call(file.callbackContext, file.key, this._xhr.responseText);
  38846. }
  38847. break;
  38848. case 'binary':
  38849. if (file.callback)
  38850. {
  38851. file.data = file.callback.call(file.callbackContext, file.key, this._xhr.response);
  38852. }
  38853. else
  38854. {
  38855. file.data = this._xhr.response;
  38856. }
  38857. this.game.cache.addBinary(file.key, file.data);
  38858. break;
  38859. }
  38860. if (loadNext)
  38861. {
  38862. this.nextFile(index, true);
  38863. }
  38864. },
  38865. /**
  38866. * Successfully loaded a JSON file.
  38867. *
  38868. * @method Phaser.Loader#jsonLoadComplete
  38869. * @param {number} index - The index of the file in the file queue that loaded.
  38870. */
  38871. jsonLoadComplete: function (index) {
  38872. if (!this._fileList[index])
  38873. {
  38874. console.warn('Phaser.Loader jsonLoadComplete invalid index ' + index);
  38875. return;
  38876. }
  38877. var file = this._fileList[index];
  38878. var data = JSON.parse(this._xhr.responseText);
  38879. file.loaded = true;
  38880. if (file.type === 'tilemap')
  38881. {
  38882. this.game.cache.addTilemap(file.key, file.url, data, file.format);
  38883. }
  38884. else if (file.type === 'json')
  38885. {
  38886. this.game.cache.addJSON(file.key, file.url, data);
  38887. }
  38888. else
  38889. {
  38890. this.game.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format);
  38891. }
  38892. this.nextFile(index, true);
  38893. },
  38894. /**
  38895. * Successfully loaded a CSV file.
  38896. *
  38897. * @method Phaser.Loader#csvLoadComplete
  38898. * @param {number} index - The index of the file in the file queue that loaded.
  38899. */
  38900. csvLoadComplete: function (index) {
  38901. if (!this._fileList[index])
  38902. {
  38903. console.warn('Phaser.Loader csvLoadComplete invalid index ' + index);
  38904. return;
  38905. }
  38906. var file = this._fileList[index];
  38907. var data = this._xhr.responseText;
  38908. file.loaded = true;
  38909. this.game.cache.addTilemap(file.key, file.url, data, file.format);
  38910. this.nextFile(index, true);
  38911. },
  38912. /**
  38913. * Error occured when load a JSON.
  38914. *
  38915. * @method Phaser.Loader#dataLoadError
  38916. * @param {number} index - The index of the file in the file queue that errored.
  38917. */
  38918. dataLoadError: function (index) {
  38919. var file = this._fileList[index];
  38920. file.loaded = true;
  38921. file.error = true;
  38922. console.warn("Phaser.Loader dataLoadError: " + file.key);
  38923. this.nextFile(index, true);
  38924. },
  38925. /**
  38926. * Successfully loaded an XML file.
  38927. *
  38928. * @method Phaser.Loader#xmlLoadComplete
  38929. * @param {number} index - The index of the file in the file queue that loaded.
  38930. */
  38931. xmlLoadComplete: function (index) {
  38932. var data = this._xhr.responseText;
  38933. var xml;
  38934. try
  38935. {
  38936. if (window['DOMParser'])
  38937. {
  38938. var domparser = new DOMParser();
  38939. xml = domparser.parseFromString(data, "text/xml");
  38940. }
  38941. else
  38942. {
  38943. xml = new ActiveXObject("Microsoft.XMLDOM");
  38944. xml.async = 'false';
  38945. xml.loadXML(data);
  38946. }
  38947. }
  38948. catch (e)
  38949. {
  38950. xml = undefined;
  38951. }
  38952. if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length)
  38953. {
  38954. throw new Error("Phaser.Loader. Invalid XML given");
  38955. }
  38956. var file = this._fileList[index];
  38957. file.loaded = true;
  38958. if (file.type == 'bitmapfont')
  38959. {
  38960. this.game.cache.addBitmapFont(file.key, file.url, file.data, xml, file.xSpacing, file.ySpacing);
  38961. }
  38962. else if (file.type == 'textureatlas')
  38963. {
  38964. this.game.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format);
  38965. }
  38966. this.nextFile(index, true);
  38967. },
  38968. /**
  38969. * Handle loading next file.
  38970. *
  38971. * @method Phaser.Loader#nextFile
  38972. * @private
  38973. * @param {number} previousIndex - Index of the previously loaded asset.
  38974. * @param {boolean} success - Whether the previous asset loaded successfully or not.
  38975. */
  38976. nextFile: function (previousIndex, success) {
  38977. this.progressFloat += this._progressChunk;
  38978. this.progress = Math.round(this.progressFloat);
  38979. if (this.progress > 100)
  38980. {
  38981. this.progress = 100;
  38982. }
  38983. if (this.preloadSprite !== null)
  38984. {
  38985. if (this.preloadSprite.direction === 0)
  38986. {
  38987. this.preloadSprite.rect.width = Math.floor((this.preloadSprite.width / 100) * this.progress);
  38988. this.preloadSprite.sprite.crop(this.preloadSprite.rect);
  38989. }
  38990. else
  38991. {
  38992. this.preloadSprite.rect.height = Math.floor((this.preloadSprite.height / 100) * this.progress);
  38993. this.preloadSprite.sprite.crop(this.preloadSprite.rect);
  38994. }
  38995. }
  38996. this.onFileComplete.dispatch(this.progress, this._fileList[previousIndex].key, success, this.totalLoadedFiles(), this._fileList.length);
  38997. if (this.totalQueuedFiles() > 0)
  38998. {
  38999. this._fileIndex++;
  39000. this.loadFile();
  39001. }
  39002. else
  39003. {
  39004. this.hasLoaded = true;
  39005. this.isLoading = false;
  39006. this.removeAll();
  39007. this.onLoadComplete.dispatch();
  39008. }
  39009. },
  39010. /**
  39011. * Returns the number of files that have already been loaded, even if they errored.
  39012. *
  39013. * @method Phaser.Loader#totalLoadedFiles
  39014. * @return {number} The number of files that have already been loaded (even if they errored)
  39015. */
  39016. totalLoadedFiles: function () {
  39017. var total = 0;
  39018. for (var i = 0; i < this._fileList.length; i++)
  39019. {
  39020. if (this._fileList[i].loaded)
  39021. {
  39022. total++;
  39023. }
  39024. }
  39025. return total;
  39026. },
  39027. /**
  39028. * 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.
  39029. *
  39030. * @method Phaser.Loader#totalQueuedFiles
  39031. * @return {number} The number of files that still remain in the load queue.
  39032. */
  39033. totalQueuedFiles: function () {
  39034. var total = 0;
  39035. for (var i = 0; i < this._fileList.length; i++)
  39036. {
  39037. if (this._fileList[i].loaded === false)
  39038. {
  39039. total++;
  39040. }
  39041. }
  39042. return total;
  39043. },
  39044. /**
  39045. * Returns the number of asset packs that have already been loaded, even if they errored.
  39046. *
  39047. * @method Phaser.Loader#totalLoadedPacks
  39048. * @return {number} The number of asset packs that have already been loaded (even if they errored)
  39049. */
  39050. totalLoadedPacks: function () {
  39051. var total = 0;
  39052. for (var i = 0; i < this._packList.length; i++)
  39053. {
  39054. if (this._packList[i].loaded)
  39055. {
  39056. total++;
  39057. }
  39058. }
  39059. return total;
  39060. },
  39061. /**
  39062. * 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.
  39063. *
  39064. * @method Phaser.Loader#totalQueuedPacks
  39065. * @return {number} The number of asset packs that still remain in the load queue.
  39066. */
  39067. totalQueuedPacks: function () {
  39068. var total = 0;
  39069. for (var i = 0; i < this._packList.length; i++)
  39070. {
  39071. if (this._packList[i].loaded === false)
  39072. {
  39073. total++;
  39074. }
  39075. }
  39076. return total;
  39077. }
  39078. };
  39079. Phaser.Loader.prototype.constructor = Phaser.Loader;
  39080. /**
  39081. * @author Richard Davey <rich@photonstorm.com>
  39082. * @copyright 2014 Photon Storm Ltd.
  39083. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  39084. */
  39085. /**
  39086. * Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache.
  39087. *
  39088. * @class Phaser.LoaderParser
  39089. */
  39090. Phaser.LoaderParser = {
  39091. /**
  39092. * Parse a Bitmap Font from an XML file.
  39093. *
  39094. * @method Phaser.LoaderParser.bitmapFont
  39095. * @param {Phaser.Game} game - A reference to the current game.
  39096. * @param {object} xml - XML data you want to parse.
  39097. * @param {string} cacheKey - The key of the texture this font uses in the cache.
  39098. * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters.
  39099. * @param {number} [ySpacing=0] - Additional vertical spacing between the characters.
  39100. */
  39101. bitmapFont: function (game, xml, cacheKey, xSpacing, ySpacing) {
  39102. var data = {};
  39103. var info = xml.getElementsByTagName('info')[0];
  39104. var common = xml.getElementsByTagName('common')[0];
  39105. data.font = info.getAttribute('face');
  39106. data.size = parseInt(info.getAttribute('size'), 10);
  39107. data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) + ySpacing;
  39108. data.chars = {};
  39109. var letters = xml.getElementsByTagName('char');
  39110. for (var i = 0; i < letters.length; i++)
  39111. {
  39112. var charCode = parseInt(letters[i].getAttribute('id'), 10);
  39113. var textureRect = new PIXI.Rectangle(
  39114. parseInt(letters[i].getAttribute('x'), 10),
  39115. parseInt(letters[i].getAttribute('y'), 10),
  39116. parseInt(letters[i].getAttribute('width'), 10),
  39117. parseInt(letters[i].getAttribute('height'), 10)
  39118. );
  39119. data.chars[charCode] = {
  39120. xOffset: parseInt(letters[i].getAttribute('xoffset'), 10),
  39121. yOffset: parseInt(letters[i].getAttribute('yoffset'), 10),
  39122. xAdvance: parseInt(letters[i].getAttribute('xadvance'), 10) + xSpacing,
  39123. kerning: {},
  39124. texture: PIXI.TextureCache[cacheKey] = new PIXI.Texture(PIXI.BaseTextureCache[cacheKey], textureRect)
  39125. };
  39126. }
  39127. var kernings = xml.getElementsByTagName('kerning');
  39128. for (i = 0; i < kernings.length; i++)
  39129. {
  39130. var first = parseInt(kernings[i].getAttribute('first'), 10);
  39131. var second = parseInt(kernings[i].getAttribute('second'), 10);
  39132. var amount = parseInt(kernings[i].getAttribute('amount'), 10);
  39133. data.chars[second].kerning[first] = amount;
  39134. }
  39135. PIXI.BitmapText.fonts[cacheKey] = data;
  39136. }
  39137. };
  39138. /**
  39139. * @author Richard Davey <rich@photonstorm.com>
  39140. * @copyright 2014 Photon Storm Ltd.
  39141. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  39142. */
  39143. /**
  39144. * The Sound class constructor.
  39145. *
  39146. * @class Phaser.Sound
  39147. * @classdesc The Sound class
  39148. * @constructor
  39149. * @param {Phaser.Game} game - Reference to the current game instance.
  39150. * @param {string} key - Asset key for the sound.
  39151. * @param {number} [volume=1] - Default value for the volume, between 0 and 1.
  39152. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  39153. */
  39154. Phaser.Sound = function (game, key, volume, loop, connect) {
  39155. if (typeof volume == 'undefined') { volume = 1; }
  39156. if (typeof loop == 'undefined') { loop = false; }
  39157. if (typeof connect === 'undefined') { connect = game.sound.connectToMaster; }
  39158. /**
  39159. * A reference to the currently running Game.
  39160. * @property {Phaser.Game} game
  39161. */
  39162. this.game = game;
  39163. /**
  39164. * @property {string} name - Name of the sound.
  39165. */
  39166. this.name = key;
  39167. /**
  39168. * @property {string} key - Asset key for the sound.
  39169. */
  39170. this.key = key;
  39171. /**
  39172. * @property {boolean} loop - Whether or not the sound or current sound marker will loop.
  39173. */
  39174. this.loop = loop;
  39175. /**
  39176. * @property {number} volume - The sound or sound marker volume. A value between 0 (silence) and 1 (full volume).
  39177. */
  39178. this.volume = volume;
  39179. /**
  39180. * @property {object} markers - The sound markers.
  39181. */
  39182. this.markers = {};
  39183. /**
  39184. * @property {AudioContext} context - Reference to the AudioContext instance.
  39185. */
  39186. this.context = null;
  39187. /**
  39188. * @property {boolean} autoplay - Boolean indicating whether the sound should start automatically.
  39189. */
  39190. this.autoplay = false;
  39191. /**
  39192. * @property {number} totalDuration - The total duration of the sound in seconds.
  39193. */
  39194. this.totalDuration = 0;
  39195. /**
  39196. * @property {number} startTime - The time the Sound starts at (typically 0 unless starting from a marker)
  39197. * @default
  39198. */
  39199. this.startTime = 0;
  39200. /**
  39201. * @property {number} currentTime - The current time the sound is at.
  39202. */
  39203. this.currentTime = 0;
  39204. /**
  39205. * @property {number} duration - The duration of the current sound marker in seconds.
  39206. */
  39207. this.duration = 0;
  39208. /**
  39209. * @property {number} durationMS - The duration of the current sound marker in ms.
  39210. */
  39211. this.durationMS = 0;
  39212. /**
  39213. * @property {number} position - The position of the current sound marker.
  39214. */
  39215. this.position = 0;
  39216. /**
  39217. * @property {number} stopTime - The time the sound stopped.
  39218. */
  39219. this.stopTime = 0;
  39220. /**
  39221. * @property {boolean} paused - true if the sound is paused, otherwise false.
  39222. * @default
  39223. */
  39224. this.paused = false;
  39225. /**
  39226. * @property {number} pausedPosition - The position the sound had reached when it was paused.
  39227. */
  39228. this.pausedPosition = 0;
  39229. /**
  39230. * @property {number} pausedTime - The game time at which the sound was paused.
  39231. */
  39232. this.pausedTime = 0;
  39233. /**
  39234. * @property {boolean} isPlaying - true if the sound is currently playing, otherwise false.
  39235. * @default
  39236. */
  39237. this.isPlaying = false;
  39238. /**
  39239. * @property {string} currentMarker - The string ID of the currently playing marker, if any.
  39240. * @default
  39241. */
  39242. this.currentMarker = '';
  39243. /**
  39244. * @property {boolean} pendingPlayback - true if the sound file is pending playback
  39245. * @readonly
  39246. */
  39247. this.pendingPlayback = false;
  39248. /**
  39249. * @property {boolean} override - if true when you play this sound it will always start from the beginning.
  39250. * @default
  39251. */
  39252. this.override = false;
  39253. /**
  39254. * @property {boolean} usingWebAudio - true if this sound is being played with Web Audio.
  39255. * @readonly
  39256. */
  39257. this.usingWebAudio = this.game.sound.usingWebAudio;
  39258. /**
  39259. * @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag.
  39260. */
  39261. this.usingAudioTag = this.game.sound.usingAudioTag;
  39262. /**
  39263. * @property {object} externalNode - If defined this Sound won't connect to the SoundManager master gain node, but will instead connect to externalNode.
  39264. */
  39265. this.externalNode = null;
  39266. /**
  39267. * @property {object} masterGainNode - The master gain node in a Web Audio system.
  39268. */
  39269. this.masterGainNode = null;
  39270. /**
  39271. * @property {object} gainNode - The gain node in a Web Audio system.
  39272. */
  39273. this.gainNode = null;
  39274. if (this.usingWebAudio)
  39275. {
  39276. this.context = this.game.sound.context;
  39277. this.masterGainNode = this.game.sound.masterGain;
  39278. if (typeof this.context.createGain === 'undefined')
  39279. {
  39280. this.gainNode = this.context.createGainNode();
  39281. }
  39282. else
  39283. {
  39284. this.gainNode = this.context.createGain();
  39285. }
  39286. this.gainNode.gain.value = volume * this.game.sound.volume;
  39287. if (connect)
  39288. {
  39289. this.gainNode.connect(this.masterGainNode);
  39290. }
  39291. }
  39292. else
  39293. {
  39294. if (this.game.cache.getSound(key) && this.game.cache.isSoundReady(key))
  39295. {
  39296. this._sound = this.game.cache.getSoundData(key);
  39297. this.totalDuration = 0;
  39298. if (this._sound.duration)
  39299. {
  39300. this.totalDuration = this._sound.duration;
  39301. }
  39302. }
  39303. else
  39304. {
  39305. this.game.cache.onSoundUnlock.add(this.soundHasUnlocked, this);
  39306. }
  39307. }
  39308. /**
  39309. * @property {Phaser.Signal} onDecoded - The onDecoded event is dispatched when the sound has finished decoding (typically for mp3 files)
  39310. */
  39311. this.onDecoded = new Phaser.Signal();
  39312. /**
  39313. * @property {Phaser.Signal} onPlay - The onPlay event is dispatched each time this sound is played.
  39314. */
  39315. this.onPlay = new Phaser.Signal();
  39316. /**
  39317. * @property {Phaser.Signal} onPause - The onPause event is dispatched when this sound is paused.
  39318. */
  39319. this.onPause = new Phaser.Signal();
  39320. /**
  39321. * @property {Phaser.Signal} onResume - The onResume event is dispatched when this sound is resumed from a paused state.
  39322. */
  39323. this.onResume = new Phaser.Signal();
  39324. /**
  39325. * @property {Phaser.Signal} onLoop - The onLoop event is dispatched when this sound loops during playback.
  39326. */
  39327. this.onLoop = new Phaser.Signal();
  39328. /**
  39329. * @property {Phaser.Signal} onStop - The onStop event is dispatched when this sound stops playback.
  39330. */
  39331. this.onStop = new Phaser.Signal();
  39332. /**
  39333. * @property {Phaser.Signal} onMute - The onMouse event is dispatched when this sound is muted.
  39334. */
  39335. this.onMute = new Phaser.Signal();
  39336. /**
  39337. * @property {Phaser.Signal} onMarkerComplete - The onMarkerComplete event is dispatched when a marker within this sound completes playback.
  39338. */
  39339. this.onMarkerComplete = new Phaser.Signal();
  39340. /**
  39341. * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume).
  39342. * @private
  39343. */
  39344. this._volume = volume;
  39345. /**
  39346. * @property {any} _buffer - Decoded data buffer / Audio tag.
  39347. * @private
  39348. */
  39349. this._buffer = null;
  39350. /**
  39351. * @property {boolean} _muted - Boolean indicating whether the sound is muted or not.
  39352. * @private
  39353. */
  39354. this._muted = false;
  39355. /**
  39356. * @property {number} _tempMarker - Internal marker var.
  39357. * @private
  39358. */
  39359. this._tempMarker = 0;
  39360. /**
  39361. * @property {number} _tempPosition - Internal marker var.
  39362. * @private
  39363. */
  39364. this._tempPosition = 0;
  39365. /**
  39366. * @property {number} _tempVolume - Internal marker var.
  39367. * @private
  39368. */
  39369. this._tempVolume = 0;
  39370. /**
  39371. * @property {boolean} _tempLoop - Internal marker var.
  39372. * @private
  39373. */
  39374. this._tempLoop = 0;
  39375. /**
  39376. * @property {boolean} _paused - Was this sound paused via code or a game event?
  39377. * @private
  39378. */
  39379. this._paused = false;
  39380. /**
  39381. * @property {boolean} _onDecodedEventDispatched - Was the onDecoded event dispatched?
  39382. * @private
  39383. */
  39384. this._onDecodedEventDispatched = false;
  39385. };
  39386. Phaser.Sound.prototype = {
  39387. /**
  39388. * Called automatically when this sound is unlocked.
  39389. * @method Phaser.Sound#soundHasUnlocked
  39390. * @param {string} key - The Phaser.Cache key of the sound file to check for decoding.
  39391. * @protected
  39392. */
  39393. soundHasUnlocked: function (key) {
  39394. if (key == this.key)
  39395. {
  39396. this._sound = this.game.cache.getSoundData(this.key);
  39397. this.totalDuration = this._sound.duration;
  39398. }
  39399. },
  39400. /**
  39401. * Adds a marker into the current Sound. A marker is represented by a unique key and a start time and duration.
  39402. * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback.
  39403. *
  39404. * @method Phaser.Sound#addMarker
  39405. * @param {string} name - A unique name for this marker, i.e. 'explosion', 'gunshot', etc.
  39406. * @param {number} start - The start point of this marker in the audio file, given in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc.
  39407. * @param {number} duration - The duration of the marker in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc.
  39408. * @param {number} [volume=1] - The volume the sound will play back at, between 0 (silent) and 1 (full volume).
  39409. * @param {boolean} [loop=false] - Sets if the sound will loop or not.
  39410. */
  39411. addMarker: function (name, start, duration, volume, loop) {
  39412. if (typeof volume == 'undefined') { volume = 1; }
  39413. if (typeof loop == 'undefined') { loop = false; }
  39414. this.markers[name] = {
  39415. name: name,
  39416. start: start,
  39417. stop: start + duration,
  39418. volume: volume,
  39419. duration: duration,
  39420. durationMS: duration * 1000,
  39421. loop: loop
  39422. };
  39423. },
  39424. /**
  39425. * Removes a marker from the sound.
  39426. * @method Phaser.Sound#removeMarker
  39427. * @param {string} name - The key of the marker to remove.
  39428. */
  39429. removeMarker: function (name) {
  39430. delete this.markers[name];
  39431. },
  39432. /**
  39433. * Called automatically by Phaser.SoundManager.
  39434. * @method Phaser.Sound#update
  39435. * @protected
  39436. */
  39437. update: function () {
  39438. if (this.isDecoded && !this._onDecodedEventDispatched) {
  39439. this.onDecoded.dispatch(this);
  39440. this._onDecodedEventDispatched=true;
  39441. }
  39442. if (this.pendingPlayback && this.game.cache.isSoundReady(this.key))
  39443. {
  39444. this.pendingPlayback = false;
  39445. this.play(this._tempMarker, this._tempPosition, this._tempVolume, this._tempLoop);
  39446. }
  39447. if (this.isPlaying)
  39448. {
  39449. this.currentTime = this.game.time.now - this.startTime;
  39450. if (this.currentTime >= this.durationMS)
  39451. {
  39452. if (this.usingWebAudio)
  39453. {
  39454. if (this.loop)
  39455. {
  39456. // won't work with markers, needs to reset the position
  39457. this.onLoop.dispatch(this);
  39458. if (this.currentMarker === '')
  39459. {
  39460. this.currentTime = 0;
  39461. this.startTime = this.game.time.now;
  39462. }
  39463. else
  39464. {
  39465. this.onMarkerComplete.dispatch(this.currentMarker, this);
  39466. this.play(this.currentMarker, 0, this.volume, true, true);
  39467. }
  39468. }
  39469. else
  39470. {
  39471. this.stop();
  39472. }
  39473. }
  39474. else
  39475. {
  39476. if (this.loop)
  39477. {
  39478. this.onLoop.dispatch(this);
  39479. this.play(this.currentMarker, 0, this.volume, true, true);
  39480. }
  39481. else
  39482. {
  39483. this.stop();
  39484. }
  39485. }
  39486. }
  39487. }
  39488. },
  39489. /**
  39490. * Play this sound, or a marked section of it.
  39491. * @method Phaser.Sound#play
  39492. * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound.
  39493. * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker.
  39494. * @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).
  39495. * @param {boolean} [loop=false] - Loop when it finished playing?
  39496. * @param {boolean} [forceRestart=true] - If the sound is already playing you can set forceRestart to restart it from the beginning.
  39497. * @return {Phaser.Sound} This sound instance.
  39498. */
  39499. play: function (marker, position, volume, loop, forceRestart) {
  39500. if (typeof marker === 'undefined') { marker = ''; }
  39501. if (typeof forceRestart === 'undefined') { forceRestart = true; }
  39502. if (this.isPlaying === true && forceRestart === false && this.override === false)
  39503. {
  39504. // Use Restart instead
  39505. return this;
  39506. }
  39507. if (this.isPlaying && this.override)
  39508. {
  39509. if (this.usingWebAudio)
  39510. {
  39511. if (typeof this._sound.stop === 'undefined')
  39512. {
  39513. this._sound.noteOff(0);
  39514. }
  39515. else
  39516. {
  39517. this._sound.stop(0);
  39518. }
  39519. }
  39520. else if (this.usingAudioTag)
  39521. {
  39522. this._sound.pause();
  39523. this._sound.currentTime = 0;
  39524. }
  39525. }
  39526. this.currentMarker = marker;
  39527. if (marker !== '')
  39528. {
  39529. if (this.markers[marker])
  39530. {
  39531. // Playing a marker? Then we default to the marker values
  39532. this.position = this.markers[marker].start;
  39533. this.volume = this.markers[marker].volume;
  39534. this.loop = this.markers[marker].loop;
  39535. this.duration = this.markers[marker].duration;
  39536. this.durationMS = this.markers[marker].durationMS;
  39537. if (typeof volume !== 'undefined')
  39538. {
  39539. this.volume = volume;
  39540. }
  39541. if (typeof loop !== 'undefined')
  39542. {
  39543. this.loop = loop;
  39544. }
  39545. this._tempMarker = marker;
  39546. this._tempPosition = this.position;
  39547. this._tempVolume = this.volume;
  39548. this._tempLoop = this.loop;
  39549. }
  39550. else
  39551. {
  39552. console.warn("Phaser.Sound.play: audio marker " + marker + " doesn't exist");
  39553. return this;
  39554. }
  39555. }
  39556. else
  39557. {
  39558. position = position || 0;
  39559. if (typeof volume === 'undefined') { volume = this._volume; }
  39560. if (typeof loop === 'undefined') { loop = this.loop; }
  39561. this.position = position;
  39562. this.volume = volume;
  39563. this.loop = loop;
  39564. this.duration = 0;
  39565. this.durationMS = 0;
  39566. this._tempMarker = marker;
  39567. this._tempPosition = position;
  39568. this._tempVolume = volume;
  39569. this._tempLoop = loop;
  39570. }
  39571. if (this.usingWebAudio)
  39572. {
  39573. // Does the sound need decoding?
  39574. if (this.game.cache.isSoundDecoded(this.key))
  39575. {
  39576. // Do we need to do this every time we play? How about just if the buffer is empty?
  39577. if (this._buffer == null)
  39578. {
  39579. this._buffer = this.game.cache.getSoundData(this.key);
  39580. }
  39581. this._sound = this.context.createBufferSource();
  39582. this._sound.buffer = this._buffer;
  39583. if (this.externalNode)
  39584. {
  39585. this._sound.connect(this.externalNode);
  39586. }
  39587. else
  39588. {
  39589. this._sound.connect(this.gainNode);
  39590. }
  39591. this.totalDuration = this._sound.buffer.duration;
  39592. if (this.duration === 0)
  39593. {
  39594. // console.log('duration reset');
  39595. this.duration = this.totalDuration;
  39596. this.durationMS = this.totalDuration * 1000;
  39597. }
  39598. if (this.loop && marker === '')
  39599. {
  39600. this._sound.loop = true;
  39601. }
  39602. // Useful to cache this somewhere perhaps?
  39603. if (typeof this._sound.start === 'undefined')
  39604. {
  39605. this._sound.noteGrainOn(0, this.position, this.duration);
  39606. // this._sound.noteGrainOn(0, this.position, this.duration / 1000);
  39607. //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it
  39608. }
  39609. else
  39610. {
  39611. // this._sound.start(0, this.position, this.duration / 1000);
  39612. this._sound.start(0, this.position, this.duration);
  39613. }
  39614. this.isPlaying = true;
  39615. this.startTime = this.game.time.now;
  39616. this.currentTime = 0;
  39617. this.stopTime = this.startTime + this.durationMS;
  39618. this.onPlay.dispatch(this);
  39619. }
  39620. else
  39621. {
  39622. this.pendingPlayback = true;
  39623. if (this.game.cache.getSound(this.key) && this.game.cache.getSound(this.key).isDecoding === false)
  39624. {
  39625. this.game.sound.decode(this.key, this);
  39626. }
  39627. }
  39628. }
  39629. else
  39630. {
  39631. if (this.game.cache.getSound(this.key) && this.game.cache.getSound(this.key).locked)
  39632. {
  39633. this.game.cache.reloadSound(this.key);
  39634. this.pendingPlayback = true;
  39635. }
  39636. else
  39637. {
  39638. if (this._sound && (this.game.device.cocoonJS || this._sound.readyState === 4))
  39639. {
  39640. this._sound.play();
  39641. // This doesn't become available until you call play(), wonderful ...
  39642. this.totalDuration = this._sound.duration;
  39643. if (this.duration === 0)
  39644. {
  39645. this.duration = this.totalDuration;
  39646. this.durationMS = this.totalDuration * 1000;
  39647. }
  39648. this._sound.currentTime = this.position;
  39649. this._sound.muted = this._muted;
  39650. if (this._muted)
  39651. {
  39652. this._sound.volume = 0;
  39653. }
  39654. else
  39655. {
  39656. this._sound.volume = this._volume;
  39657. }
  39658. this.isPlaying = true;
  39659. this.startTime = this.game.time.now;
  39660. this.currentTime = 0;
  39661. this.stopTime = this.startTime + this.durationMS;
  39662. this.onPlay.dispatch(this);
  39663. }
  39664. else
  39665. {
  39666. this.pendingPlayback = true;
  39667. }
  39668. }
  39669. }
  39670. return this;
  39671. },
  39672. /**
  39673. * Restart the sound, or a marked section of it.
  39674. *
  39675. * @method Phaser.Sound#restart
  39676. * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound.
  39677. * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker.
  39678. * @param {number} [volume=1] - Volume of the sound you want to play.
  39679. * @param {boolean} [loop=false] - Loop when it finished playing?
  39680. */
  39681. restart: function (marker, position, volume, loop) {
  39682. marker = marker || '';
  39683. position = position || 0;
  39684. volume = volume || 1;
  39685. if (typeof loop == 'undefined') { loop = false; }
  39686. this.play(marker, position, volume, loop, true);
  39687. },
  39688. /**
  39689. * Pauses the sound.
  39690. *
  39691. * @method Phaser.Sound#pause
  39692. */
  39693. pause: function () {
  39694. if (this.isPlaying && this._sound)
  39695. {
  39696. this.paused = true;
  39697. this.pausedPosition = this.currentTime;
  39698. this.pausedTime = this.game.time.now;
  39699. this.onPause.dispatch(this);
  39700. this.stop();
  39701. }
  39702. },
  39703. /**
  39704. * Resumes the sound.
  39705. *
  39706. * @method Phaser.Sound#resume
  39707. */
  39708. resume: function () {
  39709. if (this.paused && this._sound)
  39710. {
  39711. if (this.usingWebAudio)
  39712. {
  39713. var p = this.position + (this.pausedPosition / 1000);
  39714. this._sound = this.context.createBufferSource();
  39715. this._sound.buffer = this._buffer;
  39716. if (this.externalNode)
  39717. {
  39718. this._sound.connect(this.externalNode);
  39719. }
  39720. else
  39721. {
  39722. this._sound.connect(this.gainNode);
  39723. }
  39724. if (this.loop)
  39725. {
  39726. this._sound.loop = true;
  39727. }
  39728. if (typeof this._sound.start === 'undefined')
  39729. {
  39730. this._sound.noteGrainOn(0, p, this.duration);
  39731. //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it
  39732. }
  39733. else
  39734. {
  39735. this._sound.start(0, p, this.duration);
  39736. }
  39737. }
  39738. else
  39739. {
  39740. this._sound.play();
  39741. }
  39742. this.isPlaying = true;
  39743. this.paused = false;
  39744. this.startTime += (this.game.time.now - this.pausedTime);
  39745. this.onResume.dispatch(this);
  39746. }
  39747. },
  39748. /**
  39749. * Stop playing this sound.
  39750. *
  39751. * @method Phaser.Sound#stop
  39752. */
  39753. stop: function () {
  39754. if (this.isPlaying && this._sound)
  39755. {
  39756. if (this.usingWebAudio)
  39757. {
  39758. if (typeof this._sound.stop === 'undefined')
  39759. {
  39760. this._sound.noteOff(0);
  39761. }
  39762. else
  39763. {
  39764. try {
  39765. this._sound.stop(0);
  39766. }
  39767. catch (e)
  39768. {
  39769. // Thanks Android 4.4
  39770. }
  39771. }
  39772. }
  39773. else if (this.usingAudioTag)
  39774. {
  39775. this._sound.pause();
  39776. this._sound.currentTime = 0;
  39777. }
  39778. }
  39779. this.isPlaying = false;
  39780. var prevMarker = this.currentMarker;
  39781. if (this.currentMarker !== '')
  39782. {
  39783. this.onMarkerComplete.dispatch(this.currentMarker, this);
  39784. }
  39785. this.currentMarker = '';
  39786. if (!this.paused)
  39787. {
  39788. this.onStop.dispatch(this, prevMarker);
  39789. }
  39790. },
  39791. /**
  39792. * Destroys this sound and all associated events and removes it from the SoundManager.
  39793. *
  39794. * @method Phaser.Sound#destroy
  39795. * @param {boolean} [remove=true] - If true this Sound is automatically removed from the SoundManager.
  39796. */
  39797. destroy: function (remove) {
  39798. if (typeof remove === 'undefined') { remove = true; }
  39799. this.stop();
  39800. if (remove)
  39801. {
  39802. this.game.sound.remove(this);
  39803. }
  39804. else
  39805. {
  39806. this.markers = {};
  39807. this.context = null;
  39808. this._buffer = null;
  39809. this.externalNode = null;
  39810. this.onDecoded.dispose();
  39811. this.onPlay.dispose();
  39812. this.onPause.dispose();
  39813. this.onResume.dispose();
  39814. this.onLoop.dispose();
  39815. this.onStop.dispose();
  39816. this.onMute.dispose();
  39817. this.onMarkerComplete.dispose();
  39818. }
  39819. }
  39820. };
  39821. Phaser.Sound.prototype.constructor = Phaser.Sound;
  39822. /**
  39823. * @name Phaser.Sound#isDecoding
  39824. * @property {boolean} isDecoding - Returns true if the sound file is still decoding.
  39825. * @readonly
  39826. */
  39827. Object.defineProperty(Phaser.Sound.prototype, "isDecoding", {
  39828. get: function () {
  39829. return this.game.cache.getSound(this.key).isDecoding;
  39830. }
  39831. });
  39832. /**
  39833. * @name Phaser.Sound#isDecoded
  39834. * @property {boolean} isDecoded - Returns true if the sound file has decoded.
  39835. * @readonly
  39836. */
  39837. Object.defineProperty(Phaser.Sound.prototype, "isDecoded", {
  39838. get: function () {
  39839. return this.game.cache.isSoundDecoded(this.key);
  39840. }
  39841. });
  39842. /**
  39843. * @name Phaser.Sound#mute
  39844. * @property {boolean} mute - Gets or sets the muted state of this sound.
  39845. */
  39846. Object.defineProperty(Phaser.Sound.prototype, "mute", {
  39847. get: function () {
  39848. return (this._muted || this.game.sound.mute);
  39849. },
  39850. set: function (value) {
  39851. value = value || null;
  39852. if (value)
  39853. {
  39854. this._muted = true;
  39855. if (this.usingWebAudio)
  39856. {
  39857. this._muteVolume = this.gainNode.gain.value;
  39858. this.gainNode.gain.value = 0;
  39859. }
  39860. else if (this.usingAudioTag && this._sound)
  39861. {
  39862. this._muteVolume = this._sound.volume;
  39863. this._sound.volume = 0;
  39864. }
  39865. }
  39866. else
  39867. {
  39868. this._muted = false;
  39869. if (this.usingWebAudio)
  39870. {
  39871. this.gainNode.gain.value = this._muteVolume;
  39872. }
  39873. else if (this.usingAudioTag && this._sound)
  39874. {
  39875. this._sound.volume = this._muteVolume;
  39876. }
  39877. }
  39878. this.onMute.dispatch(this);
  39879. }
  39880. });
  39881. /**
  39882. * @name Phaser.Sound#volume
  39883. * @property {number} volume - Gets or sets the volume of this sound, a value between 0 and 1.
  39884. * @readonly
  39885. */
  39886. Object.defineProperty(Phaser.Sound.prototype, "volume", {
  39887. get: function () {
  39888. return this._volume;
  39889. },
  39890. set: function (value) {
  39891. if (this.usingWebAudio)
  39892. {
  39893. this._volume = value;
  39894. this.gainNode.gain.value = value;
  39895. }
  39896. else if (this.usingAudioTag && this._sound)
  39897. {
  39898. // Causes an Index size error in Firefox if you don't clamp the value
  39899. if (value >= 0 && value <= 1)
  39900. {
  39901. this._volume = value;
  39902. this._sound.volume = value;
  39903. }
  39904. }
  39905. }
  39906. });
  39907. /**
  39908. * @author Richard Davey <rich@photonstorm.com>
  39909. * @copyright 2014 Photon Storm Ltd.
  39910. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  39911. */
  39912. /**
  39913. * Sound Manager constructor.
  39914. * 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.
  39915. * Note: On Firefox 25+ on Linux if you have media.gstreamer disabled in about:config then it cannot play back mp3 or m4a files.
  39916. * The audio file type and the encoding of those files are extremely important. Not all browsers can play all audio formats.
  39917. * There is a good guide to what's supported here: http://hpr.dogphilosophy.net/test/
  39918. *
  39919. * @class Phaser.SoundManager
  39920. * @classdesc Phaser Sound Manager.
  39921. * @constructor
  39922. * @param {Phaser.Game} game reference to the current game instance.
  39923. */
  39924. Phaser.SoundManager = function (game) {
  39925. /**
  39926. * @property {Phaser.Game} game - Local reference to game.
  39927. */
  39928. this.game = game;
  39929. /**
  39930. * @property {Phaser.Signal} onSoundDecode - The event dispatched when a sound decodes (typically only for mp3 files)
  39931. */
  39932. this.onSoundDecode = new Phaser.Signal();
  39933. /**
  39934. * @property {boolean} _codeMuted - Internal mute tracking var.
  39935. * @private
  39936. * @default
  39937. */
  39938. this._codeMuted = false;
  39939. /**
  39940. * @property {boolean} _muted - Internal mute tracking var.
  39941. * @private
  39942. * @default
  39943. */
  39944. this._muted = false;
  39945. /**
  39946. * @property {Description} _unlockSource - Internal unlock tracking var.
  39947. * @private
  39948. * @default
  39949. */
  39950. this._unlockSource = null;
  39951. /**
  39952. * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume).
  39953. * @private
  39954. * @default
  39955. */
  39956. this._volume = 1;
  39957. /**
  39958. * @property {array} _sounds - An array containing all the sounds
  39959. * @private
  39960. */
  39961. this._sounds = [];
  39962. /**
  39963. * @property {AudioContext} context - The AudioContext being used for playback.
  39964. * @default
  39965. */
  39966. this.context = null;
  39967. /**
  39968. * @property {boolean} usingWebAudio - true if this sound is being played with Web Audio.
  39969. * @readonly
  39970. */
  39971. this.usingWebAudio = true;
  39972. /**
  39973. * @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag.
  39974. * @readonly
  39975. */
  39976. this.usingAudioTag = false;
  39977. /**
  39978. * @property {boolean} noAudio - Has audio been disabled via the PhaserGlobal object? Useful if you need to use a 3rd party audio library instead.
  39979. * @default
  39980. */
  39981. this.noAudio = false;
  39982. /**
  39983. * @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.
  39984. * @default
  39985. */
  39986. this.connectToMaster = true;
  39987. /**
  39988. * @property {boolean} touchLocked - true if the audio system is currently locked awaiting a touch event.
  39989. * @default
  39990. */
  39991. this.touchLocked = false;
  39992. /**
  39993. * @property {number} channels - The number of audio channels to use in playback.
  39994. * @default
  39995. */
  39996. this.channels = 32;
  39997. };
  39998. Phaser.SoundManager.prototype = {
  39999. /**
  40000. * Initialises the sound manager.
  40001. * @method Phaser.SoundManager#boot
  40002. * @protected
  40003. */
  40004. boot: function () {
  40005. if (this.game.device.iOS && this.game.device.webAudio === false)
  40006. {
  40007. this.channels = 1;
  40008. }
  40009. if (!this.game.device.cocoonJS && this.game.device.iOS || (window['PhaserGlobal'] && window['PhaserGlobal'].fakeiOSTouchLock))
  40010. {
  40011. this.game.input.touch.callbackContext = this;
  40012. this.game.input.touch.touchStartCallback = this.unlock;
  40013. this.game.input.mouse.callbackContext = this;
  40014. this.game.input.mouse.mouseDownCallback = this.unlock;
  40015. this.touchLocked = true;
  40016. }
  40017. else
  40018. {
  40019. this.touchLocked = false;
  40020. }
  40021. if (window['PhaserGlobal'])
  40022. {
  40023. // Check to see if all audio playback is disabled (i.e. handled by a 3rd party class)
  40024. if (window['PhaserGlobal'].disableAudio === true)
  40025. {
  40026. this.usingWebAudio = false;
  40027. this.noAudio = true;
  40028. return;
  40029. }
  40030. // Check if the Web Audio API is disabled (for testing Audio Tag playback during development)
  40031. if (window['PhaserGlobal'].disableWebAudio === true)
  40032. {
  40033. this.usingWebAudio = false;
  40034. this.usingAudioTag = true;
  40035. this.noAudio = false;
  40036. return;
  40037. }
  40038. }
  40039. if (!!window['AudioContext'])
  40040. {
  40041. try {
  40042. this.context = new window['AudioContext']();
  40043. } catch (error) {
  40044. this.context = null;
  40045. this.usingWebAudio = false;
  40046. this.noAudio = true;
  40047. }
  40048. }
  40049. else if (!!window['webkitAudioContext'])
  40050. {
  40051. try {
  40052. this.context = new window['webkitAudioContext']();
  40053. } catch (error) {
  40054. this.context = null;
  40055. this.usingWebAudio = false;
  40056. this.noAudio = true;
  40057. }
  40058. }
  40059. if (!!window['Audio'] && this.context === null)
  40060. {
  40061. this.usingWebAudio = false;
  40062. this.usingAudioTag = true;
  40063. this.noAudio = false;
  40064. }
  40065. if (this.context !== null)
  40066. {
  40067. if (typeof this.context.createGain === 'undefined')
  40068. {
  40069. this.masterGain = this.context.createGainNode();
  40070. }
  40071. else
  40072. {
  40073. this.masterGain = this.context.createGain();
  40074. }
  40075. this.masterGain.gain.value = 1;
  40076. this.masterGain.connect(this.context.destination);
  40077. }
  40078. },
  40079. /**
  40080. * Enables the audio, usually after the first touch.
  40081. * @method Phaser.SoundManager#unlock
  40082. */
  40083. unlock: function () {
  40084. if (this.touchLocked === false)
  40085. {
  40086. return;
  40087. }
  40088. // Global override (mostly for Audio Tag testing)
  40089. if (this.game.device.webAudio === false || (window['PhaserGlobal'] && window['PhaserGlobal'].disableWebAudio === true))
  40090. {
  40091. // Create an Audio tag?
  40092. this.touchLocked = false;
  40093. this._unlockSource = null;
  40094. this.game.input.touch.callbackContext = null;
  40095. this.game.input.touch.touchStartCallback = null;
  40096. this.game.input.mouse.callbackContext = null;
  40097. this.game.input.mouse.mouseDownCallback = null;
  40098. }
  40099. else
  40100. {
  40101. // Create empty buffer and play it
  40102. var buffer = this.context.createBuffer(1, 1, 22050);
  40103. this._unlockSource = this.context.createBufferSource();
  40104. this._unlockSource.buffer = buffer;
  40105. this._unlockSource.connect(this.context.destination);
  40106. //this._unlockSource.noteOn(0);
  40107. }
  40108. },
  40109. /**
  40110. * Stops all the sounds in the game.
  40111. *
  40112. * @method Phaser.SoundManager#stopAll
  40113. */
  40114. stopAll: function () {
  40115. for (var i = 0; i < this._sounds.length; i++)
  40116. {
  40117. if (this._sounds[i])
  40118. {
  40119. this._sounds[i].stop();
  40120. }
  40121. }
  40122. },
  40123. /**
  40124. * Pauses all the sounds in the game.
  40125. *
  40126. * @method Phaser.SoundManager#pauseAll
  40127. */
  40128. pauseAll: function () {
  40129. for (var i = 0; i < this._sounds.length; i++)
  40130. {
  40131. if (this._sounds[i])
  40132. {
  40133. this._sounds[i].pause();
  40134. }
  40135. }
  40136. },
  40137. /**
  40138. * Resumes every sound in the game.
  40139. *
  40140. * @method Phaser.SoundManager#resumeAll
  40141. */
  40142. resumeAll: function () {
  40143. for (var i = 0; i < this._sounds.length; i++)
  40144. {
  40145. if (this._sounds[i])
  40146. {
  40147. this._sounds[i].resume();
  40148. }
  40149. }
  40150. },
  40151. /**
  40152. * Decode a sound by its assets key.
  40153. *
  40154. * @method Phaser.SoundManager#decode
  40155. * @param {string} key - Assets key of the sound to be decoded.
  40156. * @param {Phaser.Sound} [sound] - Its buffer will be set to decoded data.
  40157. */
  40158. decode: function (key, sound) {
  40159. sound = sound || null;
  40160. var soundData = this.game.cache.getSoundData(key);
  40161. if (soundData)
  40162. {
  40163. if (this.game.cache.isSoundDecoded(key) === false)
  40164. {
  40165. this.game.cache.updateSound(key, 'isDecoding', true);
  40166. var that = this;
  40167. this.context.decodeAudioData(soundData, function (buffer) {
  40168. that.game.cache.decodedSound(key, buffer);
  40169. if (sound)
  40170. {
  40171. that.onSoundDecode.dispatch(key, sound);
  40172. }
  40173. });
  40174. }
  40175. }
  40176. },
  40177. /**
  40178. * Updates every sound in the game.
  40179. *
  40180. * @method Phaser.SoundManager#update
  40181. */
  40182. update: function () {
  40183. if (this.touchLocked)
  40184. {
  40185. if (this.game.device.webAudio && this._unlockSource !== null)
  40186. {
  40187. if ((this._unlockSource.playbackState === this._unlockSource.PLAYING_STATE || this._unlockSource.playbackState === this._unlockSource.FINISHED_STATE))
  40188. {
  40189. this.touchLocked = false;
  40190. this._unlockSource = null;
  40191. this.game.input.touch.callbackContext = null;
  40192. this.game.input.touch.touchStartCallback = null;
  40193. }
  40194. }
  40195. }
  40196. for (var i = 0; i < this._sounds.length; i++)
  40197. {
  40198. this._sounds[i].update();
  40199. }
  40200. },
  40201. /**
  40202. * Adds a new Sound into the SoundManager.
  40203. *
  40204. * @method Phaser.SoundManager#add
  40205. * @param {string} key - Asset key for the sound.
  40206. * @param {number} [volume=1] - Default value for the volume.
  40207. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  40208. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  40209. * @return {Phaser.Sound} The new sound instance.
  40210. */
  40211. add: function (key, volume, loop, connect) {
  40212. if (typeof volume === 'undefined') { volume = 1; }
  40213. if (typeof loop === 'undefined') { loop = false; }
  40214. if (typeof connect === 'undefined') { connect = this.connectToMaster; }
  40215. var sound = new Phaser.Sound(this.game, key, volume, loop, connect);
  40216. this._sounds.push(sound);
  40217. return sound;
  40218. },
  40219. /**
  40220. * Removes a Sound from the SoundManager. The removed Sound is destroyed before removal.
  40221. *
  40222. * @method Phaser.SoundManager#remove
  40223. * @param {Phaser.Sound} sound - The sound object to remove.
  40224. * @return {boolean} True if the sound was removed successfully, otherwise false.
  40225. */
  40226. remove: function (sound) {
  40227. var i = this._sounds.length;
  40228. while (i--)
  40229. {
  40230. if (this._sounds[i] === sound)
  40231. {
  40232. this._sounds[i].destroy(false);
  40233. this._sounds.splice(i, 1);
  40234. return true;
  40235. }
  40236. }
  40237. return false;
  40238. },
  40239. /**
  40240. * Removes all Sounds from the SoundManager that have an asset key matching the given value.
  40241. * The removed Sounds are destroyed before removal.
  40242. *
  40243. * @method Phaser.SoundManager#removeByKey
  40244. * @param {string} key - The key to match when removing sound objects.
  40245. * @return {number} The number of matching sound objects that were removed.
  40246. */
  40247. removeByKey: function (key) {
  40248. var i = this._sounds.length;
  40249. var removed = 0;
  40250. while (i--)
  40251. {
  40252. if (this._sounds[i].key === key)
  40253. {
  40254. this._sounds[i].destroy(false);
  40255. this._sounds.splice(i, 1);
  40256. removed++;
  40257. }
  40258. }
  40259. return removed;
  40260. },
  40261. /**
  40262. * Adds a new Sound into the SoundManager and starts it playing.
  40263. *
  40264. * @method Phaser.SoundManager#play
  40265. * @param {string} key - Asset key for the sound.
  40266. * @param {number} [volume=1] - Default value for the volume.
  40267. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  40268. * @return {Phaser.Sound} The new sound instance.
  40269. */
  40270. play: function (key, volume, loop) {
  40271. var sound = this.add(key, volume, loop);
  40272. sound.play();
  40273. return sound;
  40274. },
  40275. /**
  40276. * Internal mute handler called automatically by the Sound.mute setter.
  40277. *
  40278. * @method Phaser.SoundManager#setMute
  40279. * @private
  40280. */
  40281. setMute: function () {
  40282. if (this._muted)
  40283. {
  40284. return;
  40285. }
  40286. this._muted = true;
  40287. if (this.usingWebAudio)
  40288. {
  40289. this._muteVolume = this.masterGain.gain.value;
  40290. this.masterGain.gain.value = 0;
  40291. }
  40292. // Loop through sounds
  40293. for (var i = 0; i < this._sounds.length; i++)
  40294. {
  40295. if (this._sounds[i].usingAudioTag)
  40296. {
  40297. this._sounds[i].mute = true;
  40298. }
  40299. }
  40300. },
  40301. /**
  40302. * Internal mute handler called automatically by the Sound.mute setter.
  40303. *
  40304. * @method Phaser.SoundManager#unsetMute
  40305. * @private
  40306. */
  40307. unsetMute: function () {
  40308. if (!this._muted || this._codeMuted)
  40309. {
  40310. return;
  40311. }
  40312. this._muted = false;
  40313. if (this.usingWebAudio)
  40314. {
  40315. this.masterGain.gain.value = this._muteVolume;
  40316. }
  40317. // Loop through sounds
  40318. for (var i = 0; i < this._sounds.length; i++)
  40319. {
  40320. if (this._sounds[i].usingAudioTag)
  40321. {
  40322. this._sounds[i].mute = false;
  40323. }
  40324. }
  40325. }
  40326. };
  40327. Phaser.SoundManager.prototype.constructor = Phaser.SoundManager;
  40328. /**
  40329. * @name Phaser.SoundManager#mute
  40330. * @property {boolean} mute - Gets or sets the muted state of the SoundManager. This effects all sounds in the game.
  40331. */
  40332. Object.defineProperty(Phaser.SoundManager.prototype, "mute", {
  40333. get: function () {
  40334. return this._muted;
  40335. },
  40336. set: function (value) {
  40337. value = value || null;
  40338. if (value)
  40339. {
  40340. if (this._muted)
  40341. {
  40342. return;
  40343. }
  40344. this._codeMuted = true;
  40345. this.setMute();
  40346. }
  40347. else
  40348. {
  40349. if (!this._muted)
  40350. {
  40351. return;
  40352. }
  40353. this._codeMuted = false;
  40354. this.unsetMute();
  40355. }
  40356. }
  40357. });
  40358. /**
  40359. * @name Phaser.SoundManager#volume
  40360. * @property {number} volume - Gets or sets the global volume of the SoundManager, a value between 0 and 1.
  40361. */
  40362. Object.defineProperty(Phaser.SoundManager.prototype, "volume", {
  40363. get: function () {
  40364. if (this.usingWebAudio)
  40365. {
  40366. return this.masterGain.gain.value;
  40367. }
  40368. else
  40369. {
  40370. return this._volume;
  40371. }
  40372. },
  40373. set: function (value) {
  40374. this._volume = value;
  40375. if (this.usingWebAudio)
  40376. {
  40377. this.masterGain.gain.value = value;
  40378. }
  40379. else
  40380. {
  40381. // Loop through the sound cache and change the volume of all html audio tags
  40382. for (var i = 0; i < this._sounds.length; i++)
  40383. {
  40384. if (this._sounds[i].usingAudioTag)
  40385. {
  40386. this._sounds[i].volume = this._sounds[i].volume * value;
  40387. }
  40388. }
  40389. }
  40390. }
  40391. });
  40392. /**
  40393. * @author Richard Davey <rich@photonstorm.com>
  40394. * @copyright 2014 Photon Storm Ltd.
  40395. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  40396. */
  40397. /**
  40398. * A collection of methods for displaying debug information about game objects.
  40399. * 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
  40400. * to it, which must be uploaded every frame. Be advised: this is expenive.
  40401. * If your game is using a Canvas renderer then the debug information is literally drawn on the top of the active game canvas and no Sprite is used.
  40402. *
  40403. * @class Phaser.Utils.Debug
  40404. * @constructor
  40405. * @param {Phaser.Game} game - A reference to the currently running game.
  40406. */
  40407. Phaser.Utils.Debug = function (game) {
  40408. /**
  40409. * @property {Phaser.Game} game - A reference to the currently running Game.
  40410. */
  40411. this.game = game;
  40412. /**
  40413. * @property {PIXI.Sprite} sprite - If debugging in WebGL mode we need this.
  40414. */
  40415. this.sprite = null;
  40416. /**
  40417. * @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws.
  40418. */
  40419. this.canvas = null;
  40420. /**
  40421. * @property {PIXI.BaseTexture} baseTexture - Required Pixi var.
  40422. */
  40423. this.baseTexture = null;
  40424. /**
  40425. * @property {PIXI.Texture} texture - Required Pixi var.
  40426. */
  40427. this.texture = null;
  40428. /**
  40429. * @property {Phaser.Frame} textureFrame - Dimensions of the renderable area.
  40430. */
  40431. this.textureFrame = null;
  40432. /**
  40433. * @property {CanvasRenderingContext2D} context - The 2d context of the canvas.
  40434. */
  40435. this.context = null;
  40436. /**
  40437. * @property {string} font - The font that the debug information is rendered in.
  40438. * @default '14px Courier'
  40439. */
  40440. this.font = '14px Courier';
  40441. /**
  40442. * @property {number} columnWidth - The spacing between columns.
  40443. */
  40444. this.columnWidth = 100;
  40445. /**
  40446. * @property {number} lineHeight - The line height between the debug text.
  40447. */
  40448. this.lineHeight = 16;
  40449. /**
  40450. * @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background.
  40451. */
  40452. this.renderShadow = true;
  40453. /**
  40454. * @property {Context} currentX - The current X position the debug information will be rendered at.
  40455. * @default
  40456. */
  40457. this.currentX = 0;
  40458. /**
  40459. * @property {number} currentY - The current Y position the debug information will be rendered at.
  40460. * @default
  40461. */
  40462. this.currentY = 0;
  40463. /**
  40464. * @property {number} currentAlpha - The current alpha the debug information will be rendered at.
  40465. * @default
  40466. */
  40467. this.currentAlpha = 1;
  40468. /**
  40469. * @property {boolean} dirty - Does the canvas need re-rendering?
  40470. */
  40471. this.dirty = false;
  40472. };
  40473. Phaser.Utils.Debug.prototype = {
  40474. /**
  40475. * Internal method that boots the debug displayer.
  40476. *
  40477. * @method Phaser.Utils.Debug#boot
  40478. * @protected
  40479. */
  40480. boot: function () {
  40481. if (this.game.renderType === Phaser.CANVAS)
  40482. {
  40483. this.context = this.game.context;
  40484. }
  40485. else
  40486. {
  40487. this.canvas = Phaser.Canvas.create(this.game.width, this.game.height, '', true);
  40488. this.context = this.canvas.getContext('2d');
  40489. this.baseTexture = new PIXI.BaseTexture(this.canvas);
  40490. this.texture = new PIXI.Texture(this.baseTexture);
  40491. this.textureFrame = new Phaser.Frame(0, 0, 0, this.game.width, this.game.height, 'debug', this.game.rnd.uuid());
  40492. this.sprite = this.game.make.image(0, 0, this.texture, this.textureFrame);
  40493. this.game.stage.addChild(this.sprite);
  40494. }
  40495. },
  40496. /**
  40497. * Internal method that clears the canvas (if a Sprite) ready for a new debug session.
  40498. *
  40499. * @method Phaser.Utils.Debug#preUpdate
  40500. */
  40501. preUpdate: function () {
  40502. if (this.dirty && this.sprite)
  40503. {
  40504. this.context.clearRect(0, 0, this.game.width, this.game.height);
  40505. this.dirty = false;
  40506. }
  40507. },
  40508. /**
  40509. * Internal method that resets and starts the debug output values.
  40510. *
  40511. * @method Phaser.Utils.Debug#start
  40512. * @protected
  40513. * @param {number} [x=0] - The X value the debug info will start from.
  40514. * @param {number} [y=0] - The Y value the debug info will start from.
  40515. * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in.
  40516. * @param {number} [columnWidth=0] - The spacing between columns.
  40517. */
  40518. start: function (x, y, color, columnWidth) {
  40519. if (typeof x !== 'number') { x = 0; }
  40520. if (typeof y !== 'number') { y = 0; }
  40521. color = color || 'rgb(255,255,255)';
  40522. if (typeof columnWidth === 'undefined') { columnWidth = 0; }
  40523. this.currentX = x;
  40524. this.currentY = y;
  40525. this.currentColor = color;
  40526. this.currentAlpha = this.context.globalAlpha;
  40527. this.columnWidth = columnWidth;
  40528. if (this.sprite)
  40529. {
  40530. this.dirty = true;
  40531. }
  40532. this.context.save();
  40533. this.context.setTransform(1, 0, 0, 1, 0, 0);
  40534. this.context.strokeStyle = color;
  40535. this.context.fillStyle = color;
  40536. this.context.font = this.font;
  40537. this.context.globalAlpha = 1;
  40538. },
  40539. /**
  40540. * Internal method that stops the debug output.
  40541. *
  40542. * @method Phaser.Utils.Debug#stop
  40543. * @protected
  40544. */
  40545. stop: function () {
  40546. this.context.restore();
  40547. this.context.globalAlpha = this.currentAlpha;
  40548. if (this.sprite)
  40549. {
  40550. PIXI.updateWebGLTexture(this.baseTexture, this.game.renderer.gl);
  40551. }
  40552. },
  40553. /**
  40554. * Internal method that outputs a single line of text split over as many columns as needed, one per parameter.
  40555. *
  40556. * @method Phaser.Utils.Debug#line
  40557. * @protected
  40558. */
  40559. line: function () {
  40560. var x = this.currentX;
  40561. for (var i = 0; i < arguments.length; i++)
  40562. {
  40563. if (this.renderShadow)
  40564. {
  40565. this.context.fillStyle = 'rgb(0,0,0)';
  40566. this.context.fillText(arguments[i], x + 1, this.currentY + 1);
  40567. this.context.fillStyle = this.currentColor;
  40568. }
  40569. this.context.fillText(arguments[i], x, this.currentY);
  40570. x += this.columnWidth;
  40571. }
  40572. this.currentY += this.lineHeight;
  40573. },
  40574. /**
  40575. * Render Sound information, including decoded state, duration, volume and more.
  40576. *
  40577. * @method Phaser.Utils.Debug#soundInfo
  40578. * @param {Phaser.Sound} sound - The sound object to debug.
  40579. * @param {number} x - X position of the debug info to be rendered.
  40580. * @param {number} y - Y position of the debug info to be rendered.
  40581. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  40582. */
  40583. soundInfo: function (sound, x, y, color) {
  40584. this.start(x, y, color);
  40585. this.line('Sound: ' + sound.key + ' Locked: ' + sound.game.sound.touchLocked);
  40586. this.line('Is Ready?: ' + this.game.cache.isSoundReady(sound.key) + ' Pending Playback: ' + sound.pendingPlayback);
  40587. this.line('Decoded: ' + sound.isDecoded + ' Decoding: ' + sound.isDecoding);
  40588. this.line('Total Duration: ' + sound.totalDuration + ' Playing: ' + sound.isPlaying);
  40589. this.line('Time: ' + sound.currentTime);
  40590. this.line('Volume: ' + sound.volume + ' Muted: ' + sound.mute);
  40591. this.line('WebAudio: ' + sound.usingWebAudio + ' Audio: ' + sound.usingAudioTag);
  40592. if (sound.currentMarker !== '')
  40593. {
  40594. this.line('Marker: ' + sound.currentMarker + ' Duration: ' + sound.duration + ' (ms: ' + sound.durationMS + ')');
  40595. this.line('Start: ' + sound.markers[sound.currentMarker].start + ' Stop: ' + sound.markers[sound.currentMarker].stop);
  40596. this.line('Position: ' + sound.position);
  40597. }
  40598. this.stop();
  40599. },
  40600. /**
  40601. * Render camera information including dimensions and location.
  40602. *
  40603. * @method Phaser.Utils.Debug#cameraInfo
  40604. * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for.
  40605. * @param {number} x - X position of the debug info to be rendered.
  40606. * @param {number} y - Y position of the debug info to be rendered.
  40607. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  40608. */
  40609. cameraInfo: function (camera, x, y, color) {
  40610. this.start(x, y, color);
  40611. this.line('Camera (' + camera.width + ' x ' + camera.height + ')');
  40612. this.line('X: ' + camera.x + ' Y: ' + camera.y);
  40613. this.line('Bounds x: ' + camera.bounds.x + ' Y: ' + camera.bounds.y + ' w: ' + camera.bounds.width + ' h: ' + camera.bounds.height);
  40614. this.line('View x: ' + camera.view.x + ' Y: ' + camera.view.y + ' w: ' + camera.view.width + ' h: ' + camera.view.height);
  40615. this.stop();
  40616. },
  40617. /**
  40618. * Render Timer information.
  40619. *
  40620. * @method Phaser.Utils.Debug#timer
  40621. * @param {Phaser.Timer} timer - The Phaser.Timer to show the debug information for.
  40622. * @param {number} x - X position of the debug info to be rendered.
  40623. * @param {number} y - Y position of the debug info to be rendered.
  40624. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  40625. */
  40626. timer: function (timer, x, y, color) {
  40627. this.start(x, y, color);
  40628. this.line('Timer (running: ' + timer.running + ' expired: ' + timer.expired + ')');
  40629. this.line('Next Tick: ' + timer.next + ' Duration: ' + timer.duration);
  40630. this.line('Paused: ' + timer.paused + ' Length: ' + timer.length);
  40631. this.stop();
  40632. },
  40633. /**
  40634. * Renders the Pointer.circle object onto the stage in green if down or red if up along with debug text.
  40635. *
  40636. * @method Phaser.Utils.Debug#pointer
  40637. * @param {Phaser.Pointer} pointer - The Pointer you wish to display.
  40638. * @param {boolean} [hideIfUp=false] - Doesn't render the circle if the pointer is up.
  40639. * @param {string} [downColor='rgba(0,255,0,0.5)'] - The color the circle is rendered in if down.
  40640. * @param {string} [upColor='rgba(255,0,0,0.5)'] - The color the circle is rendered in if up (and hideIfUp is false).
  40641. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  40642. */
  40643. pointer: function (pointer, hideIfUp, downColor, upColor, color) {
  40644. if (pointer == null)
  40645. {
  40646. return;
  40647. }
  40648. if (typeof hideIfUp === 'undefined') { hideIfUp = false; }
  40649. downColor = downColor || 'rgba(0,255,0,0.5)';
  40650. upColor = upColor || 'rgba(255,0,0,0.5)';
  40651. if (hideIfUp === true && pointer.isUp === true)
  40652. {
  40653. return;
  40654. }
  40655. this.start(pointer.x, pointer.y - 100, color);
  40656. this.context.beginPath();
  40657. this.context.arc(pointer.x, pointer.y, pointer.circle.radius, 0, Math.PI * 2);
  40658. if (pointer.active)
  40659. {
  40660. this.context.fillStyle = downColor;
  40661. }
  40662. else
  40663. {
  40664. this.context.fillStyle = upColor;
  40665. }
  40666. this.context.fill();
  40667. this.context.closePath();
  40668. // Render the points
  40669. this.context.beginPath();
  40670. this.context.moveTo(pointer.positionDown.x, pointer.positionDown.y);
  40671. this.context.lineTo(pointer.position.x, pointer.position.y);
  40672. this.context.lineWidth = 2;
  40673. this.context.stroke();
  40674. this.context.closePath();
  40675. // Render the text
  40676. this.line('ID: ' + pointer.id + " Active: " + pointer.active);
  40677. this.line('World X: ' + pointer.worldX + " World Y: " + pointer.worldY);
  40678. this.line('Screen X: ' + pointer.x + " Screen Y: " + pointer.y);
  40679. this.line('Duration: ' + pointer.duration + " ms");
  40680. this.line('is Down: ' + pointer.isDown + " is Up: " + pointer.isUp);
  40681. this.stop();
  40682. },
  40683. /**
  40684. * Render Sprite Input Debug information.
  40685. *
  40686. * @method Phaser.Utils.Debug#spriteInputInfo
  40687. * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the input data for.
  40688. * @param {number} x - X position of the debug info to be rendered.
  40689. * @param {number} y - Y position of the debug info to be rendered.
  40690. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  40691. */
  40692. spriteInputInfo: function (sprite, x, y, color) {
  40693. this.start(x, y, color);
  40694. this.line('Sprite Input: (' + sprite.width + ' x ' + sprite.height + ')');
  40695. this.line('x: ' + sprite.input.pointerX().toFixed(1) + ' y: ' + sprite.input.pointerY().toFixed(1));
  40696. this.line('over: ' + sprite.input.pointerOver() + ' duration: ' + sprite.input.overDuration().toFixed(0));
  40697. this.line('down: ' + sprite.input.pointerDown() + ' duration: ' + sprite.input.downDuration().toFixed(0));
  40698. this.line('just over: ' + sprite.input.justOver() + ' just out: ' + sprite.input.justOut());
  40699. this.stop();
  40700. },
  40701. /**
  40702. * Renders Phaser.Key object information.
  40703. *
  40704. * @method Phaser.Utils.Debug#key
  40705. * @param {Phaser.Key} key - The Key to render the information for.
  40706. * @param {number} x - X position of the debug info to be rendered.
  40707. * @param {number} y - Y position of the debug info to be rendered.
  40708. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  40709. */
  40710. key: function (key, x, y, color) {
  40711. this.start(x, y, color, 150);
  40712. this.line('Key:', key.keyCode, 'isDown:', key.isDown);
  40713. this.line('justPressed:', key.justPressed(), 'justReleased:', key.justReleased());
  40714. this.line('Time Down:', key.timeDown.toFixed(0), 'duration:', key.duration.toFixed(0));
  40715. this.stop();
  40716. },
  40717. /**
  40718. * Render debug information about the Input object.
  40719. *
  40720. * @method Phaser.Utils.Debug#inputInfo
  40721. * @param {number} x - X position of the debug info to be rendered.
  40722. * @param {number} y - Y position of the debug info to be rendered.
  40723. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  40724. */
  40725. inputInfo: function (x, y, color) {
  40726. this.start(x, y, color);
  40727. this.line('Input');
  40728. this.line('X: ' + this.game.input.x + ' Y: ' + this.game.input.y);
  40729. this.line('World X: ' + this.game.input.worldX + ' World Y: ' + this.game.input.worldY);
  40730. this.line('Scale X: ' + this.game.input.scale.x.toFixed(1) + ' Scale Y: ' + this.game.input.scale.x.toFixed(1));
  40731. this.line('Screen X: ' + this.game.input.activePointer.screenX + ' Screen Y: ' + this.game.input.activePointer.screenY);
  40732. this.stop();
  40733. },
  40734. /**
  40735. * Renders the Sprites bounds. Note: This is really expensive as it has to calculate the bounds every time you call it!
  40736. *
  40737. * @method Phaser.Utils.Debug#spriteBounds
  40738. * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the bounds of.
  40739. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  40740. * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false)
  40741. */
  40742. spriteBounds: function (sprite, color, filled) {
  40743. var bounds = sprite.getBounds();
  40744. bounds.x += this.game.camera.x;
  40745. bounds.y += this.game.camera.y;
  40746. this.rectangle(bounds, color, filled);
  40747. },
  40748. /**
  40749. * Render debug infos (including name, bounds info, position and some other properties) about the Sprite.
  40750. *
  40751. * @method Phaser.Utils.Debug#spriteInfo
  40752. * @param {Phaser.Sprite} sprite - The Sprite to display the information of.
  40753. * @param {number} x - X position of the debug info to be rendered.
  40754. * @param {number} y - Y position of the debug info to be rendered.
  40755. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  40756. */
  40757. spriteInfo: function (sprite, x, y, color) {
  40758. this.start(x, y, color);
  40759. this.line('Sprite: ' + ' (' + sprite.width + ' x ' + sprite.height + ') anchor: ' + sprite.anchor.x + ' x ' + sprite.anchor.y);
  40760. this.line('x: ' + sprite.x.toFixed(1) + ' y: ' + sprite.y.toFixed(1));
  40761. this.line('angle: ' + sprite.angle.toFixed(1) + ' rotation: ' + sprite.rotation.toFixed(1));
  40762. this.line('visible: ' + sprite.visible + ' in camera: ' + sprite.inCamera);
  40763. this.stop();
  40764. },
  40765. /**
  40766. * Renders the sprite coordinates in local, positional and world space.
  40767. *
  40768. * @method Phaser.Utils.Debug#spriteCoords
  40769. * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the coordinates for.
  40770. * @param {number} x - X position of the debug info to be rendered.
  40771. * @param {number} y - Y position of the debug info to be rendered.
  40772. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  40773. */
  40774. spriteCoords: function (sprite, x, y, color) {
  40775. this.start(x, y, color, 100);
  40776. if (sprite.name)
  40777. {
  40778. this.line(sprite.name);
  40779. }
  40780. this.line('x:', sprite.x.toFixed(2), 'y:', sprite.y.toFixed(2));
  40781. this.line('pos x:', sprite.position.x.toFixed(2), 'pos y:', sprite.position.y.toFixed(2));
  40782. this.line('world x:', sprite.world.x.toFixed(2), 'world y:', sprite.world.y.toFixed(2));
  40783. this.stop();
  40784. },
  40785. /**
  40786. * Renders Line information in the given color.
  40787. *
  40788. * @method Phaser.Utils.Debug#lineInfo
  40789. * @param {Phaser.Line} line - The Line to display the data for.
  40790. * @param {number} x - X position of the debug info to be rendered.
  40791. * @param {number} y - Y position of the debug info to be rendered.
  40792. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  40793. */
  40794. lineInfo: function (line, x, y, color) {
  40795. this.start(x, y, color, 80);
  40796. this.line('start.x:', line.start.x.toFixed(2), 'start.y:', line.start.y.toFixed(2));
  40797. this.line('end.x:', line.end.x.toFixed(2), 'end.y:', line.end.y.toFixed(2));
  40798. this.line('length:', line.length.toFixed(2), 'angle:', line.angle);
  40799. this.stop();
  40800. },
  40801. /**
  40802. * Renders a single pixel at the given size.
  40803. *
  40804. * @method Phaser.Utils.Debug#pixel
  40805. * @param {number} x - X position of the pixel to be rendered.
  40806. * @param {number} y - Y position of the pixel to be rendered.
  40807. * @param {string} [color] - Color of the pixel (format is css color string).
  40808. * @param {number} [size=2] - The 'size' to render the pixel at.
  40809. */
  40810. pixel: function (x, y, color, size) {
  40811. size = size || 2;
  40812. this.start();
  40813. this.context.fillStyle = color;
  40814. this.context.fillRect(x, y, size, size);
  40815. this.stop();
  40816. },
  40817. /**
  40818. * Renders a Phaser geometry object including Rectangle, Circle, Point or Line.
  40819. *
  40820. * @method Phaser.Utils.Debug#geom
  40821. * @param {Phaser.Rectangle|Phaser.Circle|Phaser.Point|Phaser.Line} object - The geometry object to render.
  40822. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  40823. * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false)
  40824. * @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.
  40825. */
  40826. geom: function (object, color, filled, forceType) {
  40827. if (typeof filled === 'undefined') { filled = true; }
  40828. if (typeof forceType === 'undefined') { forceType = 0; }
  40829. color = color || 'rgba(0,255,0,0.4)';
  40830. this.start();
  40831. this.context.fillStyle = color;
  40832. this.context.strokeStyle = color;
  40833. if (object instanceof Phaser.Rectangle || forceType === 1)
  40834. {
  40835. if (filled)
  40836. {
  40837. this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height);
  40838. }
  40839. else
  40840. {
  40841. this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height);
  40842. }
  40843. }
  40844. else if (object instanceof Phaser.Circle || forceType === 2)
  40845. {
  40846. this.context.beginPath();
  40847. this.context.arc(object.x - this.game.camera.x, object.y - this.game.camera.y, object.radius, 0, Math.PI * 2, false);
  40848. this.context.closePath();
  40849. if (filled)
  40850. {
  40851. this.context.fill();
  40852. }
  40853. else
  40854. {
  40855. this.context.stroke();
  40856. }
  40857. }
  40858. else if (object instanceof Phaser.Point || forceType === 3)
  40859. {
  40860. this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, 4, 4);
  40861. }
  40862. else if (object instanceof Phaser.Line || forceType === 4)
  40863. {
  40864. this.context.lineWidth = 1;
  40865. this.context.beginPath();
  40866. this.context.moveTo((object.start.x + 0.5) - this.game.camera.x, (object.start.y + 0.5) - this.game.camera.y);
  40867. this.context.lineTo((object.end.x + 0.5) - this.game.camera.x, (object.end.y + 0.5) - this.game.camera.y);
  40868. this.context.closePath();
  40869. this.context.stroke();
  40870. }
  40871. this.stop();
  40872. },
  40873. /**
  40874. * Renders a Rectangle.
  40875. *
  40876. * @method Phaser.Utils.Debug#geom
  40877. * @param {Phaser.Rectangle|object} object - The geometry object to render.
  40878. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  40879. * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false)
  40880. */
  40881. rectangle: function (object, color, filled) {
  40882. if (typeof filled === 'undefined') { filled = true; }
  40883. color = color || 'rgba(0, 255, 0, 0.4)';
  40884. this.start();
  40885. if (filled)
  40886. {
  40887. this.context.fillStyle = color;
  40888. this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height);
  40889. }
  40890. else
  40891. {
  40892. this.context.strokeStyle = color;
  40893. this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height);
  40894. }
  40895. this.stop();
  40896. },
  40897. /**
  40898. * Render a string of text.
  40899. *
  40900. * @method Phaser.Utils.Debug#text
  40901. * @param {string} text - The line of text to draw.
  40902. * @param {number} x - X position of the debug info to be rendered.
  40903. * @param {number} y - Y position of the debug info to be rendered.
  40904. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  40905. * @param {string} [font] - The font of text to draw.
  40906. */
  40907. text: function (text, x, y, color, font) {
  40908. color = color || 'rgb(255,255,255)';
  40909. font = font || '16px Courier';
  40910. this.start();
  40911. this.context.font = font;
  40912. if (this.renderShadow)
  40913. {
  40914. this.context.fillStyle = 'rgb(0,0,0)';
  40915. this.context.fillText(text, x + 1, y + 1);
  40916. }
  40917. this.context.fillStyle = color;
  40918. this.context.fillText(text, x, y);
  40919. this.stop();
  40920. },
  40921. /**
  40922. * Visually renders a QuadTree to the display.
  40923. *
  40924. * @method Phaser.Utils.Debug#quadTree
  40925. * @param {Phaser.QuadTree} quadtree - The quadtree to render.
  40926. * @param {string} color - The color of the lines in the quadtree.
  40927. */
  40928. quadTree: function (quadtree, color) {
  40929. color = color || 'rgba(255,0,0,0.3)';
  40930. this.start();
  40931. var bounds = quadtree.bounds;
  40932. if (quadtree.nodes.length === 0)
  40933. {
  40934. this.context.strokeStyle = color;
  40935. this.context.strokeRect(bounds.x, bounds.y, bounds.width, bounds.height);
  40936. this.text('size: ' + quadtree.objects.length, bounds.x + 4, bounds.y + 16, 'rgb(0,200,0)', '12px Courier');
  40937. this.context.strokeStyle = 'rgb(0,255,0)';
  40938. for (var i = 0; i < quadtree.objects.length; i++)
  40939. {
  40940. this.context.strokeRect(quadtree.objects[i].x, quadtree.objects[i].y, quadtree.objects[i].width, quadtree.objects[i].height);
  40941. }
  40942. }
  40943. else
  40944. {
  40945. for (var i = 0; i < quadtree.nodes.length; i++)
  40946. {
  40947. this.quadTree(quadtree.nodes[i]);
  40948. }
  40949. }
  40950. this.stop();
  40951. },
  40952. /**
  40953. * Render a Sprites Physics body if it has one set. Note this only works for Arcade and
  40954. * Ninja (AABB, circle only) Physics.
  40955. * To display a P2 body you should enable debug mode on the body when creating it.
  40956. *
  40957. * @method Phaser.Utils.Debug#body
  40958. * @param {Phaser.Sprite} sprite - The sprite whos body will be rendered.
  40959. * @param {string} [color='rgba(0,255,0,0.4)'] - color of the debug info to be rendered. (format is css color string).
  40960. * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false)
  40961. */
  40962. body: function (sprite, color, filled) {
  40963. if (sprite.body)
  40964. {
  40965. if (sprite.body.type === Phaser.Physics.ARCADE)
  40966. {
  40967. this.start();
  40968. Phaser.Physics.Arcade.Body.render(this.context, sprite.body, color, filled);
  40969. this.stop();
  40970. }
  40971. else if (sprite.body.type === Phaser.Physics.NINJA)
  40972. {
  40973. this.start();
  40974. Phaser.Physics.Ninja.Body.render(this.context, sprite.body, color, filled);
  40975. this.stop();
  40976. }
  40977. }
  40978. },
  40979. /**
  40980. * Render a Sprites Physic Body information.
  40981. *
  40982. * @method Phaser.Utils.Debug#bodyInfo
  40983. * @param {Phaser.Sprite} sprite - The sprite to be rendered.
  40984. * @param {number} x - X position of the debug info to be rendered.
  40985. * @param {number} y - Y position of the debug info to be rendered.
  40986. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  40987. */
  40988. bodyInfo: function (sprite, x, y, color) {
  40989. if (sprite.body)
  40990. {
  40991. if (sprite.body.type === Phaser.Physics.ARCADE)
  40992. {
  40993. this.start(x, y, color, 210);
  40994. Phaser.Physics.Arcade.Body.renderBodyInfo(this, sprite.body);
  40995. this.stop();
  40996. }
  40997. }
  40998. }
  40999. };
  41000. Phaser.Utils.Debug.prototype.constructor = Phaser.Utils.Debug;
  41001. /**
  41002. * @author Richard Davey <rich@photonstorm.com>
  41003. * @copyright 2014 Photon Storm Ltd.
  41004. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  41005. */
  41006. /**
  41007. * The Phaser.Color class is a set of static methods that assist in color manipulation and conversion.
  41008. *
  41009. * @class Phaser.Color
  41010. */
  41011. Phaser.Color = {
  41012. /**
  41013. * Packs the r, g, b, a components into a single integer, for use with Int32Array.
  41014. * If device is little endian then ABGR order is used. Otherwise RGBA order is used.
  41015. *
  41016. * @author Matt DesLauriers (@mattdesl)
  41017. * @method Phaser.Color.packPixel
  41018. * @static
  41019. * @param {number} r - The red color component, in the range 0 - 255.
  41020. * @param {number} g - The green color component, in the range 0 - 255.
  41021. * @param {number} b - The blue color component, in the range 0 - 255.
  41022. * @param {number} a - The alpha color component, in the range 0 - 255.
  41023. * @return {number} The packed color as uint32
  41024. */
  41025. packPixel: function (r, g, b, a) {
  41026. if (Phaser.Device.LITTLE_ENDIAN)
  41027. {
  41028. return ( (a << 24) | (b << 16) | (g << 8) | r ) >>> 0;
  41029. }
  41030. else
  41031. {
  41032. return ( (r << 24) | (g << 16) | (b << 8) | a ) >>> 0;
  41033. }
  41034. },
  41035. /**
  41036. * Unpacks the r, g, b, a components into the specified color object, or a new
  41037. * object, for use with Int32Array. If little endian, then ABGR order is used when
  41038. * unpacking, otherwise, RGBA order is used. The resulting color object has the
  41039. * `r, g, b, a` properties which are unrelated to endianness.
  41040. *
  41041. * Note that the integer is assumed to be packed in the correct endianness. On little-endian
  41042. * the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a
  41043. * endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a).
  41044. *
  41045. * @author Matt DesLauriers (@mattdesl)
  41046. * @method Phaser.Color.unpackPixel
  41047. * @static
  41048. * @param {number} rgba - The integer, packed in endian order by packPixel.
  41049. * @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.
  41050. * @param {boolean} [hsl=false] - Also convert the rgb values into hsl?
  41051. * @param {boolean} [hsv=false] - Also convert the rgb values into hsv?
  41052. * @return {object} An object with the red, green and blue values set in the r, g and b properties.
  41053. */
  41054. unpackPixel: function (rgba, out, hsl, hsv) {
  41055. if (typeof out === 'undefined' || out === null) { out = Phaser.Color.createColor(); }
  41056. if (typeof hsl === 'undefined' || hsl === null) { hsl = false; }
  41057. if (typeof hsv === 'undefined' || hsv === null) { hsv = false; }
  41058. if (Phaser.Device.LITTLE_ENDIAN)
  41059. {
  41060. out.a = ((rgba & 0xff000000) >>> 24);
  41061. out.b = ((rgba & 0x00ff0000) >>> 16);
  41062. out.g = ((rgba & 0x0000ff00) >>> 8);
  41063. out.r = ((rgba & 0x000000ff));
  41064. }
  41065. else
  41066. {
  41067. out.r = ((rgba & 0xff000000) >>> 24);
  41068. out.g = ((rgba & 0x00ff0000) >>> 16);
  41069. out.b = ((rgba & 0x0000ff00) >>> 8);
  41070. out.a = ((rgba & 0x000000ff));
  41071. }
  41072. out.color = rgba;
  41073. out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + (out.a / 255) + ')';
  41074. if (hsl)
  41075. {
  41076. Phaser.Color.RGBtoHSL(out.r, out.g, out.b, out);
  41077. }
  41078. if (hsv)
  41079. {
  41080. Phaser.Color.RGBtoHSV(out.r, out.g, out.b, out);
  41081. }
  41082. return out;
  41083. },
  41084. /**
  41085. * A utility to convert an integer in 0xRRGGBBAA format to a color object.
  41086. * This does not rely on endianness.
  41087. *
  41088. * @author Matt DesLauriers (@mattdesl)
  41089. * @method Phaser.Color.fromRGBA
  41090. * @static
  41091. * @param {number} rgba - An RGBA hex
  41092. * @param {object} [out] - The object to use, optional.
  41093. * @return {object} A color object.
  41094. */
  41095. fromRGBA: function (rgba, out) {
  41096. if (!out)
  41097. {
  41098. out = Phaser.Color.createColor();
  41099. }
  41100. out.r = ((rgba & 0xff000000) >>> 24);
  41101. out.g = ((rgba & 0x00ff0000) >>> 16);
  41102. out.b = ((rgba & 0x0000ff00) >>> 8);
  41103. out.a = ((rgba & 0x000000ff));
  41104. out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + out.a + ')';
  41105. return out;
  41106. },
  41107. /**
  41108. * A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format.
  41109. *
  41110. * @author Matt DesLauriers (@mattdesl)
  41111. * @method Phaser.Color.toRGBA
  41112. * @static
  41113. * @param {number} r - The red color component, in the range 0 - 255.
  41114. * @param {number} g - The green color component, in the range 0 - 255.
  41115. * @param {number} b - The blue color component, in the range 0 - 255.
  41116. * @param {number} a - The alpha color component, in the range 0 - 255.
  41117. * @return {number} A RGBA-packed 32 bit integer
  41118. */
  41119. toRGBA: function (r, g, b, a) {
  41120. return (r << 24) | (g << 16) | (b << 8) | a;
  41121. },
  41122. /**
  41123. * Converts an RGB color value to HSL (hue, saturation and lightness).
  41124. * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
  41125. * Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1].
  41126. * Based on code by Michael Jackson (https://github.com/mjijackson)
  41127. *
  41128. * @method Phaser.Color.RGBtoHSL
  41129. * @static
  41130. * @param {number} r - The red color component, in the range 0 - 255.
  41131. * @param {number} g - The green color component, in the range 0 - 255.
  41132. * @param {number} b - The blue color component, in the range 0 - 255.
  41133. * @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.
  41134. * @return {object} An object with the hue, saturation and lightness values set in the h, s and l properties.
  41135. */
  41136. RGBtoHSL: function (r, g, b, out) {
  41137. if (!out)
  41138. {
  41139. out = Phaser.Color.createColor(r, g, b, 1);
  41140. }
  41141. r /= 255;
  41142. g /= 255;
  41143. b /= 255;
  41144. var min = Math.min(r, g, b);
  41145. var max = Math.max(r, g, b);
  41146. // achromatic by default
  41147. out.h = 0;
  41148. out.s = 0;
  41149. out.l = (max + min) / 2;
  41150. if (max !== min)
  41151. {
  41152. var d = max - min;
  41153. out.s = out.l > 0.5 ? d / (2 - max - min) : d / (max + min);
  41154. if (max === r)
  41155. {
  41156. out.h = (g - b) / d + (g < b ? 6 : 0);
  41157. }
  41158. else if (max === g)
  41159. {
  41160. out.h = (b - r) / d + 2;
  41161. }
  41162. else if (max === b)
  41163. {
  41164. out.h = (r - g) / d + 4;
  41165. }
  41166. out.h /= 6;
  41167. }
  41168. return out;
  41169. },
  41170. /**
  41171. * Converts an HSL (hue, saturation and lightness) color value to RGB.
  41172. * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
  41173. * Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255].
  41174. * Based on code by Michael Jackson (https://github.com/mjijackson)
  41175. *
  41176. * @method Phaser.Color.HSLtoRGB
  41177. * @static
  41178. * @param {number} h - The hue, in the range 0 - 1.
  41179. * @param {number} s - The saturation, in the range 0 - 1.
  41180. * @param {number} l - The lightness, in the range 0 - 1.
  41181. * @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.
  41182. * @return {object} An object with the red, green and blue values set in the r, g and b properties.
  41183. */
  41184. HSLtoRGB: function (h, s, l, out) {
  41185. if (!out)
  41186. {
  41187. out = Phaser.Color.createColor(l, l, l);
  41188. }
  41189. else
  41190. {
  41191. // achromatic by default
  41192. out.r = l;
  41193. out.g = l;
  41194. out.b = l;
  41195. }
  41196. if (s !== 0)
  41197. {
  41198. var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  41199. var p = 2 * l - q;
  41200. out.r = Phaser.Color.hueToColor(p, q, h + 1 / 3);
  41201. out.g = Phaser.Color.hueToColor(p, q, h);
  41202. out.b = Phaser.Color.hueToColor(p, q, h - 1 / 3);
  41203. }
  41204. // out.r = (out.r * 255 | 0);
  41205. // out.g = (out.g * 255 | 0);
  41206. // out.b = (out.b * 255 | 0);
  41207. out.r = Math.floor((out.r * 255 | 0));
  41208. out.g = Math.floor((out.g * 255 | 0));
  41209. out.b = Math.floor((out.b * 255 | 0));
  41210. Phaser.Color.updateColor(out);
  41211. return out;
  41212. },
  41213. /**
  41214. * Converts an RGB color value to HSV (hue, saturation and value).
  41215. * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
  41216. * Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1].
  41217. * Based on code by Michael Jackson (https://github.com/mjijackson)
  41218. *
  41219. * @method Phaser.Color.RGBtoHSV
  41220. * @static
  41221. * @param {number} r - The red color component, in the range 0 - 255.
  41222. * @param {number} g - The green color component, in the range 0 - 255.
  41223. * @param {number} b - The blue color component, in the range 0 - 255.
  41224. * @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.
  41225. * @return {object} An object with the hue, saturation and value set in the h, s and v properties.
  41226. */
  41227. RGBtoHSV: function (r, g, b, out) {
  41228. if (!out)
  41229. {
  41230. out = Phaser.Color.createColor(r, g, b, 255);
  41231. }
  41232. r /= 255;
  41233. g /= 255;
  41234. b /= 255;
  41235. var min = Math.min(r, g, b);
  41236. var max = Math.max(r, g, b);
  41237. var d = max - min;
  41238. // achromatic by default
  41239. out.h = 0;
  41240. out.s = max === 0 ? 0 : d / max;
  41241. out.v = max;
  41242. if (max !== min)
  41243. {
  41244. if (max === r)
  41245. {
  41246. out.h = (g - b) / d + (g < b ? 6 : 0);
  41247. }
  41248. else if (max === g)
  41249. {
  41250. out.h = (b - r) / d + 2;
  41251. }
  41252. else if (max === b)
  41253. {
  41254. out.h = (r - g) / d + 4;
  41255. }
  41256. out.h /= 6;
  41257. }
  41258. return out;
  41259. },
  41260. /**
  41261. * Converts an HSV (hue, saturation and value) color value to RGB.
  41262. * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
  41263. * Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255].
  41264. * Based on code by Michael Jackson (https://github.com/mjijackson)
  41265. *
  41266. * @method Phaser.Color.HSVtoRGB
  41267. * @static
  41268. * @param {number} h - The hue, in the range 0 - 1.
  41269. * @param {number} s - The saturation, in the range 0 - 1.
  41270. * @param {number} v - The value, in the range 0 - 1.
  41271. * @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.
  41272. * @return {object} An object with the red, green and blue values set in the r, g and b properties.
  41273. */
  41274. HSVtoRGB: function (h, s, v, out) {
  41275. if (typeof out === 'undefined') { out = Phaser.Color.createColor(0, 0, 0, 1, h, s, 0, v); }
  41276. var r, g, b;
  41277. var i = Math.floor(h * 6);
  41278. var f = h * 6 - i;
  41279. var p = v * (1 - s);
  41280. var q = v * (1 - f * s);
  41281. var t = v * (1 - (1 - f) * s);
  41282. switch (i % 6)
  41283. {
  41284. case 0:
  41285. r = v;
  41286. g = t;
  41287. b = p;
  41288. break;
  41289. case 1:
  41290. r = q;
  41291. g = v;
  41292. b = p;
  41293. break;
  41294. case 2:
  41295. r = p;
  41296. g = v;
  41297. b = t;
  41298. break;
  41299. case 3:
  41300. r = p;
  41301. g = q;
  41302. b = v;
  41303. break;
  41304. case 4:
  41305. r = t;
  41306. g = p;
  41307. b = v;
  41308. break;
  41309. case 5:
  41310. r = v;
  41311. g = p;
  41312. b = q;
  41313. break;
  41314. }
  41315. out.r = Math.floor(r * 255);
  41316. out.g = Math.floor(g * 255);
  41317. out.b = Math.floor(b * 255);
  41318. Phaser.Color.updateColor(out);
  41319. return out;
  41320. },
  41321. /**
  41322. * Converts a hue to an RGB color.
  41323. * Based on code by Michael Jackson (https://github.com/mjijackson)
  41324. *
  41325. * @method Phaser.Color.hueToColor
  41326. * @static
  41327. * @param {number} p
  41328. * @param {number} q
  41329. * @param {number} t
  41330. * @return {number} The color component value.
  41331. */
  41332. hueToColor: function (p, q, t) {
  41333. if (t < 0)
  41334. {
  41335. t += 1;
  41336. }
  41337. if (t > 1)
  41338. {
  41339. t -= 1;
  41340. }
  41341. if (t < 1 / 6)
  41342. {
  41343. return p + (q - p) * 6 * t;
  41344. }
  41345. if (t < 1 / 2)
  41346. {
  41347. return q;
  41348. }
  41349. if (t < 2 / 3)
  41350. {
  41351. return p + (q - p) * (2 / 3 - t) * 6;
  41352. }
  41353. return p;
  41354. },
  41355. /**
  41356. * A utility function to create a lightweight 'color' object with the default components.
  41357. * Any components that are not specified will default to zero.
  41358. *
  41359. * This is useful when you want to use a shared color object for the getPixel and getPixelAt methods.
  41360. *
  41361. * @author Matt DesLauriers (@mattdesl)
  41362. * @method Phaser.Color.createColor
  41363. * @static
  41364. * @param {number} [r=0] - The red color component, in the range 0 - 255.
  41365. * @param {number} [g=0] - The green color component, in the range 0 - 255.
  41366. * @param {number} [b=0] - The blue color component, in the range 0 - 255.
  41367. * @param {number} [a=1] - The alpha color component, in the range 0 - 1.
  41368. * @param {number} [h=0] - The hue, in the range 0 - 1.
  41369. * @param {number} [s=0] - The saturation, in the range 0 - 1.
  41370. * @param {number} [l=0] - The lightness, in the range 0 - 1.
  41371. * @param {number} [v=0] - The value, in the range 0 - 1.
  41372. * @return {object} The resulting object with r, g, b, a properties and h, s, l and v.
  41373. */
  41374. createColor: function (r, g, b, a, h, s, l, v) {
  41375. 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 };
  41376. out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + out.a + ')';
  41377. return out;
  41378. },
  41379. /**
  41380. * Takes a color object and updates the rgba property.
  41381. *
  41382. * @method Phaser.Color.updateColor
  41383. * @static
  41384. * @param {object} out - The color object to update.
  41385. * @returns {number} A native color value integer (format: 0xAARRGGBB).
  41386. */
  41387. updateColor: function (out) {
  41388. out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + out.a + ')';
  41389. return out;
  41390. },
  41391. /**
  41392. * Given an alpha and 3 color values this will return an integer representation of it.
  41393. *
  41394. * @method Phaser.Color.getColor32
  41395. * @static
  41396. * @param {number} a - The alpha color component, in the range 0 - 255.
  41397. * @param {number} r - The red color component, in the range 0 - 255.
  41398. * @param {number} g - The green color component, in the range 0 - 255.
  41399. * @param {number} b - The blue color component, in the range 0 - 255.
  41400. * @returns {number} A native color value integer (format: 0xAARRGGBB).
  41401. */
  41402. getColor32: function (a, r, g, b) {
  41403. return a << 24 | r << 16 | g << 8 | b;
  41404. },
  41405. /**
  41406. * Given 3 color values this will return an integer representation of it.
  41407. *
  41408. * @method Phaser.Color.getColor
  41409. * @static
  41410. * @param {number} r - The red color component, in the range 0 - 255.
  41411. * @param {number} g - The green color component, in the range 0 - 255.
  41412. * @param {number} b - The blue color component, in the range 0 - 255.
  41413. * @returns {number} A native color value integer (format: 0xRRGGBB).
  41414. */
  41415. getColor: function (r, g, b) {
  41416. return r << 16 | g << 8 | b;
  41417. },
  41418. /**
  41419. * Converts the given color values into a string.
  41420. * If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`.
  41421. *
  41422. * @method Phaser.Color.RGBtoString
  41423. * @static
  41424. * @param {number} r - The red color component, in the range 0 - 255.
  41425. * @param {number} g - The green color component, in the range 0 - 255.
  41426. * @param {number} b - The blue color component, in the range 0 - 255.
  41427. * @param {number} [a=255] - The alpha color component, in the range 0 - 255.
  41428. * @param {string} [prefix='#'] - The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`.
  41429. * @return {string} A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`.
  41430. */
  41431. RGBtoString: function (r, g, b, a, prefix) {
  41432. if (typeof a === 'undefined') { a = 255; }
  41433. if (typeof prefix === 'undefined') { prefix = '#'; }
  41434. if (prefix === '#')
  41435. {
  41436. return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
  41437. }
  41438. else
  41439. {
  41440. return '0x' + Phaser.Color.componentToHex(a) + Phaser.Color.componentToHex(r) + Phaser.Color.componentToHex(g) + Phaser.Color.componentToHex(b);
  41441. }
  41442. },
  41443. /**
  41444. * Converts a hex string into an integer color value.
  41445. *
  41446. * @method Phaser.Color.hexToRGB
  41447. * @static
  41448. * @param {string} hex - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`.
  41449. * @return {number} The rgb color value in the format 0xAARRGGBB.
  41450. */
  41451. hexToRGB: function (hex) {
  41452. var rgb = Phaser.Color.hexToColor(hex);
  41453. if (rgb)
  41454. {
  41455. return Phaser.Color.getColor32(rgb.a, rgb.r, rgb.g, rgb.b);
  41456. }
  41457. },
  41458. /**
  41459. * Converts a hex string into a Phaser Color object.
  41460. *
  41461. * @method Phaser.Color.hexToColor
  41462. * @static
  41463. * @param {string} hex - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`.
  41464. * @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.
  41465. * @return {object} An object with the red, green and blue values set in the r, g and b properties.
  41466. */
  41467. hexToColor: function (hex, out) {
  41468. if (!out)
  41469. {
  41470. out = Phaser.Color.createColor();
  41471. }
  41472. // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  41473. var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  41474. hex = hex.replace(shorthandRegex, function(m, r, g, b) {
  41475. return r + r + g + g + b + b;
  41476. });
  41477. var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  41478. if (result)
  41479. {
  41480. out.r = parseInt(result[1], 16);
  41481. out.g = parseInt(result[2], 16);
  41482. out.b = parseInt(result[3], 16);
  41483. }
  41484. return out;
  41485. },
  41486. /**
  41487. * Return a string containing a hex representation of the given color component.
  41488. *
  41489. * @method Phaser.Color.componentToHex
  41490. * @static
  41491. * @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255.
  41492. * @returns {string} A string of length 2 characters, i.e. 255 = ff, 100 = 64.
  41493. */
  41494. componentToHex: function (color) {
  41495. var hex = color.toString(16);
  41496. return hex.length == 1 ? "0" + hex : hex;
  41497. },
  41498. /**
  41499. * Get HSV color wheel values in an array which will be 360 elements in size.
  41500. *
  41501. * @method Phaser.Color.HSVColorWheel
  41502. * @static
  41503. * @param {number} [s=1] - The saturation, in the range 0 - 1.
  41504. * @param {number} [v=1] - The value, in the range 0 - 1.
  41505. * @return {array} An array containing 360 elements corresponding to the HSV color wheel.
  41506. */
  41507. HSVColorWheel: function (s, v) {
  41508. if (typeof s === 'undefined') { s = 1.0; }
  41509. if (typeof v === 'undefined') { v = 1.0; }
  41510. var colors = [];
  41511. for (var c = 0; c <= 359; c++)
  41512. {
  41513. colors.push(Phaser.Color.HSVtoRGB(c / 359, s, v));
  41514. }
  41515. return colors;
  41516. },
  41517. /**
  41518. * Get HSL color wheel values in an array which will be 360 elements in size.
  41519. *
  41520. * @method Phaser.Color.HSLColorWheel
  41521. * @static
  41522. * @param {number} [s=0.5] - The saturation, in the range 0 - 1.
  41523. * @param {number} [l=0.5] - The lightness, in the range 0 - 1.
  41524. * @return {array} An array containing 360 elements corresponding to the HSL color wheel.
  41525. */
  41526. HSLColorWheel: function (s, l) {
  41527. if (typeof s === 'undefined') { s = 0.5; }
  41528. if (typeof l === 'undefined') { l = 0.5; }
  41529. var colors = [];
  41530. for (var c = 0; c <= 359; c++)
  41531. {
  41532. colors.push(Phaser.Color.HSLtoRGB(c / 359, s, l));
  41533. }
  41534. return colors;
  41535. },
  41536. /**
  41537. * Interpolates the two given colours based on the supplied step and currentStep properties.
  41538. *
  41539. * @method Phaser.Color.interpolateColor
  41540. * @static
  41541. * @param {number} color1 - The first color value.
  41542. * @param {number} color2 - The second color value.
  41543. * @param {number} steps - The number of steps to run the interpolation over.
  41544. * @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.
  41545. * @param {number} alpha - The alpha of the returned color.
  41546. * @returns {number} The interpolated color value.
  41547. */
  41548. interpolateColor: function (color1, color2, steps, currentStep, alpha) {
  41549. if (typeof alpha === "undefined") { alpha = 255; }
  41550. var src1 = Phaser.Color.getRGB(color1);
  41551. var src2 = Phaser.Color.getRGB(color2);
  41552. var r = (((src2.red - src1.red) * currentStep) / steps) + src1.red;
  41553. var g = (((src2.green - src1.green) * currentStep) / steps) + src1.green;
  41554. var b = (((src2.blue - src1.blue) * currentStep) / steps) + src1.blue;
  41555. return Phaser.Color.getColor32(alpha, r, g, b);
  41556. },
  41557. /**
  41558. * Interpolates the two given colours based on the supplied step and currentStep properties.
  41559. *
  41560. * @method Phaser.Color.interpolateColorWithRGB
  41561. * @static
  41562. * @param {number} color - The first color value.
  41563. * @param {number} r - The red color value, between 0 and 0xFF (255).
  41564. * @param {number} g - The green color value, between 0 and 0xFF (255).
  41565. * @param {number} b - The blue color value, between 0 and 0xFF (255).
  41566. * @param {number} steps - The number of steps to run the interpolation over.
  41567. * @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.
  41568. * @returns {number} The interpolated color value.
  41569. */
  41570. interpolateColorWithRGB: function (color, r, g, b, steps, currentStep) {
  41571. var src = Phaser.Color.getRGB(color);
  41572. var or = (((r - src.red) * currentStep) / steps) + src.red;
  41573. var og = (((g - src.green) * currentStep) / steps) + src.green;
  41574. var ob = (((b - src.blue) * currentStep) / steps) + src.blue;
  41575. return Phaser.Color.getColor(or, og, ob);
  41576. },
  41577. /**
  41578. * Interpolates the two given colours based on the supplied step and currentStep properties.
  41579. * @method Phaser.Color.interpolateRGB
  41580. * @static
  41581. * @param {number} r1 - The red color value, between 0 and 0xFF (255).
  41582. * @param {number} g1 - The green color value, between 0 and 0xFF (255).
  41583. * @param {number} b1 - The blue color value, between 0 and 0xFF (255).
  41584. * @param {number} r2 - The red color value, between 0 and 0xFF (255).
  41585. * @param {number} g2 - The green color value, between 0 and 0xFF (255).
  41586. * @param {number} b2 - The blue color value, between 0 and 0xFF (255).
  41587. * @param {number} steps - The number of steps to run the interpolation over.
  41588. * @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.
  41589. * @returns {number} The interpolated color value.
  41590. */
  41591. interpolateRGB: function (r1, g1, b1, r2, g2, b2, steps, currentStep) {
  41592. var r = (((r2 - r1) * currentStep) / steps) + r1;
  41593. var g = (((g2 - g1) * currentStep) / steps) + g1;
  41594. var b = (((b2 - b1) * currentStep) / steps) + b1;
  41595. return Phaser.Color.getColor(r, g, b);
  41596. },
  41597. /**
  41598. * Returns a random color value between black and white
  41599. * Set the min value to start each channel from the given offset.
  41600. * Set the max value to restrict the maximum color used per channel.
  41601. *
  41602. * @method Phaser.Color.getRandomColor
  41603. * @static
  41604. * @param {number} min - The lowest value to use for the color.
  41605. * @param {number} max - The highest value to use for the color.
  41606. * @param {number} alpha - The alpha value of the returning color (default 255 = fully opaque).
  41607. * @returns {number} 32-bit color value with alpha.
  41608. */
  41609. getRandomColor: function (min, max, alpha) {
  41610. if (typeof min === "undefined") { min = 0; }
  41611. if (typeof max === "undefined") { max = 255; }
  41612. if (typeof alpha === "undefined") { alpha = 255; }
  41613. // Sanity checks
  41614. if (max > 255 || min > max)
  41615. {
  41616. return Phaser.Color.getColor(255, 255, 255);
  41617. }
  41618. var red = min + Math.round(Math.random() * (max - min));
  41619. var green = min + Math.round(Math.random() * (max - min));
  41620. var blue = min + Math.round(Math.random() * (max - min));
  41621. return Phaser.Color.getColor32(alpha, red, green, blue);
  41622. },
  41623. /**
  41624. * Return the component parts of a color as an Object with the properties alpha, red, green, blue.
  41625. *
  41626. * Alpha will only be set if it exist in the given color (0xAARRGGBB)
  41627. *
  41628. * @method Phaser.Color.getRGB
  41629. * @static
  41630. * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB).
  41631. * @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.
  41632. */
  41633. getRGB: function (color) {
  41634. if (color > 16777215)
  41635. {
  41636. // The color value has an alpha component
  41637. return {
  41638. alpha: color >>> 24,
  41639. red: color >> 16 & 0xFF,
  41640. green: color >> 8 & 0xFF,
  41641. blue: color & 0xFF,
  41642. a: color >>> 24,
  41643. r: color >> 16 & 0xFF,
  41644. g: color >> 8 & 0xFF,
  41645. b: color & 0xFF
  41646. };
  41647. }
  41648. else
  41649. {
  41650. return {
  41651. alpha: 255,
  41652. red: color >> 16 & 0xFF,
  41653. green: color >> 8 & 0xFF,
  41654. blue: color & 0xFF,
  41655. a: 255,
  41656. r: color >> 16 & 0xFF,
  41657. g: color >> 8 & 0xFF,
  41658. b: color & 0xFF
  41659. };
  41660. }
  41661. },
  41662. /**
  41663. * Returns a CSS friendly string value from the given color.
  41664. *
  41665. * @method Phaser.Color.getWebRGB
  41666. * @static
  41667. * @param {number|Object} color - Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties.
  41668. * @returns {string} A string in the format: 'rgba(r,g,b,a)'
  41669. */
  41670. getWebRGB: function (color) {
  41671. if (typeof color === 'object')
  41672. {
  41673. return 'rgba(' + color.r.toString() + ',' + color.g.toString() + ',' + color.b.toString() + ',' + (color.a / 255).toString() + ')';
  41674. }
  41675. else
  41676. {
  41677. var rgb = Phaser.Color.getRGB(color);
  41678. return 'rgba(' + rgb.r.toString() + ',' + rgb.g.toString() + ',' + rgb.b.toString() + ',' + (rgb.a / 255).toString() + ')';
  41679. }
  41680. },
  41681. /**
  41682. * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255.
  41683. *
  41684. * @method Phaser.Color.getAlpha
  41685. * @static
  41686. * @param {number} color - In the format 0xAARRGGBB.
  41687. * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)).
  41688. */
  41689. getAlpha: function (color) {
  41690. return color >>> 24;
  41691. },
  41692. /**
  41693. * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1.
  41694. *
  41695. * @method Phaser.Color.getAlphaFloat
  41696. * @static
  41697. * @param {number} color - In the format 0xAARRGGBB.
  41698. * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)).
  41699. */
  41700. getAlphaFloat: function (color) {
  41701. return (color >>> 24) / 255;
  41702. },
  41703. /**
  41704. * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255.
  41705. *
  41706. * @method Phaser.Color.getRed
  41707. * @static
  41708. * @param {number} color In the format 0xAARRGGBB.
  41709. * @returns {number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red).
  41710. */
  41711. getRed: function (color) {
  41712. return color >> 16 & 0xFF;
  41713. },
  41714. /**
  41715. * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255.
  41716. *
  41717. * @method Phaser.Color.getGreen
  41718. * @static
  41719. * @param {number} color - In the format 0xAARRGGBB.
  41720. * @returns {number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green).
  41721. */
  41722. getGreen: function (color) {
  41723. return color >> 8 & 0xFF;
  41724. },
  41725. /**
  41726. * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255.
  41727. *
  41728. * @method Phaser.Color.getBlue
  41729. * @static
  41730. * @param {number} color - In the format 0xAARRGGBB.
  41731. * @returns {number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue).
  41732. */
  41733. getBlue: function (color) {
  41734. return color & 0xFF;
  41735. },
  41736. // The following are all DEPRECATED
  41737. /**
  41738. * DEPRECATED: This method will be removed in Phaser 2.1.
  41739. * Returns a string containing handy information about the given color including string hex value,
  41740. * RGB format information. Each section starts on a newline, 3 lines in total.
  41741. *
  41742. * @method Phaser.Color.getColorInfo
  41743. * @static
  41744. * @param {number} color - A color value in the format 0xAARRGGBB.
  41745. * @returns {string} String containing the 3 lines of information.
  41746. */
  41747. getColorInfo: function (color) {
  41748. var argb = Phaser.Color.getRGB(color);
  41749. // Hex format
  41750. var result = Phaser.Color.RGBtoHexstring(color) + "\n";
  41751. // RGB format
  41752. result = result.concat("Alpha: " + argb.alpha + " Red: " + argb.red + " Green: " + argb.green + " Blue: " + argb.blue) + "\n";
  41753. return result;
  41754. },
  41755. /**
  41756. * DEPRECATED: This method will be removed in Phaser 2.1. Please use Phaser.Color.RGBtoString instead.
  41757. * Return a string representation of the color in the format 0xAARRGGBB.
  41758. *
  41759. * @method Phaser.Color.RGBtoHexstring
  41760. * @static
  41761. * @param {number} color - The color to get the string representation for
  41762. * @returns {string} A string of length 10 characters in the format 0xAARRGGBB
  41763. */
  41764. RGBtoHexstring: function (color) {
  41765. var argb = Phaser.Color.getRGB(color);
  41766. return "0x" + Phaser.Color.colorToHexstring(argb.alpha) + Phaser.Color.colorToHexstring(argb.red) + Phaser.Color.colorToHexstring(argb.green) + Phaser.Color.colorToHexstring(argb.blue);
  41767. },
  41768. /**
  41769. * DEPRECATED: This method will be removed in Phaser 2.1. Please use Phaser.Color.RGBtoString instead.
  41770. * Return a string representation of the color in the format #RRGGBB.
  41771. *
  41772. * @method Phaser.Color.RGBtoWebstring
  41773. * @static
  41774. * @param {number} color - The color to get the string representation for.
  41775. * @returns {string} A string of length 10 characters in the format 0xAARRGGBB.
  41776. */
  41777. RGBtoWebstring: function (color) {
  41778. var argb = Phaser.Color.getRGB(color);
  41779. return "#" + Phaser.Color.colorToHexstring(argb.red) + Phaser.Color.colorToHexstring(argb.green) + Phaser.Color.colorToHexstring(argb.blue);
  41780. },
  41781. /**
  41782. * DEPRECATED: This method will be removed in Phaser 2.1. Please use Phaser.Color.componentToHex instead.
  41783. * Return a string containing a hex representation of the given color.
  41784. *
  41785. * @method Phaser.Color.colorToHexstring
  41786. * @static
  41787. * @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255).
  41788. * @returns {string} A string of length 2 characters, i.e. 255 = FF, 0 = 00.
  41789. */
  41790. colorToHexstring: function (color) {
  41791. var digits = "0123456789ABCDEF";
  41792. var lsd = color % 16;
  41793. var msd = (color - lsd) / 16;
  41794. var hexified = digits.charAt(msd) + digits.charAt(lsd);
  41795. return hexified;
  41796. }
  41797. };
  41798. /**
  41799. * @author Richard Davey <rich@photonstorm.com>
  41800. * @copyright 2014 Photon Storm Ltd.
  41801. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  41802. */
  41803. /**
  41804. * The Physics Manager is responsible for looking after all of the running physics systems.
  41805. * Phaser supports 3 physics systems: Arcade Physics, P2 and Ninja Physics (with Box2D and Chipmunk in development)
  41806. * Game Objects can belong to only 1 physics system, but you can have multiple systems active in a single game.
  41807. *
  41808. * 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
  41809. * faster (due to being much simpler) Arcade Physics system.
  41810. *
  41811. * @class Phaser.Physics
  41812. *
  41813. * @constructor
  41814. * @param {Phaser.Game} game - A reference to the currently running game.
  41815. * @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation.
  41816. */
  41817. Phaser.Physics = function (game, config) {
  41818. config = config || {};
  41819. /**
  41820. * @property {Phaser.Game} game - Local reference to game.
  41821. */
  41822. this.game = game;
  41823. /**
  41824. * @property {object} config - The physics configuration object as passed to the game on creation.
  41825. */
  41826. this.config = config;
  41827. /**
  41828. * @property {Phaser.Physics.Arcade} arcade - The Arcade Physics system.
  41829. */
  41830. this.arcade = null;
  41831. /**
  41832. * @property {Phaser.Physics.P2} p2 - The P2.JS Physics system.
  41833. */
  41834. this.p2 = null;
  41835. /**
  41836. * @property {Phaser.Physics.Ninja} ninja - The N+ Ninja Physics System.
  41837. */
  41838. this.ninja = null;
  41839. /**
  41840. * @property {Phaser.Physics.Box2D} box2d - The Box2D Physics system (to be done).
  41841. */
  41842. this.box2d = null;
  41843. /**
  41844. * @property {Phaser.Physics.Chipmunk} chipmunk - The Chipmunk Physics system (to be done).
  41845. */
  41846. this.chipmunk = null;
  41847. this.parseConfig();
  41848. };
  41849. /**
  41850. * @const
  41851. * @type {number}
  41852. */
  41853. Phaser.Physics.ARCADE = 0;
  41854. /**
  41855. * @const
  41856. * @type {number}
  41857. */
  41858. Phaser.Physics.P2JS = 1;
  41859. /**
  41860. * @const
  41861. * @type {number}
  41862. */
  41863. Phaser.Physics.NINJA = 2;
  41864. /**
  41865. * @const
  41866. * @type {number}
  41867. */
  41868. Phaser.Physics.BOX2D = 3;
  41869. /**
  41870. * @const
  41871. * @type {number}
  41872. */
  41873. Phaser.Physics.CHIPMUNK = 5;
  41874. Phaser.Physics.prototype = {
  41875. /**
  41876. * Parses the Physics Configuration object passed to the Game constructor and starts any physics systems specified within.
  41877. *
  41878. * @method Phaser.Physics#parseConfig
  41879. */
  41880. parseConfig: function () {
  41881. if ((!this.config.hasOwnProperty('arcade') || this.config['arcade'] === true) && Phaser.Physics.hasOwnProperty('Arcade'))
  41882. {
  41883. // If Arcade isn't specified, we create it automatically if we can
  41884. this.arcade = new Phaser.Physics.Arcade(this.game);
  41885. this.game.time.deltaCap = 0.2;
  41886. }
  41887. if (this.config.hasOwnProperty('ninja') && this.config['ninja'] === true && Phaser.Physics.hasOwnProperty('Ninja'))
  41888. {
  41889. this.ninja = new Phaser.Physics.Ninja(this.game);
  41890. }
  41891. if (this.config.hasOwnProperty('p2') && this.config['p2'] === true && Phaser.Physics.hasOwnProperty('P2'))
  41892. {
  41893. this.p2 = new Phaser.Physics.P2(this.game, this.config);
  41894. }
  41895. },
  41896. /**
  41897. * This will create an instance of the requested physics simulation.
  41898. * Phaser.Physics.Arcade is running by default, but all others need activating directly.
  41899. * You can start the following physics systems:
  41900. * Phaser.Physics.P2JS - A full-body advanced physics system by Stefan Hedman.
  41901. * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system.
  41902. * Phaser.Physics.BOX2D and Phaser.Physics.CHIPMUNK are still in development.
  41903. *
  41904. * @method Phaser.Physics#startSystem
  41905. * @param {number} The physics system to start.
  41906. */
  41907. startSystem: function (system) {
  41908. if (system === Phaser.Physics.ARCADE)
  41909. {
  41910. this.arcade = new Phaser.Physics.Arcade(this.game);
  41911. }
  41912. else if (system === Phaser.Physics.P2JS)
  41913. {
  41914. this.p2 = new Phaser.Physics.P2(this.game, this.config);
  41915. }
  41916. if (system === Phaser.Physics.NINJA)
  41917. {
  41918. this.ninja = new Phaser.Physics.Ninja(this.game);
  41919. }
  41920. else if (system === Phaser.Physics.BOX2D && this.box2d === null)
  41921. {
  41922. throw new Error('The Box2D physics system has not been implemented yet.');
  41923. }
  41924. else if (system === Phaser.Physics.CHIPMUNK && this.chipmunk === null)
  41925. {
  41926. throw new Error('The Chipmunk physics system has not been implemented yet.');
  41927. }
  41928. this.setBoundsToWorld();
  41929. },
  41930. /**
  41931. * This will create a default physics body on the given game object or array of objects.
  41932. * 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.
  41933. * It can be for any of the physics systems that have been started:
  41934. *
  41935. * Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation.
  41936. * Phaser.Physics.P2JS - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints.
  41937. * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision.
  41938. * Phaser.Physics.BOX2D and Phaser.Physics.CHIPMUNK are still in development.
  41939. *
  41940. * 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
  41941. * individual physics systems `enable` methods instead of using this generic one.
  41942. *
  41943. * @method Phaser.Physics#enable
  41944. * @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.
  41945. * @param {number} [system=Phaser.Physics.ARCADE] - The physics system that will be used to create the body. Defaults to Arcade Physics.
  41946. * @param {boolean} [debug=false] - Enable the debug drawing for this body. Defaults to false.
  41947. */
  41948. enable: function (object, system, debug) {
  41949. if (typeof system === 'undefined') { system = Phaser.Physics.ARCADE; }
  41950. if (typeof debug === 'undefined') { debug = false; }
  41951. if (system === Phaser.Physics.ARCADE)
  41952. {
  41953. this.arcade.enable(object);
  41954. }
  41955. else if (system === Phaser.Physics.P2JS && this.p2)
  41956. {
  41957. this.p2.enable(object, debug);
  41958. }
  41959. else if (system === Phaser.Physics.NINJA && this.ninja)
  41960. {
  41961. this.ninja.enableAABB(object);
  41962. }
  41963. },
  41964. /**
  41965. * preUpdate checks.
  41966. *
  41967. * @method Phaser.Physics#preUpdate
  41968. * @protected
  41969. */
  41970. preUpdate: function () {
  41971. // ArcadePhysics / Ninja don't have a core to preUpdate
  41972. if (this.p2)
  41973. {
  41974. this.p2.preUpdate();
  41975. }
  41976. },
  41977. /**
  41978. * Updates all running physics systems.
  41979. *
  41980. * @method Phaser.Physics#update
  41981. * @protected
  41982. */
  41983. update: function () {
  41984. // ArcadePhysics / Ninja don't have a core to update
  41985. if (this.p2)
  41986. {
  41987. this.p2.update();
  41988. }
  41989. },
  41990. /**
  41991. * Updates the physics bounds to match the world dimensions.
  41992. *
  41993. * @method Phaser.Physics#setBoundsToWorld
  41994. * @protected
  41995. */
  41996. setBoundsToWorld: function () {
  41997. if (this.arcade)
  41998. {
  41999. this.arcade.setBoundsToWorld();
  42000. }
  42001. if (this.ninja)
  42002. {
  42003. this.ninja.setBoundsToWorld();
  42004. }
  42005. if (this.p2)
  42006. {
  42007. this.p2.setBoundsToWorld();
  42008. }
  42009. },
  42010. /**
  42011. * Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes.
  42012. *
  42013. * @method Phaser.Physics#clear
  42014. * @protected
  42015. */
  42016. clear: function () {
  42017. if (this.p2)
  42018. {
  42019. this.p2.clear();
  42020. }
  42021. },
  42022. /**
  42023. * Destroys all active physics systems. Usually only called on a Game Shutdown, not on a State swap.
  42024. *
  42025. * @method Phaser.Physics#destroy
  42026. */
  42027. destroy: function () {
  42028. if (this.p2)
  42029. {
  42030. this.p2.destroy();
  42031. }
  42032. this.arcade = null;
  42033. this.ninja = null;
  42034. this.p2 = null;
  42035. }
  42036. };
  42037. Phaser.Physics.prototype.constructor = Phaser.Physics;
  42038. /**
  42039. * @author Richard Davey <rich@photonstorm.com>
  42040. * @copyright 2014 Photon Storm Ltd.
  42041. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  42042. */
  42043. /**
  42044. * Arcade Physics constructor.
  42045. *
  42046. * @class Phaser.Physics.Arcade
  42047. * @classdesc Arcade Physics Constructor
  42048. * @constructor
  42049. * @param {Phaser.Game} game reference to the current game instance.
  42050. */
  42051. Phaser.Physics.Arcade = function (game) {
  42052. /**
  42053. * @property {Phaser.Game} game - Local reference to game.
  42054. */
  42055. this.game = game;
  42056. /**
  42057. * @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity.
  42058. */
  42059. this.gravity = new Phaser.Point();
  42060. /**
  42061. * @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds.
  42062. */
  42063. this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height);
  42064. /**
  42065. * Set the checkCollision properties to control for which bounds collision is processed.
  42066. * For example checkCollision.down = false means Bodies cannot collide with the World.bounds.bottom.
  42067. * @property {object} checkCollision - An object containing allowed collision flags.
  42068. */
  42069. this.checkCollision = { up: true, down: true, left: true, right: true };
  42070. /**
  42071. * @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad.
  42072. */
  42073. this.maxObjects = 10;
  42074. /**
  42075. * @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels.
  42076. */
  42077. this.maxLevels = 4;
  42078. /**
  42079. * @property {number} OVERLAP_BIAS - A value added to the delta values during collision checks.
  42080. */
  42081. this.OVERLAP_BIAS = 4;
  42082. /**
  42083. * @property {number} TILE_BIAS - A value added to the delta values during collision with tiles. Adjust this if you get tunnelling.
  42084. */
  42085. this.TILE_BIAS = 16;
  42086. /**
  42087. * @property {boolean} forceX - If true World.separate will always separate on the X axis before Y. Otherwise it will check gravity totals first.
  42088. */
  42089. this.forceX = false;
  42090. /**
  42091. * @property {Phaser.QuadTree} quadTree - The world QuadTree.
  42092. */
  42093. 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);
  42094. // Avoid gc spikes by caching these values for re-use
  42095. /**
  42096. * @property {number} _overlap - Internal cache var.
  42097. * @private
  42098. */
  42099. this._overlap = 0;
  42100. /**
  42101. * @property {number} _maxOverlap - Internal cache var.
  42102. * @private
  42103. */
  42104. this._maxOverlap = 0;
  42105. /**
  42106. * @property {number} _velocity1 - Internal cache var.
  42107. * @private
  42108. */
  42109. this._velocity1 = 0;
  42110. /**
  42111. * @property {number} _velocity2 - Internal cache var.
  42112. * @private
  42113. */
  42114. this._velocity2 = 0;
  42115. /**
  42116. * @property {number} _newVelocity1 - Internal cache var.
  42117. * @private
  42118. */
  42119. this._newVelocity1 = 0;
  42120. /**
  42121. * @property {number} _newVelocity2 - Internal cache var.
  42122. * @private
  42123. */
  42124. this._newVelocity2 = 0;
  42125. /**
  42126. * @property {number} _average - Internal cache var.
  42127. * @private
  42128. */
  42129. this._average = 0;
  42130. /**
  42131. * @property {Array} _mapData - Internal cache var.
  42132. * @private
  42133. */
  42134. this._mapData = [];
  42135. /**
  42136. * @property {boolean} _result - Internal cache var.
  42137. * @private
  42138. */
  42139. this._result = false;
  42140. /**
  42141. * @property {number} _total - Internal cache var.
  42142. * @private
  42143. */
  42144. this._total = 0;
  42145. /**
  42146. * @property {number} _angle - Internal cache var.
  42147. * @private
  42148. */
  42149. this._angle = 0;
  42150. /**
  42151. * @property {number} _dx - Internal cache var.
  42152. * @private
  42153. */
  42154. this._dx = 0;
  42155. /**
  42156. * @property {number} _dy - Internal cache var.
  42157. * @private
  42158. */
  42159. this._dy = 0;
  42160. };
  42161. Phaser.Physics.Arcade.prototype.constructor = Phaser.Physics.Arcade;
  42162. Phaser.Physics.Arcade.prototype = {
  42163. /**
  42164. * Updates the size of this physics world.
  42165. *
  42166. * @method Phaser.Physics.Arcade#setBounds
  42167. * @param {number} x - Top left most corner of the world.
  42168. * @param {number} y - Top left most corner of the world.
  42169. * @param {number} width - New width of the world. Can never be smaller than the Game.width.
  42170. * @param {number} height - New height of the world. Can never be smaller than the Game.height.
  42171. */
  42172. setBounds: function (x, y, width, height) {
  42173. this.bounds.setTo(x, y, width, height);
  42174. },
  42175. /**
  42176. * Updates the size of this physics world to match the size of the game world.
  42177. *
  42178. * @method Phaser.Physics.Arcade#setBoundsToWorld
  42179. */
  42180. setBoundsToWorld: function () {
  42181. this.bounds.setTo(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height);
  42182. },
  42183. /**
  42184. * This will create an Arcade Physics body on the given game object or array of game objects.
  42185. * 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.
  42186. *
  42187. * @method Phaser.Physics.Arcade#enable
  42188. * @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.
  42189. * @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.
  42190. */
  42191. enable: function (object, children) {
  42192. if (typeof children === 'undefined') { children = true; }
  42193. var i = 1;
  42194. if (Array.isArray(object))
  42195. {
  42196. i = object.length;
  42197. while (i--)
  42198. {
  42199. if (object[i] instanceof Phaser.Group)
  42200. {
  42201. // If it's a Group then we do it on the children regardless
  42202. this.enable(object[i].children, children);
  42203. }
  42204. else
  42205. {
  42206. this.enableBody(object[i]);
  42207. if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0)
  42208. {
  42209. this.enable(object[i], true);
  42210. }
  42211. }
  42212. }
  42213. }
  42214. else
  42215. {
  42216. if (object instanceof Phaser.Group)
  42217. {
  42218. // If it's a Group then we do it on the children regardless
  42219. this.enable(object.children, children);
  42220. }
  42221. else
  42222. {
  42223. this.enableBody(object);
  42224. if (children && object.hasOwnProperty('children') && object.children.length > 0)
  42225. {
  42226. this.enable(object.children, true);
  42227. }
  42228. }
  42229. }
  42230. },
  42231. /**
  42232. * Creates an Arcade Physics body on the given game object.
  42233. * 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.
  42234. *
  42235. * @method Phaser.Physics.Arcade#enableBody
  42236. * @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.
  42237. */
  42238. enableBody: function (object) {
  42239. if (object.hasOwnProperty('body') && object.body === null)
  42240. {
  42241. object.body = new Phaser.Physics.Arcade.Body(object);
  42242. }
  42243. },
  42244. /**
  42245. * Called automatically by a Physics body, it updates all motion related values on the Body.
  42246. *
  42247. * @method Phaser.Physics.Arcade#updateMotion
  42248. * @param {Phaser.Physics.Arcade.Body} The Body object to be updated.
  42249. */
  42250. updateMotion: function (body) {
  42251. this._velocityDelta = this.computeVelocity(0, body, body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity;
  42252. body.angularVelocity += this._velocityDelta;
  42253. body.rotation += (body.angularVelocity * this.game.time.physicsElapsed);
  42254. body.velocity.x = this.computeVelocity(1, body, body.velocity.x, body.acceleration.x, body.drag.x, body.maxVelocity.x);
  42255. body.velocity.y = this.computeVelocity(2, body, body.velocity.y, body.acceleration.y, body.drag.y, body.maxVelocity.y);
  42256. },
  42257. /**
  42258. * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity.
  42259. * Based on a function in Flixel by @ADAMATOMIC
  42260. *
  42261. * @method Phaser.Physics.Arcade#computeVelocity
  42262. * @param {number} axis - 0 for nothing, 1 for horizontal, 2 for vertical.
  42263. * @param {Phaser.Physics.Arcade.Body} body - The Body object to be updated.
  42264. * @param {number} velocity - Any component of velocity (e.g. 20).
  42265. * @param {number} acceleration - Rate at which the velocity is changing.
  42266. * @param {number} drag - Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set.
  42267. * @param {number} [max=10000] - An absolute value cap for the velocity.
  42268. * @return {number} The altered Velocity value.
  42269. */
  42270. computeVelocity: function (axis, body, velocity, acceleration, drag, max) {
  42271. max = max || 10000;
  42272. if (axis == 1 && body.allowGravity)
  42273. {
  42274. velocity += (this.gravity.x + body.gravity.x) * this.game.time.physicsElapsed;
  42275. }
  42276. else if (axis == 2 && body.allowGravity)
  42277. {
  42278. velocity += (this.gravity.y + body.gravity.y) * this.game.time.physicsElapsed;
  42279. }
  42280. if (acceleration)
  42281. {
  42282. velocity += acceleration * this.game.time.physicsElapsed;
  42283. }
  42284. else if (drag)
  42285. {
  42286. this._drag = drag * this.game.time.physicsElapsed;
  42287. if (velocity - this._drag > 0)
  42288. {
  42289. velocity -= this._drag;
  42290. }
  42291. else if (velocity + this._drag < 0)
  42292. {
  42293. velocity += this._drag;
  42294. }
  42295. else
  42296. {
  42297. velocity = 0;
  42298. }
  42299. }
  42300. if (velocity > max)
  42301. {
  42302. velocity = max;
  42303. }
  42304. else if (velocity < -max)
  42305. {
  42306. velocity = -max;
  42307. }
  42308. return velocity;
  42309. },
  42310. /**
  42311. * Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters.
  42312. * You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks.
  42313. * Unlike collide the objects are NOT automatically separated or have any physics applied, they merely test for overlap results.
  42314. * The second parameter can be an array of objects, of differing types.
  42315. * NOTE: This function is not recursive, and will not test against children of objects passed (i.e. Groups within Groups).
  42316. *
  42317. * @method Phaser.Physics.Arcade#overlap
  42318. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
  42319. * @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.
  42320. * @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.
  42321. * @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 processCallback returns true.
  42322. * @param {object} [callbackContext] - The context in which to run the callbacks.
  42323. * @return {boolean} True if an overlap occured otherwise false.
  42324. */
  42325. overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) {
  42326. overlapCallback = overlapCallback || null;
  42327. processCallback = processCallback || null;
  42328. callbackContext = callbackContext || overlapCallback;
  42329. this._result = false;
  42330. this._total = 0;
  42331. if (Array.isArray(object2))
  42332. {
  42333. for (var i = 0, len = object2.length; i < len; i++)
  42334. {
  42335. this.collideHandler(object1, object2[i], overlapCallback, processCallback, callbackContext, true);
  42336. }
  42337. }
  42338. else
  42339. {
  42340. this.collideHandler(object1, object2, overlapCallback, processCallback, callbackContext, true);
  42341. }
  42342. return (this._total > 0);
  42343. },
  42344. /**
  42345. * 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.
  42346. * The second parameter can be an array of objects, of differing types.
  42347. * The objects are also automatically separated. If you don't require separation then use ArcadePhysics.overlap instead.
  42348. * 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,
  42349. * 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.
  42350. * 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.
  42351. * NOTE: This function is not recursive, and will not test against children of objects passed (i.e. Groups or Tilemaps within other Groups).
  42352. *
  42353. * @method Phaser.Physics.Arcade#collide
  42354. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.Tilemap.
  42355. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.Tilemap.
  42356. * @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.
  42357. * @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.
  42358. * @param {object} [callbackContext] - The context in which to run the callbacks.
  42359. * @return {boolean} True if a collision occured otherwise false.
  42360. */
  42361. collide: function (object1, object2, collideCallback, processCallback, callbackContext) {
  42362. collideCallback = collideCallback || null;
  42363. processCallback = processCallback || null;
  42364. callbackContext = callbackContext || collideCallback;
  42365. this._result = false;
  42366. this._total = 0;
  42367. if (Array.isArray(object2))
  42368. {
  42369. for (var i = 0, len = object2.length; i < len; i++)
  42370. {
  42371. this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, false);
  42372. }
  42373. }
  42374. else
  42375. {
  42376. this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, false);
  42377. }
  42378. return (this._total > 0);
  42379. },
  42380. /**
  42381. * Internal collision handler.
  42382. *
  42383. * @method Phaser.Physics.Arcade#collideHandler
  42384. * @private
  42385. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.Tilemap.
  42386. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.Tilemap. Can also be an array of objects to check.
  42387. * @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.
  42388. * @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.
  42389. * @param {object} callbackContext - The context in which to run the callbacks.
  42390. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  42391. */
  42392. collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) {
  42393. // Only collide valid objects
  42394. if (typeof object2 === 'undefined' && (object1.type === Phaser.GROUP || object1.type === Phaser.EMITTER))
  42395. {
  42396. this.collideGroupVsSelf(object1, collideCallback, processCallback, callbackContext, overlapOnly);
  42397. return;
  42398. }
  42399. if (object1 && object2 && object1.exists && object2.exists)
  42400. {
  42401. // SPRITES
  42402. if (object1.type == Phaser.SPRITE || object1.type == Phaser.TILESPRITE)
  42403. {
  42404. if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
  42405. {
  42406. this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
  42407. }
  42408. else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
  42409. {
  42410. this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
  42411. }
  42412. else if (object2.type == Phaser.TILEMAPLAYER)
  42413. {
  42414. this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext);
  42415. }
  42416. }
  42417. // GROUPS
  42418. else if (object1.type == Phaser.GROUP)
  42419. {
  42420. if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
  42421. {
  42422. this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
  42423. }
  42424. else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
  42425. {
  42426. this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
  42427. }
  42428. else if (object2.type == Phaser.TILEMAPLAYER)
  42429. {
  42430. this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext);
  42431. }
  42432. }
  42433. // TILEMAP LAYERS
  42434. else if (object1.type == Phaser.TILEMAPLAYER)
  42435. {
  42436. if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
  42437. {
  42438. this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext);
  42439. }
  42440. else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
  42441. {
  42442. this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext);
  42443. }
  42444. }
  42445. // EMITTER
  42446. else if (object1.type == Phaser.EMITTER)
  42447. {
  42448. if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
  42449. {
  42450. this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
  42451. }
  42452. else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
  42453. {
  42454. this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
  42455. }
  42456. else if (object2.type == Phaser.TILEMAPLAYER)
  42457. {
  42458. this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext);
  42459. }
  42460. }
  42461. }
  42462. },
  42463. /**
  42464. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  42465. *
  42466. * @method Phaser.Physics.Arcade#collideSpriteVsSprite
  42467. * @private
  42468. * @param {Phaser.Sprite} sprite1 - The first sprite to check.
  42469. * @param {Phaser.Sprite} sprite2 - The second sprite to check.
  42470. * @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.
  42471. * @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.
  42472. * @param {object} callbackContext - The context in which to run the callbacks.
  42473. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  42474. * @return {boolean} True if there was a collision, otherwise false.
  42475. */
  42476. collideSpriteVsSprite: function (sprite1, sprite2, collideCallback, processCallback, callbackContext, overlapOnly) {
  42477. if (!sprite1.body || !sprite2.body)
  42478. {
  42479. return false;
  42480. }
  42481. if (this.separate(sprite1.body, sprite2.body, processCallback, callbackContext, overlapOnly))
  42482. {
  42483. if (collideCallback)
  42484. {
  42485. collideCallback.call(callbackContext, sprite1, sprite2);
  42486. }
  42487. this._total++;
  42488. }
  42489. return true;
  42490. },
  42491. /**
  42492. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  42493. *
  42494. * @method Phaser.Physics.Arcade#collideSpriteVsGroup
  42495. * @private
  42496. * @param {Phaser.Sprite} sprite - The sprite to check.
  42497. * @param {Phaser.Group} group - The Group to check.
  42498. * @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.
  42499. * @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.
  42500. * @param {object} callbackContext - The context in which to run the callbacks.
  42501. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  42502. */
  42503. collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) {
  42504. if (group.length === 0 || !sprite.body)
  42505. {
  42506. return;
  42507. }
  42508. // What is the sprite colliding with in the quadtree?
  42509. this.quadTree.clear();
  42510. 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);
  42511. this.quadTree.populate(group);
  42512. this._potentials = this.quadTree.retrieve(sprite);
  42513. for (var i = 0, len = this._potentials.length; i < len; i++)
  42514. {
  42515. // We have our potential suspects, are they in this group?
  42516. if (this.separate(sprite.body, this._potentials[i], processCallback, callbackContext, overlapOnly))
  42517. {
  42518. if (collideCallback)
  42519. {
  42520. collideCallback.call(callbackContext, sprite, this._potentials[i].sprite);
  42521. }
  42522. this._total++;
  42523. }
  42524. }
  42525. },
  42526. /**
  42527. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  42528. *
  42529. * @method Phaser.Physics.Arcade#collideGroupVsSelf
  42530. * @private
  42531. * @param {Phaser.Group} group - The Group to check.
  42532. * @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.
  42533. * @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.
  42534. * @param {object} callbackContext - The context in which to run the callbacks.
  42535. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  42536. * @return {boolean} True if there was a collision, otherwise false.
  42537. */
  42538. collideGroupVsSelf: function (group, collideCallback, processCallback, callbackContext, overlapOnly) {
  42539. if (group.length === 0)
  42540. {
  42541. return;
  42542. }
  42543. var len = group.children.length;
  42544. for (var i = 0; i < len; i++)
  42545. {
  42546. for (var j = i + 1; j <= len; j++)
  42547. {
  42548. if (group.children[i] && group.children[j] && group.children[i].exists && group.children[j].exists)
  42549. {
  42550. this.collideSpriteVsSprite(group.children[i], group.children[j], collideCallback, processCallback, callbackContext, overlapOnly);
  42551. }
  42552. }
  42553. }
  42554. },
  42555. /**
  42556. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  42557. *
  42558. * @method Phaser.Physics.Arcade#collideGroupVsGroup
  42559. * @private
  42560. * @param {Phaser.Group} group1 - The first Group to check.
  42561. * @param {Phaser.Group} group2 - The second Group to check.
  42562. * @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.
  42563. * @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.
  42564. * @param {object} callbackContext - The context in which to run the callbacks.
  42565. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  42566. */
  42567. collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) {
  42568. if (group1.length === 0 || group2.length === 0)
  42569. {
  42570. return;
  42571. }
  42572. for (var i = 0, len = group1.children.length; i < len; i++)
  42573. {
  42574. if (group1.children[i].exists)
  42575. {
  42576. this.collideSpriteVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly);
  42577. }
  42578. }
  42579. },
  42580. /**
  42581. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  42582. *
  42583. * @method Phaser.Physics.Arcade#collideSpriteVsTilemapLayer
  42584. * @private
  42585. * @param {Phaser.Sprite} sprite - The sprite to check.
  42586. * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check.
  42587. * @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.
  42588. * @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.
  42589. * @param {object} callbackContext - The context in which to run the callbacks.
  42590. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  42591. */
  42592. collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext) {
  42593. if (!sprite.body)
  42594. {
  42595. return;
  42596. }
  42597. this._mapData = tilemapLayer.getTiles(
  42598. sprite.body.position.x - sprite.body.tilePadding.x,
  42599. sprite.body.position.y - sprite.body.tilePadding.y,
  42600. sprite.body.width + sprite.body.tilePadding.x,
  42601. sprite.body.height + sprite.body.tilePadding.y,
  42602. false, false);
  42603. if (this._mapData.length === 0)
  42604. {
  42605. return;
  42606. }
  42607. for (var i = 0; i < this._mapData.length; i++)
  42608. {
  42609. if (processCallback)
  42610. {
  42611. if (processCallback.call(callbackContext, sprite, this._mapData[i]))
  42612. {
  42613. if (this.separateTile(i, sprite.body, this._mapData[i]))
  42614. {
  42615. this._total++;
  42616. if (collideCallback)
  42617. {
  42618. collideCallback.call(callbackContext, sprite, this._mapData[i]);
  42619. }
  42620. }
  42621. }
  42622. }
  42623. else
  42624. {
  42625. if (this.separateTile(i, sprite.body, this._mapData[i]))
  42626. {
  42627. this._total++;
  42628. if (collideCallback)
  42629. {
  42630. collideCallback.call(callbackContext, sprite, this._mapData[i]);
  42631. }
  42632. }
  42633. }
  42634. }
  42635. },
  42636. /**
  42637. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  42638. *
  42639. * @private
  42640. * @method Phaser.Physics.Arcade#collideGroupVsTilemapLayer
  42641. * @param {Phaser.Group} group - The Group to check.
  42642. * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check.
  42643. * @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.
  42644. * @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.
  42645. * @param {object} callbackContext - The context in which to run the callbacks.
  42646. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  42647. */
  42648. collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext) {
  42649. if (group.length === 0)
  42650. {
  42651. return;
  42652. }
  42653. for (var i = 0, len = group.children.length; i < len; i++)
  42654. {
  42655. if (group.children[i].exists)
  42656. {
  42657. this.collideSpriteVsTilemapLayer(group.children[i], tilemapLayer, collideCallback, processCallback, callbackContext);
  42658. }
  42659. }
  42660. },
  42661. /**
  42662. * The core separation function to separate two physics bodies.
  42663. *
  42664. * @private
  42665. * @method Phaser.Physics.Arcade#separate
  42666. * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to separate.
  42667. * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to separate.
  42668. * @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.
  42669. * @param {object} [callbackContext] - The context in which to run the process callback.
  42670. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  42671. * @return {boolean} Returns true if the bodies collided, otherwise false.
  42672. */
  42673. separate: function (body1, body2, processCallback, callbackContext, overlapOnly) {
  42674. if (!body1.enable || !body2.enable || !this.intersects(body1, body2))
  42675. {
  42676. return false;
  42677. }
  42678. // They overlap. Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort.
  42679. if (processCallback && processCallback.call(callbackContext, body1.sprite, body2.sprite) === false)
  42680. {
  42681. return false;
  42682. }
  42683. if (overlapOnly)
  42684. {
  42685. // We already know they intersect from the check above, and we don't need separation, so ...
  42686. return true;
  42687. }
  42688. // Do we separate on x or y first?
  42689. // If we weren't having to carry around so much legacy baggage with us, we could do this properly. But alas ...
  42690. if (this.forceX || Math.abs(this.gravity.y + body1.gravity.y) < Math.abs(this.gravity.x + body1.gravity.x))
  42691. {
  42692. this._result = (this.separateX(body1, body2, overlapOnly) || this.separateY(body1, body2, overlapOnly));
  42693. }
  42694. else
  42695. {
  42696. this._result = (this.separateY(body1, body2, overlapOnly) || this.separateX(body1, body2, overlapOnly));
  42697. }
  42698. return this._result;
  42699. },
  42700. /**
  42701. * Check for intersection against two bodies.
  42702. *
  42703. * @method Phaser.Physics.Arcade#intersects
  42704. * @param {Phaser.Physics.Arcade.Body} body1 - The Body object to check.
  42705. * @param {Phaser.Physics.Arcade.Body} body2 - The Body object to check.
  42706. * @return {boolean} True if they intersect, otherwise false.
  42707. */
  42708. intersects: function (body1, body2) {
  42709. if (body1.right <= body2.position.x)
  42710. {
  42711. return false;
  42712. }
  42713. if (body1.bottom <= body2.position.y)
  42714. {
  42715. return false;
  42716. }
  42717. if (body1.position.x >= body2.right)
  42718. {
  42719. return false;
  42720. }
  42721. if (body1.position.y >= body2.bottom)
  42722. {
  42723. return false;
  42724. }
  42725. return true;
  42726. },
  42727. /**
  42728. * The core separation function to separate two physics bodies on the x axis.
  42729. *
  42730. * @private
  42731. * @method Phaser.Physics.Arcade#separateX
  42732. * @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate.
  42733. * @param {Phaser.Physics.Arcade.Body} body2 - The Body object to separate.
  42734. * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place.
  42735. * @return {boolean} Returns true if the bodies were separated, otherwise false.
  42736. */
  42737. separateX: function (body1, body2, overlapOnly) {
  42738. // Can't separate two immovable bodies
  42739. if (body1.immovable && body2.immovable)
  42740. {
  42741. return false;
  42742. }
  42743. this._overlap = 0;
  42744. // Check if the hulls actually overlap
  42745. if (this.intersects(body1, body2))
  42746. {
  42747. this._maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + this.OVERLAP_BIAS;
  42748. if (body1.deltaX() === 0 && body2.deltaX() === 0)
  42749. {
  42750. // They overlap but neither of them are moving
  42751. body1.embedded = true;
  42752. body2.embedded = true;
  42753. }
  42754. else if (body1.deltaX() > body2.deltaX())
  42755. {
  42756. // Body1 is moving right and/or Body2 is moving left
  42757. this._overlap = body1.right - body2.x;
  42758. if ((this._overlap > this._maxOverlap) || body1.checkCollision.right === false || body2.checkCollision.left === false)
  42759. {
  42760. this._overlap = 0;
  42761. }
  42762. else
  42763. {
  42764. body1.touching.none = false;
  42765. body1.touching.right = true;
  42766. body2.touching.none = false;
  42767. body2.touching.left = true;
  42768. }
  42769. }
  42770. else if (body1.deltaX() < body2.deltaX())
  42771. {
  42772. // Body1 is moving left and/or Body2 is moving right
  42773. this._overlap = body1.x - body2.width - body2.x;
  42774. if ((-this._overlap > this._maxOverlap) || body1.checkCollision.left === false || body2.checkCollision.right === false)
  42775. {
  42776. this._overlap = 0;
  42777. }
  42778. else
  42779. {
  42780. body1.touching.none = false;
  42781. body1.touching.left = true;
  42782. body2.touching.none = false;
  42783. body2.touching.right = true;
  42784. }
  42785. }
  42786. // Then adjust their positions and velocities accordingly (if there was any overlap)
  42787. if (this._overlap !== 0)
  42788. {
  42789. body1.overlapX = this._overlap;
  42790. body2.overlapX = this._overlap;
  42791. if (overlapOnly || body1.customSeparateX || body2.customSeparateX)
  42792. {
  42793. return true;
  42794. }
  42795. this._velocity1 = body1.velocity.x;
  42796. this._velocity2 = body2.velocity.x;
  42797. if (!body1.immovable && !body2.immovable)
  42798. {
  42799. this._overlap *= 0.5;
  42800. body1.x = body1.x - this._overlap;
  42801. body2.x += this._overlap;
  42802. this._newVelocity1 = Math.sqrt((this._velocity2 * this._velocity2 * body2.mass) / body1.mass) * ((this._velocity2 > 0) ? 1 : -1);
  42803. this._newVelocity2 = Math.sqrt((this._velocity1 * this._velocity1 * body1.mass) / body2.mass) * ((this._velocity1 > 0) ? 1 : -1);
  42804. this._average = (this._newVelocity1 + this._newVelocity2) * 0.5;
  42805. this._newVelocity1 -= this._average;
  42806. this._newVelocity2 -= this._average;
  42807. body1.velocity.x = this._average + this._newVelocity1 * body1.bounce.x;
  42808. body2.velocity.x = this._average + this._newVelocity2 * body2.bounce.x;
  42809. }
  42810. else if (!body1.immovable)
  42811. {
  42812. body1.x = body1.x - this._overlap;
  42813. body1.velocity.x = this._velocity2 - this._velocity1 * body1.bounce.x;
  42814. }
  42815. else if (!body2.immovable)
  42816. {
  42817. body2.x += this._overlap;
  42818. body2.velocity.x = this._velocity1 - this._velocity2 * body2.bounce.x;
  42819. }
  42820. return true;
  42821. }
  42822. }
  42823. return false;
  42824. },
  42825. /**
  42826. * The core separation function to separate two physics bodies on the y axis.
  42827. *
  42828. * @private
  42829. * @method Phaser.Physics.Arcade#separateY
  42830. * @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate.
  42831. * @param {Phaser.Physics.Arcade.Body} body2 - The Body object to separate.
  42832. * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place.
  42833. * @return {boolean} Returns true if the bodies were separated, otherwise false.
  42834. */
  42835. separateY: function (body1, body2, overlapOnly) {
  42836. // Can't separate two immovable or non-existing bodys
  42837. if (body1.immovable && body2.immovable)
  42838. {
  42839. return false;
  42840. }
  42841. this._overlap = 0;
  42842. // Check if the hulls actually overlap
  42843. if (this.intersects(body1, body2))
  42844. {
  42845. this._maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + this.OVERLAP_BIAS;
  42846. if (body1.deltaY() === 0 && body2.deltaY() === 0)
  42847. {
  42848. // They overlap but neither of them are moving
  42849. body1.embedded = true;
  42850. body2.embedded = true;
  42851. }
  42852. else if (body1.deltaY() > body2.deltaY())
  42853. {
  42854. // Body1 is moving down and/or Body2 is moving up
  42855. this._overlap = body1.bottom - body2.y;
  42856. if ((this._overlap > this._maxOverlap) || body1.checkCollision.down === false || body2.checkCollision.up === false)
  42857. {
  42858. this._overlap = 0;
  42859. }
  42860. else
  42861. {
  42862. body1.touching.none = false;
  42863. body1.touching.down = true;
  42864. body2.touching.none = false;
  42865. body2.touching.up = true;
  42866. }
  42867. }
  42868. else if (body1.deltaY() < body2.deltaY())
  42869. {
  42870. // Body1 is moving up and/or Body2 is moving down
  42871. this._overlap = body1.y - body2.bottom;
  42872. if ((-this._overlap > this._maxOverlap) || body1.checkCollision.up === false || body2.checkCollision.down === false)
  42873. {
  42874. this._overlap = 0;
  42875. }
  42876. else
  42877. {
  42878. body1.touching.none = false;
  42879. body1.touching.up = true;
  42880. body2.touching.none = false;
  42881. body2.touching.down = true;
  42882. }
  42883. }
  42884. // Then adjust their positions and velocities accordingly (if there was any overlap)
  42885. if (this._overlap !== 0)
  42886. {
  42887. body1.overlapY = this._overlap;
  42888. body2.overlapY = this._overlap;
  42889. if (overlapOnly || body1.customSeparateY || body2.customSeparateY)
  42890. {
  42891. return true;
  42892. }
  42893. this._velocity1 = body1.velocity.y;
  42894. this._velocity2 = body2.velocity.y;
  42895. if (!body1.immovable && !body2.immovable)
  42896. {
  42897. this._overlap *= 0.5;
  42898. body1.y = body1.y - this._overlap;
  42899. body2.y += this._overlap;
  42900. this._newVelocity1 = Math.sqrt((this._velocity2 * this._velocity2 * body2.mass) / body1.mass) * ((this._velocity2 > 0) ? 1 : -1);
  42901. this._newVelocity2 = Math.sqrt((this._velocity1 * this._velocity1 * body1.mass) / body2.mass) * ((this._velocity1 > 0) ? 1 : -1);
  42902. this._average = (this._newVelocity1 + this._newVelocity2) * 0.5;
  42903. this._newVelocity1 -= this._average;
  42904. this._newVelocity2 -= this._average;
  42905. body1.velocity.y = this._average + this._newVelocity1 * body1.bounce.y;
  42906. body2.velocity.y = this._average + this._newVelocity2 * body2.bounce.y;
  42907. }
  42908. else if (!body1.immovable)
  42909. {
  42910. body1.y = body1.y - this._overlap;
  42911. body1.velocity.y = this._velocity2 - this._velocity1 * body1.bounce.y;
  42912. // This is special case code that handles things like horizontal moving platforms you can ride
  42913. if (body2.moves)
  42914. {
  42915. body1.x += body2.x - body2.prev.x;
  42916. }
  42917. }
  42918. else if (!body2.immovable)
  42919. {
  42920. body2.y += this._overlap;
  42921. body2.velocity.y = this._velocity1 - this._velocity2 * body2.bounce.y;
  42922. // This is special case code that handles things like horizontal moving platforms you can ride
  42923. if (body1.moves)
  42924. {
  42925. body2.x += body1.x - body1.prev.x;
  42926. }
  42927. }
  42928. return true;
  42929. }
  42930. }
  42931. return false;
  42932. },
  42933. /**
  42934. * The core separation function to separate a physics body and a tile.
  42935. *
  42936. * @private
  42937. * @method Phaser.Physics.Arcade#separateTile
  42938. * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
  42939. * @param {Phaser.Tile} tile - The tile to collide against.
  42940. * @return {boolean} Returns true if the body was separated, otherwise false.
  42941. */
  42942. separateTile: function (i, body, tile) {
  42943. // We re-check for collision in case body was separated in a previous step
  42944. if (!body.enable || !tile.intersects(body.position.x, body.position.y, body.right, body.bottom))
  42945. {
  42946. // no collision so bail out (separted in a previous step)
  42947. return false;
  42948. }
  42949. // They overlap. Any custom callbacks?
  42950. // A local callback always takes priority over a layer level callback
  42951. if (tile.collisionCallback && !tile.collisionCallback.call(tile.collisionCallbackContext, body.sprite, tile))
  42952. {
  42953. // If it returns true then we can carry on, otherwise we should abort.
  42954. return false;
  42955. }
  42956. else if (tile.layer.callbacks[tile.index] && !tile.layer.callbacks[tile.index].callback.call(tile.layer.callbacks[tile.index].callbackContext, body.sprite, tile))
  42957. {
  42958. // If it returns true then we can carry on, otherwise we should abort.
  42959. return false;
  42960. }
  42961. // We don't need to go any further if this tile doesn't actually separate
  42962. if (!tile.faceLeft && !tile.faceRight && !tile.faceTop && !tile.faceBottom)
  42963. {
  42964. // This could happen if the tile was meant to be collided with re: a callback, but otherwise isn't needed for separation
  42965. return false;
  42966. }
  42967. var ox = 0;
  42968. var oy = 0;
  42969. var minX = 0;
  42970. var minY = 1;
  42971. if (body.deltaAbsX() > body.deltaAbsY())
  42972. {
  42973. // Moving faster horizontally, check X axis first
  42974. minX = -1;
  42975. }
  42976. else if (body.deltaAbsX() < body.deltaAbsY())
  42977. {
  42978. // Moving faster vertically, check Y axis first
  42979. minY = -1;
  42980. }
  42981. if (body.deltaX() !== 0 && body.deltaY() !== 0 && (tile.faceLeft || tile.faceRight) && (tile.faceTop || tile.faceBottom))
  42982. {
  42983. // We only need do this if both axis have checking faces AND we're moving in both directions
  42984. minX = Math.min(Math.abs(body.position.x - tile.right), Math.abs(body.right - tile.left));
  42985. minY = Math.min(Math.abs(body.position.y - tile.bottom), Math.abs(body.bottom - tile.top));
  42986. }
  42987. if (minX < minY)
  42988. {
  42989. if (tile.faceLeft || tile.faceRight)
  42990. {
  42991. ox = this.tileCheckX(body, tile);
  42992. // That's horizontal done, check if we still intersects? If not then we can return now
  42993. if (ox !== 0 && !tile.intersects(body.position.x, body.position.y, body.right, body.bottom))
  42994. {
  42995. return true;
  42996. }
  42997. }
  42998. if (tile.faceTop || tile.faceBottom)
  42999. {
  43000. oy = this.tileCheckY(body, tile);
  43001. }
  43002. }
  43003. else
  43004. {
  43005. if (tile.faceTop || tile.faceBottom)
  43006. {
  43007. oy = this.tileCheckY(body, tile);
  43008. // That's vertical done, check if we still intersects? If not then we can return now
  43009. if (oy !== 0 && !tile.intersects(body.position.x, body.position.y, body.right, body.bottom))
  43010. {
  43011. return true;
  43012. }
  43013. }
  43014. if (tile.faceLeft || tile.faceRight)
  43015. {
  43016. ox = this.tileCheckX(body, tile);
  43017. }
  43018. }
  43019. return (ox !== 0 || oy !== 0);
  43020. },
  43021. /**
  43022. * Check the body against the given tile on the X axis.
  43023. *
  43024. * @private
  43025. * @method Phaser.Physics.Arcade#tileCheckX
  43026. * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
  43027. * @param {Phaser.Tile} tile - The tile to check.
  43028. * @return {number} The amount of separation that occured.
  43029. */
  43030. tileCheckX: function (body, tile) {
  43031. var ox = 0;
  43032. if (body.deltaX() < 0 && !body.blocked.left && tile.collideRight && body.checkCollision.left)
  43033. {
  43034. // Body is moving LEFT
  43035. if (tile.faceRight && body.x < tile.right)
  43036. {
  43037. ox = body.x - tile.right;
  43038. if (ox < -this.TILE_BIAS)
  43039. {
  43040. ox = 0;
  43041. }
  43042. }
  43043. }
  43044. else if (body.deltaX() > 0 && !body.blocked.right && tile.collideLeft && body.checkCollision.right)
  43045. {
  43046. // Body is moving RIGHT
  43047. if (tile.faceLeft && body.right > tile.left)
  43048. {
  43049. ox = body.right - tile.left;
  43050. if (ox > this.TILE_BIAS)
  43051. {
  43052. ox = 0;
  43053. }
  43054. }
  43055. }
  43056. if (ox !== 0)
  43057. {
  43058. this.processTileSeparationX(body, ox);
  43059. }
  43060. return ox;
  43061. },
  43062. /**
  43063. * Check the body against the given tile on the Y axis.
  43064. *
  43065. * @private
  43066. * @method Phaser.Physics.Arcade#tileCheckY
  43067. * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
  43068. * @param {Phaser.Tile} tile - The tile to check.
  43069. * @return {number} The amount of separation that occured.
  43070. */
  43071. tileCheckY: function (body, tile) {
  43072. var oy = 0;
  43073. if (body.deltaY() < 0 && !body.blocked.up && tile.collideDown && body.checkCollision.up)
  43074. {
  43075. // Body is moving UP
  43076. if (tile.faceBottom && body.y < tile.bottom)
  43077. {
  43078. oy = body.y - tile.bottom;
  43079. if (oy < -this.TILE_BIAS)
  43080. {
  43081. oy = 0;
  43082. }
  43083. }
  43084. }
  43085. else if (body.deltaY() > 0 && !body.blocked.down && tile.collideUp && body.checkCollision.down)
  43086. {
  43087. // Body is moving DOWN
  43088. if (tile.faceTop && body.bottom > tile.top)
  43089. {
  43090. oy = body.bottom - tile.top;
  43091. if (oy > this.TILE_BIAS)
  43092. {
  43093. oy = 0;
  43094. }
  43095. }
  43096. }
  43097. if (oy !== 0)
  43098. {
  43099. this.processTileSeparationY(body, oy);
  43100. }
  43101. return oy;
  43102. },
  43103. /**
  43104. * Internal function to process the separation of a physics body from a tile.
  43105. *
  43106. * @private
  43107. * @method Phaser.Physics.Arcade#processTileSeparationX
  43108. * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
  43109. * @param {number} x - The x separation amount.
  43110. * @return {boolean} Returns true as a pass-thru to the separateTile method.
  43111. */
  43112. processTileSeparationX: function (body, x) {
  43113. if (x < 0)
  43114. {
  43115. body.blocked.left = true;
  43116. }
  43117. else if (x > 0)
  43118. {
  43119. body.blocked.right = true;
  43120. }
  43121. body.position.x -= x;
  43122. if (body.bounce.x === 0)
  43123. {
  43124. body.velocity.x = 0;
  43125. }
  43126. else
  43127. {
  43128. body.velocity.x = -body.velocity.x * body.bounce.x;
  43129. }
  43130. },
  43131. /**
  43132. * Internal function to process the separation of a physics body from a tile.
  43133. *
  43134. * @private
  43135. * @method Phaser.Physics.Arcade#processTileSeparationY
  43136. * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
  43137. * @param {number} y - The y separation amount.
  43138. */
  43139. processTileSeparationY: function (body, y) {
  43140. if (y < 0)
  43141. {
  43142. body.blocked.up = true;
  43143. }
  43144. else if (y > 0)
  43145. {
  43146. body.blocked.down = true;
  43147. }
  43148. body.position.y -= y;
  43149. if (body.bounce.y === 0)
  43150. {
  43151. body.velocity.y = 0;
  43152. }
  43153. else
  43154. {
  43155. body.velocity.y = -body.velocity.y * body.bounce.y;
  43156. }
  43157. },
  43158. /**
  43159. * Given a Group and a Pointer this will check to see which Group children overlap with the Pointer coordinates.
  43160. * Each child will be sent to the given callback for further processing.
  43161. * Note that the children are not checked for depth order, but simply if they overlap the Pointer or not.
  43162. *
  43163. * @method Phaser.Physics.Arcade#getObjectsUnderPointer
  43164. * @param {Phaser.Pointer} pointer - The Pointer to check.
  43165. * @param {Phaser.Group} group - The Group to check.
  43166. * @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.
  43167. * @param {object} [callbackContext] - The context in which to run the callback.
  43168. * @return {array} An array of the Sprites from the Group that overlapped the Pointer coordinates.
  43169. */
  43170. getObjectsUnderPointer: function (pointer, group, callback, callbackContext) {
  43171. if (group.length === 0 || !pointer.exists)
  43172. {
  43173. return;
  43174. }
  43175. this.quadTree.clear();
  43176. 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);
  43177. this.quadTree.populate(group);
  43178. var rect = new Phaser.Rectangle(pointer.x, pointer.y, 1, 1);
  43179. var output = [];
  43180. this._potentials = this.quadTree.retrieve(rect);
  43181. for (var i = 0, len = this._potentials.length; i < len; i++)
  43182. {
  43183. if (this._potentials[i].hitTest(pointer.x, pointer.y))
  43184. {
  43185. if (callback)
  43186. {
  43187. callback.call(callbackContext, pointer, this._potentials[i].sprite);
  43188. }
  43189. output.push(this._potentials[i].sprite);
  43190. }
  43191. }
  43192. return output;
  43193. },
  43194. /**
  43195. * Move the given display object towards the destination object at a steady velocity.
  43196. * 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.
  43197. * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
  43198. * 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.
  43199. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  43200. * 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)
  43201. *
  43202. * @method Phaser.Physics.Arcade#moveToObject
  43203. * @param {any} displayObject - The display object to move.
  43204. * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties.
  43205. * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
  43206. * @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.
  43207. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
  43208. */
  43209. moveToObject: function (displayObject, destination, speed, maxTime) {
  43210. if (typeof speed === 'undefined') { speed = 60; }
  43211. if (typeof maxTime === 'undefined') { maxTime = 0; }
  43212. this._angle = Math.atan2(destination.y - displayObject.y, destination.x - displayObject.x);
  43213. if (maxTime > 0)
  43214. {
  43215. // We know how many pixels we need to move, but how fast?
  43216. speed = this.distanceBetween(displayObject, destination) / (maxTime / 1000);
  43217. }
  43218. displayObject.body.velocity.x = Math.cos(this._angle) * speed;
  43219. displayObject.body.velocity.y = Math.sin(this._angle) * speed;
  43220. return this._angle;
  43221. },
  43222. /**
  43223. * Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer.
  43224. * 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.
  43225. * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
  43226. * 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.
  43227. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  43228. *
  43229. * @method Phaser.Physics.Arcade#moveToPointer
  43230. * @param {any} displayObject - The display object to move.
  43231. * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
  43232. * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer.
  43233. * @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.
  43234. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
  43235. */
  43236. moveToPointer: function (displayObject, speed, pointer, maxTime) {
  43237. if (typeof speed === 'undefined') { speed = 60; }
  43238. pointer = pointer || this.game.input.activePointer;
  43239. if (typeof maxTime === 'undefined') { maxTime = 0; }
  43240. this._angle = this.angleToPointer(displayObject, pointer);
  43241. if (maxTime > 0)
  43242. {
  43243. // We know how many pixels we need to move, but how fast?
  43244. speed = this.distanceToPointer(displayObject, pointer) / (maxTime / 1000);
  43245. }
  43246. displayObject.body.velocity.x = Math.cos(this._angle) * speed;
  43247. displayObject.body.velocity.y = Math.sin(this._angle) * speed;
  43248. return this._angle;
  43249. },
  43250. /**
  43251. * Move the given display object towards the x/y coordinates at a steady velocity.
  43252. * 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.
  43253. * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
  43254. * 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.
  43255. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  43256. * 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)
  43257. *
  43258. * @method Phaser.Physics.Arcade#moveToXY
  43259. * @param {any} displayObject - The display object to move.
  43260. * @param {number} x - The x coordinate to move towards.
  43261. * @param {number} y - The y coordinate to move towards.
  43262. * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
  43263. * @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.
  43264. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
  43265. */
  43266. moveToXY: function (displayObject, x, y, speed, maxTime) {
  43267. if (typeof speed === 'undefined') { speed = 60; }
  43268. if (typeof maxTime === 'undefined') { maxTime = 0; }
  43269. this._angle = Math.atan2(y - displayObject.y, x - displayObject.x);
  43270. if (maxTime > 0)
  43271. {
  43272. // We know how many pixels we need to move, but how fast?
  43273. speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000);
  43274. }
  43275. displayObject.body.velocity.x = Math.cos(this._angle) * speed;
  43276. displayObject.body.velocity.y = Math.sin(this._angle) * speed;
  43277. return this._angle;
  43278. },
  43279. /**
  43280. * 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.
  43281. * 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.
  43282. *
  43283. * @method Phaser.Physics.Arcade#velocityFromAngle
  43284. * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative)
  43285. * @param {number} [speed=60] - The speed it will move, in pixels per second sq.
  43286. * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity.
  43287. * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value.
  43288. */
  43289. velocityFromAngle: function (angle, speed, point) {
  43290. if (typeof speed === 'undefined') { speed = 60; }
  43291. point = point || new Phaser.Point();
  43292. return point.setTo((Math.cos(this.game.math.degToRad(angle)) * speed), (Math.sin(this.game.math.degToRad(angle)) * speed));
  43293. },
  43294. /**
  43295. * 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.
  43296. * 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.
  43297. *
  43298. * @method Phaser.Physics.Arcade#velocityFromRotation
  43299. * @param {number} rotation - The angle in radians.
  43300. * @param {number} [speed=60] - The speed it will move, in pixels per second sq.
  43301. * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity.
  43302. * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value.
  43303. */
  43304. velocityFromRotation: function (rotation, speed, point) {
  43305. if (typeof speed === 'undefined') { speed = 60; }
  43306. point = point || new Phaser.Point();
  43307. return point.setTo((Math.cos(rotation) * speed), (Math.sin(rotation) * speed));
  43308. },
  43309. /**
  43310. * 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.
  43311. * 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.
  43312. *
  43313. * @method Phaser.Physics.Arcade#accelerationFromRotation
  43314. * @param {number} rotation - The angle in radians.
  43315. * @param {number} [speed=60] - The speed it will move, in pixels per second sq.
  43316. * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated acceleration.
  43317. * @return {Phaser.Point} - A Point where point.x contains the acceleration x value and point.y contains the acceleration y value.
  43318. */
  43319. accelerationFromRotation: function (rotation, speed, point) {
  43320. if (typeof speed === 'undefined') { speed = 60; }
  43321. point = point || new Phaser.Point();
  43322. return point.setTo((Math.cos(rotation) * speed), (Math.sin(rotation) * speed));
  43323. },
  43324. /**
  43325. * 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.)
  43326. * You must give a maximum speed value, beyond which the display object won't go any faster.
  43327. * 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.
  43328. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  43329. *
  43330. * @method Phaser.Physics.Arcade#accelerateToObject
  43331. * @param {any} displayObject - The display object to move.
  43332. * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties.
  43333. * @param {number} [speed=60] - The speed it will accelerate in pixels per second.
  43334. * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
  43335. * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
  43336. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
  43337. */
  43338. accelerateToObject: function (displayObject, destination, speed, xSpeedMax, ySpeedMax) {
  43339. if (typeof speed === 'undefined') { speed = 60; }
  43340. if (typeof xSpeedMax === 'undefined') { xSpeedMax = 1000; }
  43341. if (typeof ySpeedMax === 'undefined') { ySpeedMax = 1000; }
  43342. this._angle = this.angleBetween(displayObject, destination);
  43343. displayObject.body.acceleration.setTo(Math.cos(this._angle) * speed, Math.sin(this._angle) * speed);
  43344. displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
  43345. return this._angle;
  43346. },
  43347. /**
  43348. * 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.)
  43349. * You must give a maximum speed value, beyond which the display object won't go any faster.
  43350. * 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.
  43351. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  43352. *
  43353. * @method Phaser.Physics.Arcade#accelerateToPointer
  43354. * @param {any} displayObject - The display object to move.
  43355. * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer.
  43356. * @param {number} [speed=60] - The speed it will accelerate in pixels per second.
  43357. * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
  43358. * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
  43359. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
  43360. */
  43361. accelerateToPointer: function (displayObject, pointer, speed, xSpeedMax, ySpeedMax) {
  43362. if (typeof speed === 'undefined') { speed = 60; }
  43363. if (typeof pointer === 'undefined') { pointer = this.game.input.activePointer; }
  43364. if (typeof xSpeedMax === 'undefined') { xSpeedMax = 1000; }
  43365. if (typeof ySpeedMax === 'undefined') { ySpeedMax = 1000; }
  43366. this._angle = this.angleToPointer(displayObject, pointer);
  43367. displayObject.body.acceleration.setTo(Math.cos(this._angle) * speed, Math.sin(this._angle) * speed);
  43368. displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
  43369. return this._angle;
  43370. },
  43371. /**
  43372. * 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.)
  43373. * You must give a maximum speed value, beyond which the display object won't go any faster.
  43374. * 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.
  43375. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  43376. *
  43377. * @method Phaser.Physics.Arcade#accelerateToXY
  43378. * @param {any} displayObject - The display object to move.
  43379. * @param {number} x - The x coordinate to accelerate towards.
  43380. * @param {number} y - The y coordinate to accelerate towards.
  43381. * @param {number} [speed=60] - The speed it will accelerate in pixels per second.
  43382. * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
  43383. * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
  43384. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
  43385. */
  43386. accelerateToXY: function (displayObject, x, y, speed, xSpeedMax, ySpeedMax) {
  43387. if (typeof speed === 'undefined') { speed = 60; }
  43388. if (typeof xSpeedMax === 'undefined') { xSpeedMax = 1000; }
  43389. if (typeof ySpeedMax === 'undefined') { ySpeedMax = 1000; }
  43390. this._angle = this.angleToXY(displayObject, x, y);
  43391. displayObject.body.acceleration.setTo(Math.cos(this._angle) * speed, Math.sin(this._angle) * speed);
  43392. displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
  43393. return this._angle;
  43394. },
  43395. /**
  43396. * Find the distance between two display objects (like Sprites).
  43397. *
  43398. * @method Phaser.Physics.Arcade#distanceBetween
  43399. * @param {any} source - The Display Object to test from.
  43400. * @param {any} target - The Display Object to test to.
  43401. * @return {number} The distance between the source and target objects.
  43402. */
  43403. distanceBetween: function (source, target) {
  43404. this._dx = source.x - target.x;
  43405. this._dy = source.y - target.y;
  43406. return Math.sqrt(this._dx * this._dx + this._dy * this._dy);
  43407. },
  43408. /**
  43409. * Find the distance between a display object (like a Sprite) and the given x/y coordinates.
  43410. * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed.
  43411. * If you need to calculate from the center of a display object instead use the method distanceBetweenCenters()
  43412. *
  43413. * @method Phaser.Physics.Arcade#distanceToXY
  43414. * @param {any} displayObject - The Display Object to test from.
  43415. * @param {number} x - The x coordinate to move towards.
  43416. * @param {number} y - The y coordinate to move towards.
  43417. * @return {number} The distance between the object and the x/y coordinates.
  43418. */
  43419. distanceToXY: function (displayObject, x, y) {
  43420. this._dx = displayObject.x - x;
  43421. this._dy = displayObject.y - y;
  43422. return Math.sqrt(this._dx * this._dx + this._dy * this._dy);
  43423. },
  43424. /**
  43425. * Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used.
  43426. * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed.
  43427. * If you need to calculate from the center of a display object instead use the method distanceBetweenCenters()
  43428. *
  43429. * @method Phaser.Physics.Arcade#distanceToPointer
  43430. * @param {any} displayObject - The Display Object to test from.
  43431. * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used.
  43432. * @return {number} The distance between the object and the Pointer.
  43433. */
  43434. distanceToPointer: function (displayObject, pointer) {
  43435. pointer = pointer || this.game.input.activePointer;
  43436. this._dx = displayObject.x - pointer.x;
  43437. this._dy = displayObject.y - pointer.y;
  43438. return Math.sqrt(this._dx * this._dx + this._dy * this._dy);
  43439. },
  43440. /**
  43441. * Find the angle in radians between two display objects (like Sprites).
  43442. *
  43443. * @method Phaser.Physics.Arcade#angleBetween
  43444. * @param {any} source - The Display Object to test from.
  43445. * @param {any} target - The Display Object to test to.
  43446. * @return {number} The angle in radians between the source and target display objects.
  43447. */
  43448. angleBetween: function (source, target) {
  43449. this._dx = target.x - source.x;
  43450. this._dy = target.y - source.y;
  43451. return Math.atan2(this._dy, this._dx);
  43452. },
  43453. /**
  43454. * Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate.
  43455. *
  43456. * @method Phaser.Physics.Arcade#angleToXY
  43457. * @param {any} displayObject - The Display Object to test from.
  43458. * @param {number} x - The x coordinate to get the angle to.
  43459. * @param {number} y - The y coordinate to get the angle to.
  43460. * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y
  43461. */
  43462. angleToXY: function (displayObject, x, y) {
  43463. this._dx = x - displayObject.x;
  43464. this._dy = y - displayObject.y;
  43465. return Math.atan2(this._dy, this._dx);
  43466. },
  43467. /**
  43468. * Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account.
  43469. *
  43470. * @method Phaser.Physics.Arcade#angleToPointer
  43471. * @param {any} displayObject - The Display Object to test from.
  43472. * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used.
  43473. * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y
  43474. */
  43475. angleToPointer: function (displayObject, pointer) {
  43476. pointer = pointer || this.game.input.activePointer;
  43477. this._dx = pointer.worldX - displayObject.x;
  43478. this._dy = pointer.worldY - displayObject.y;
  43479. return Math.atan2(this._dy, this._dx);
  43480. }
  43481. };
  43482. /**
  43483. * @author Richard Davey <rich@photonstorm.com>
  43484. * @copyright 2014 Photon Storm Ltd.
  43485. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  43486. */
  43487. /**
  43488. * The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than
  43489. * the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body.
  43490. *
  43491. * @class Phaser.Physics.Arcade.Body
  43492. * @classdesc Arcade Physics Body Constructor
  43493. * @constructor
  43494. * @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to.
  43495. */
  43496. Phaser.Physics.Arcade.Body = function (sprite) {
  43497. /**
  43498. * @property {Phaser.Sprite} sprite - Reference to the parent Sprite.
  43499. */
  43500. this.sprite = sprite;
  43501. /**
  43502. * @property {Phaser.Game} game - Local reference to game.
  43503. */
  43504. this.game = sprite.game;
  43505. /**
  43506. * @property {number} type - The type of physics system this body belongs to.
  43507. */
  43508. this.type = Phaser.Physics.ARCADE;
  43509. /**
  43510. * @property {boolean} enable - A disabled body won't be checked for any form of collision or overlap or have its pre/post updates run.
  43511. * @default
  43512. */
  43513. this.enable = true;
  43514. /**
  43515. * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position.
  43516. */
  43517. this.offset = new Phaser.Point();
  43518. /**
  43519. * @property {Phaser.Point} position - The position of the physics body.
  43520. * @readonly
  43521. */
  43522. this.position = new Phaser.Point(sprite.x, sprite.y);
  43523. /**
  43524. * @property {Phaser.Point} prev - The previous position of the physics body.
  43525. * @readonly
  43526. */
  43527. this.prev = new Phaser.Point(this.position.x, this.position.y);
  43528. /**
  43529. * @property {boolean} allowRotation - Allow this Body to be rotated? (via angularVelocity, etc)
  43530. * @default
  43531. */
  43532. this.allowRotation = true;
  43533. /**
  43534. * @property {number} rotation - The amount the Body is rotated.
  43535. */
  43536. this.rotation = sprite.rotation;
  43537. /**
  43538. * @property {number} preRotation - The previous rotation of the physics body.
  43539. * @readonly
  43540. */
  43541. this.preRotation = sprite.rotation;
  43542. /**
  43543. * @property {number} sourceWidth - The un-scaled original size.
  43544. * @readonly
  43545. */
  43546. this.sourceWidth = sprite.texture.frame.width;
  43547. /**
  43548. * @property {number} sourceHeight - The un-scaled original size.
  43549. * @readonly
  43550. */
  43551. this.sourceHeight = sprite.texture.frame.height;
  43552. /**
  43553. * @property {number} width - The calculated width of the physics body.
  43554. */
  43555. this.width = sprite.width;
  43556. /**
  43557. * @property .numInternal ID cache
  43558. */
  43559. this.height = sprite.height;
  43560. /**
  43561. * @property {number} halfWidth - The calculated width / 2 of the physics body.
  43562. */
  43563. this.halfWidth = Math.abs(sprite.width / 2);
  43564. /**
  43565. * @property {number} halfHeight - The calculated height / 2 of the physics body.
  43566. */
  43567. this.halfHeight = Math.abs(sprite.height / 2);
  43568. /**
  43569. * @property {Phaser.Point} center - The center coordinate of the Physics Body.
  43570. */
  43571. this.center = new Phaser.Point(sprite.x + this.halfWidth, sprite.y + this.halfHeight);
  43572. /**
  43573. * @property {Phaser.Point} velocity - The velocity in pixels per second sq. of the Body.
  43574. */
  43575. this.velocity = new Phaser.Point();
  43576. /**
  43577. * @property {Phaser.Point} newVelocity - New velocity.
  43578. * @readonly
  43579. */
  43580. this.newVelocity = new Phaser.Point(0, 0);
  43581. /**
  43582. * @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.
  43583. */
  43584. this.deltaMax = new Phaser.Point(0, 0);
  43585. /**
  43586. * @property {Phaser.Point} acceleration - The velocity in pixels per second sq. of the Body.
  43587. */
  43588. this.acceleration = new Phaser.Point();
  43589. /**
  43590. * @property {Phaser.Point} drag - The drag applied to the motion of the Body.
  43591. */
  43592. this.drag = new Phaser.Point();
  43593. /**
  43594. * @property {boolean} allowGravity - Allow this Body to be influenced by gravity? Either world or local.
  43595. * @default
  43596. */
  43597. this.allowGravity = true;
  43598. /**
  43599. * @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.
  43600. */
  43601. this.gravity = new Phaser.Point(0, 0);
  43602. /**
  43603. * @property {Phaser.Point} bounce - The elasticitiy of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity.
  43604. */
  43605. this.bounce = new Phaser.Point();
  43606. /**
  43607. * @property {Phaser.Point} maxVelocity - The maximum velocity in pixels per second sq. that the Body can reach.
  43608. * @default
  43609. */
  43610. this.maxVelocity = new Phaser.Point(10000, 10000);
  43611. /**
  43612. * @property {number} angularVelocity - The angular velocity in pixels per second sq. of the Body.
  43613. * @default
  43614. */
  43615. this.angularVelocity = 0;
  43616. /**
  43617. * @property {number} angularAcceleration - The angular acceleration in pixels per second sq. of the Body.
  43618. * @default
  43619. */
  43620. this.angularAcceleration = 0;
  43621. /**
  43622. * @property {number} angularDrag - The angular drag applied to the rotation of the Body.
  43623. * @default
  43624. */
  43625. this.angularDrag = 0;
  43626. /**
  43627. * @property {number} maxAngular - The maximum angular velocity in pixels per second sq. that the Body can reach.
  43628. * @default
  43629. */
  43630. this.maxAngular = 1000;
  43631. /**
  43632. * @property {number} mass - The mass of the Body.
  43633. * @default
  43634. */
  43635. this.mass = 1;
  43636. /**
  43637. * @property {number} angle - The angle of the Body in radians as calculated by its velocity, rather than its visual angle.
  43638. * @readonly
  43639. */
  43640. this.angle = 0;
  43641. /**
  43642. * @property {number} speed - The speed of the Body as calculated by its velocity.
  43643. * @readonly
  43644. */
  43645. this.speed = 0;
  43646. /**
  43647. * @property {number} facing - A const reference to the direction the Body is traveling or facing.
  43648. * @default
  43649. */
  43650. this.facing = Phaser.NONE;
  43651. /**
  43652. * @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies.
  43653. * @default
  43654. */
  43655. this.immovable = false;
  43656. /**
  43657. * 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
  43658. * actually changes, then you should set Body.moves = false. Otherwise it will most likely fly off the screen.
  43659. * If you want the physics system to move the body around, then set moves to true.
  43660. * @property {boolean} moves - Set to true to allow the Physics system to move this Body, other false to move it manually.
  43661. * @default
  43662. */
  43663. this.moves = true;
  43664. /**
  43665. * This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate.
  43666. * Used in combination with your own collision processHandler you can create whatever type of collision response you need.
  43667. * @property {boolean} customSeparateX - Use a custom separation system or the built-in one?
  43668. * @default
  43669. */
  43670. this.customSeparateX = false;
  43671. /**
  43672. * This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate.
  43673. * Used in combination with your own collision processHandler you can create whatever type of collision response you need.
  43674. * @property {boolean} customSeparateY - Use a custom separation system or the built-in one?
  43675. * @default
  43676. */
  43677. this.customSeparateY = false;
  43678. /**
  43679. * When this body collides with another, the amount of overlap is stored here.
  43680. * @property {number} overlapX - The amount of horizontal overlap during the collision.
  43681. */
  43682. this.overlapX = 0;
  43683. /**
  43684. * When this body collides with another, the amount of overlap is stored here.
  43685. * @property {number} overlapY - The amount of vertical overlap during the collision.
  43686. */
  43687. this.overlapY = 0;
  43688. /**
  43689. * 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.
  43690. * @property {boolean} embedded - Body embed value.
  43691. */
  43692. this.embedded = false;
  43693. /**
  43694. * 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.
  43695. * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds?
  43696. */
  43697. this.collideWorldBounds = false;
  43698. /**
  43699. * Set the checkCollision properties to control which directions collision is processed for this Body.
  43700. * For example checkCollision.up = false means it won't collide when the collision happened while moving up.
  43701. * @property {object} checkCollision - An object containing allowed collision.
  43702. */
  43703. this.checkCollision = { none: false, any: true, up: true, down: true, left: true, right: true };
  43704. /**
  43705. * This object is populated with boolean values when the Body collides with another.
  43706. * touching.up = true means the collision happened to the top of this Body for example.
  43707. * @property {object} touching - An object containing touching results.
  43708. */
  43709. this.touching = { none: true, up: false, down: false, left: false, right: false };
  43710. /**
  43711. * This object is populated with previous touching values from the bodies previous collision.
  43712. * @property {object} wasTouching - An object containing previous touching results.
  43713. */
  43714. this.wasTouching = { none: true, up: false, down: false, left: false, right: false };
  43715. /**
  43716. * This object is populated with boolean values when the Body collides with the World bounds or a Tile.
  43717. * For example if blocked.up is true then the Body cannot move up.
  43718. * @property {object} blocked - An object containing on which faces this Body is blocked from moving, if any.
  43719. */
  43720. this.blocked = { up: false, down: false, left: false, right: false };
  43721. /**
  43722. * 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.
  43723. * Set this padding value to add extra padding to its bounds. tilePadding.x applied to its width, y to its height.
  43724. * @property {Phaser.Point} tilePadding - Extra padding to be added to this sprites dimensions when checking for tile collision.
  43725. */
  43726. this.tilePadding = new Phaser.Point();
  43727. /**
  43728. * @property {number} phaser - Is this Body in a preUpdate (1) or postUpdate (2) state?
  43729. */
  43730. this.phase = 0;
  43731. /**
  43732. * @property {boolean} _reset - Internal cache var.
  43733. * @private
  43734. */
  43735. this._reset = true;
  43736. /**
  43737. * @property {number} _sx - Internal cache var.
  43738. * @private
  43739. */
  43740. this._sx = sprite.scale.x;
  43741. /**
  43742. * @property {number} _sy - Internal cache var.
  43743. * @private
  43744. */
  43745. this._sy = sprite.scale.y;
  43746. /**
  43747. * @property {number} _dx - Internal cache var.
  43748. * @private
  43749. */
  43750. this._dx = 0;
  43751. /**
  43752. * @property {number} _dy - Internal cache var.
  43753. * @private
  43754. */
  43755. this._dy = 0;
  43756. };
  43757. Phaser.Physics.Arcade.Body.prototype = {
  43758. /**
  43759. * Internal method.
  43760. *
  43761. * @method Phaser.Physics.Arcade.Body#updateBounds
  43762. * @protected
  43763. */
  43764. updateBounds: function () {
  43765. var asx = Math.abs(this.sprite.scale.x);
  43766. var asy = Math.abs(this.sprite.scale.y);
  43767. if (asx !== this._sx || asy !== this._sy)
  43768. {
  43769. this.width = this.sourceWidth * asx;
  43770. this.height = this.sourceHeight * asy;
  43771. this.halfWidth = Math.floor(this.width / 2);
  43772. this.halfHeight = Math.floor(this.height / 2);
  43773. this._sx = asx;
  43774. this._sy = asy;
  43775. this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
  43776. this._reset = true;
  43777. }
  43778. },
  43779. /**
  43780. * Internal method.
  43781. *
  43782. * @method Phaser.Physics.Arcade.Body#preUpdate
  43783. * @protected
  43784. */
  43785. preUpdate: function () {
  43786. if (!this.enable)
  43787. {
  43788. return;
  43789. }
  43790. this.phase = 1;
  43791. // Store and reset collision flags
  43792. this.wasTouching.none = this.touching.none;
  43793. this.wasTouching.up = this.touching.up;
  43794. this.wasTouching.down = this.touching.down;
  43795. this.wasTouching.left = this.touching.left;
  43796. this.wasTouching.right = this.touching.right;
  43797. this.touching.none = true;
  43798. this.touching.up = false;
  43799. this.touching.down = false;
  43800. this.touching.left = false;
  43801. this.touching.right = false;
  43802. this.blocked.up = false;
  43803. this.blocked.down = false;
  43804. this.blocked.left = false;
  43805. this.blocked.right = false;
  43806. this.embedded = false;
  43807. this.updateBounds();
  43808. this.position.x = (this.sprite.world.x - (this.sprite.anchor.x * this.width)) + this.offset.x;
  43809. this.position.y = (this.sprite.world.y - (this.sprite.anchor.y * this.height)) + this.offset.y;
  43810. this.rotation = this.sprite.angle;
  43811. this.preRotation = this.rotation;
  43812. if (this._reset || this.sprite._cache[4] === 1)
  43813. {
  43814. this.prev.x = this.position.x;
  43815. this.prev.y = this.position.y;
  43816. }
  43817. if (this.moves)
  43818. {
  43819. this.game.physics.arcade.updateMotion(this);
  43820. this.newVelocity.set(this.velocity.x * this.game.time.physicsElapsed, this.velocity.y * this.game.time.physicsElapsed);
  43821. this.position.x += this.newVelocity.x;
  43822. this.position.y += this.newVelocity.y;
  43823. if (this.position.x !== this.prev.x || this.position.y !== this.prev.y)
  43824. {
  43825. this.speed = Math.sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y);
  43826. this.angle = Math.atan2(this.velocity.y, this.velocity.x);
  43827. }
  43828. // Now the State update will throw collision checks at the Body
  43829. // And finally we'll integrate the new position back to the Sprite in postUpdate
  43830. if (this.collideWorldBounds)
  43831. {
  43832. this.checkWorldBounds();
  43833. }
  43834. }
  43835. this._dx = this.deltaX();
  43836. this._dy = this.deltaY();
  43837. this._reset = false;
  43838. },
  43839. /**
  43840. * Internal method.
  43841. *
  43842. * @method Phaser.Physics.Arcade.Body#postUpdate
  43843. * @protected
  43844. */
  43845. postUpdate: function () {
  43846. if (!this.enable)
  43847. {
  43848. return;
  43849. }
  43850. // Only allow postUpdate to be called once per frame
  43851. if (this.phase === 2)
  43852. {
  43853. return;
  43854. }
  43855. this.phase = 2;
  43856. if (this.deltaX() < 0)
  43857. {
  43858. this.facing = Phaser.LEFT;
  43859. }
  43860. else if (this.deltaX() > 0)
  43861. {
  43862. this.facing = Phaser.RIGHT;
  43863. }
  43864. if (this.deltaY() < 0)
  43865. {
  43866. this.facing = Phaser.UP;
  43867. }
  43868. else if (this.deltaY() > 0)
  43869. {
  43870. this.facing = Phaser.DOWN;
  43871. }
  43872. if (this.moves)
  43873. {
  43874. this._dx = this.deltaX();
  43875. this._dy = this.deltaY();
  43876. if (this.deltaMax.x !== 0 && this._dx !== 0)
  43877. {
  43878. if (this._dx < 0 && this._dx < -this.deltaMax.x)
  43879. {
  43880. this._dx = -this.deltaMax.x;
  43881. }
  43882. else if (this._dx > 0 && this._dx > this.deltaMax.x)
  43883. {
  43884. this._dx = this.deltaMax.x;
  43885. }
  43886. }
  43887. if (this.deltaMax.y !== 0 && this._dy !== 0)
  43888. {
  43889. if (this._dy < 0 && this._dy < -this.deltaMax.y)
  43890. {
  43891. this._dy = -this.deltaMax.y;
  43892. }
  43893. else if (this._dy > 0 && this._dy > this.deltaMax.y)
  43894. {
  43895. this._dy = this.deltaMax.y;
  43896. }
  43897. }
  43898. this.sprite.x += this._dx;
  43899. this.sprite.y += this._dy;
  43900. }
  43901. this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
  43902. if (this.allowRotation)
  43903. {
  43904. this.sprite.angle += this.deltaZ();
  43905. }
  43906. this.prev.x = this.position.x;
  43907. this.prev.y = this.position.y;
  43908. },
  43909. /**
  43910. * Removes this bodies reference to its parent sprite, freeing it up for gc.
  43911. *
  43912. * @method Phaser.Physics.Arcade.Body#destroy
  43913. */
  43914. destroy: function () {
  43915. this.sprite = null;
  43916. },
  43917. /**
  43918. * Internal method.
  43919. *
  43920. * @method Phaser.Physics.Arcade.Body#checkWorldBounds
  43921. * @protected
  43922. */
  43923. checkWorldBounds: function () {
  43924. if (this.position.x < this.game.physics.arcade.bounds.x && this.game.physics.arcade.checkCollision.left)
  43925. {
  43926. this.position.x = this.game.physics.arcade.bounds.x;
  43927. this.velocity.x *= -this.bounce.x;
  43928. this.blocked.left = true;
  43929. }
  43930. else if (this.right > this.game.physics.arcade.bounds.right && this.game.physics.arcade.checkCollision.right)
  43931. {
  43932. this.position.x = this.game.physics.arcade.bounds.right - this.width;
  43933. this.velocity.x *= -this.bounce.x;
  43934. this.blocked.right = true;
  43935. }
  43936. if (this.position.y < this.game.physics.arcade.bounds.y && this.game.physics.arcade.checkCollision.up)
  43937. {
  43938. this.position.y = this.game.physics.arcade.bounds.y;
  43939. this.velocity.y *= -this.bounce.y;
  43940. this.blocked.up = true;
  43941. }
  43942. else if (this.bottom > this.game.physics.arcade.bounds.bottom && this.game.physics.arcade.checkCollision.down)
  43943. {
  43944. this.position.y = this.game.physics.arcade.bounds.bottom - this.height;
  43945. this.velocity.y *= -this.bounce.y;
  43946. this.blocked.down = true;
  43947. }
  43948. },
  43949. /**
  43950. * You can modify the size of the physics Body to be any dimension you need.
  43951. * So it could be smaller or larger than the parent Sprite. You can also control the x and y offset, which
  43952. * is the position of the Body relative to the top-left of the Sprite.
  43953. *
  43954. * @method Phaser.Physics.Arcade.Body#setSize
  43955. * @param {number} width - The width of the Body.
  43956. * @param {number} height - The height of the Body.
  43957. * @param {number} [offsetX] - The X offset of the Body from the Sprite position.
  43958. * @param {number} [offsetY] - The Y offset of the Body from the Sprite position.
  43959. */
  43960. setSize: function (width, height, offsetX, offsetY) {
  43961. if (typeof offsetX === 'undefined') { offsetX = this.offset.x; }
  43962. if (typeof offsetY === 'undefined') { offsetY = this.offset.y; }
  43963. this.sourceWidth = width;
  43964. this.sourceHeight = height;
  43965. this.width = this.sourceWidth * this._sx;
  43966. this.height = this.sourceHeight * this._sy;
  43967. this.halfWidth = Math.floor(this.width / 2);
  43968. this.halfHeight = Math.floor(this.height / 2);
  43969. this.offset.setTo(offsetX, offsetY);
  43970. this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
  43971. },
  43972. /**
  43973. * Resets all Body values (velocity, acceleration, rotation, etc)
  43974. *
  43975. * @method Phaser.Physics.Arcade.Body#reset
  43976. * @param {number} x - The new x position of the Body.
  43977. * @param {number} y - The new y position of the Body.
  43978. */
  43979. reset: function (x, y) {
  43980. this.velocity.set(0);
  43981. this.acceleration.set(0);
  43982. this.angularVelocity = 0;
  43983. this.angularAcceleration = 0;
  43984. this.position.x = (x - (this.sprite.anchor.x * this.width)) + this.offset.x;
  43985. this.position.y = (y - (this.sprite.anchor.y * this.height)) + this.offset.y;
  43986. this.prev.x = this.position.x;
  43987. this.prev.y = this.position.y;
  43988. this.rotation = this.sprite.angle;
  43989. this.preRotation = this.rotation;
  43990. this._sx = this.sprite.scale.x;
  43991. this._sy = this.sprite.scale.y;
  43992. this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
  43993. },
  43994. /**
  43995. * Tests if a world point lies within this Body.
  43996. *
  43997. * @method Phaser.Physics.Arcade.Body#hitTest
  43998. * @param {number} x - The world x coordinate to test.
  43999. * @param {number} y - The world y coordinate to test.
  44000. * @return {boolean} True if the given coordinates are inside this Body, otherwise false.
  44001. */
  44002. hitTest: function (x, y) {
  44003. return Phaser.Rectangle.contains(this, x, y);
  44004. },
  44005. /**
  44006. * Returns true if the bottom of this Body is in contact with either the world bounds or a tile.
  44007. *
  44008. * @method Phaser.Physics.Arcade.Body#onFloor
  44009. * @return {boolean} True if in contact with either the world bounds or a tile.
  44010. */
  44011. onFloor: function () {
  44012. return this.blocked.down;
  44013. },
  44014. /**
  44015. * Returns true if either side of this Body is in contact with either the world bounds or a tile.
  44016. *
  44017. * @method Phaser.Physics.Arcade.Body#onWall
  44018. * @return {boolean} True if in contact with either the world bounds or a tile.
  44019. */
  44020. onWall: function () {
  44021. return (this.blocked.left || this.blocked.right);
  44022. },
  44023. /**
  44024. * Returns the absolute delta x value.
  44025. *
  44026. * @method Phaser.Physics.Arcade.Body#deltaAbsX
  44027. * @return {number} The absolute delta value.
  44028. */
  44029. deltaAbsX: function () {
  44030. return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX());
  44031. },
  44032. /**
  44033. * Returns the absolute delta y value.
  44034. *
  44035. * @method Phaser.Physics.Arcade.Body#deltaAbsY
  44036. * @return {number} The absolute delta value.
  44037. */
  44038. deltaAbsY: function () {
  44039. return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY());
  44040. },
  44041. /**
  44042. * Returns the delta x value. The difference between Body.x now and in the previous step.
  44043. *
  44044. * @method Phaser.Physics.Arcade.Body#deltaX
  44045. * @return {number} The delta value. Positive if the motion was to the right, negative if to the left.
  44046. */
  44047. deltaX: function () {
  44048. return this.position.x - this.prev.x;
  44049. },
  44050. /**
  44051. * Returns the delta y value. The difference between Body.y now and in the previous step.
  44052. *
  44053. * @method Phaser.Physics.Arcade.Body#deltaY
  44054. * @return {number} The delta value. Positive if the motion was downwards, negative if upwards.
  44055. */
  44056. deltaY: function () {
  44057. return this.position.y - this.prev.y;
  44058. },
  44059. /**
  44060. * Returns the delta z value. The difference between Body.rotation now and in the previous step.
  44061. *
  44062. * @method Phaser.Physics.Arcade.Body#deltaZ
  44063. * @return {number} The delta value. Positive if the motion was clockwise, negative if anti-clockwise.
  44064. */
  44065. deltaZ: function () {
  44066. return this.rotation - this.preRotation;
  44067. }
  44068. };
  44069. /**
  44070. * @name Phaser.Physics.Arcade.Body#bottom
  44071. * @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height)
  44072. * @readonly
  44073. */
  44074. Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "bottom", {
  44075. get: function () {
  44076. return this.position.y + this.height;
  44077. }
  44078. });
  44079. /**
  44080. * @name Phaser.Physics.Arcade.Body#right
  44081. * @property {number} right - The right value of this Body (same as Body.x + Body.width)
  44082. * @readonly
  44083. */
  44084. Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "right", {
  44085. get: function () {
  44086. return this.position.x + this.width;
  44087. }
  44088. });
  44089. /**
  44090. * @name Phaser.Physics.Arcade.Body#x
  44091. * @property {number} x - The x position.
  44092. */
  44093. Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "x", {
  44094. get: function () {
  44095. return this.position.x;
  44096. },
  44097. set: function (value) {
  44098. this.position.x = value;
  44099. }
  44100. });
  44101. /**
  44102. * @name Phaser.Physics.Arcade.Body#y
  44103. * @property {number} y - The y position.
  44104. */
  44105. Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "y", {
  44106. get: function () {
  44107. return this.position.y;
  44108. },
  44109. set: function (value) {
  44110. this.position.y = value;
  44111. }
  44112. });
  44113. /**
  44114. * Render Sprite Body.
  44115. *
  44116. * @method Phaser.Physics.Arcade.Body#render
  44117. * @param {object} context - The context to render to.
  44118. * @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of.
  44119. * @param {string} [color='rgba(0,255,0,0.4)'] - color of the debug info to be rendered. (format is css color string).
  44120. * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false)
  44121. */
  44122. Phaser.Physics.Arcade.Body.render = function (context, body, color, filled) {
  44123. if (typeof filled === 'undefined') { filled = true; }
  44124. color = color || 'rgba(0,255,0,0.4)';
  44125. if (filled)
  44126. {
  44127. context.fillStyle = color;
  44128. context.fillRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height);
  44129. }
  44130. else
  44131. {
  44132. context.strokeStyle = color;
  44133. context.strokeRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height);
  44134. }
  44135. };
  44136. /**
  44137. * Render Sprite Body Physics Data as text.
  44138. *
  44139. * @method Phaser.Physics.Arcade.Body#renderBodyInfo
  44140. * @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of.
  44141. * @param {number} x - X position of the debug info to be rendered.
  44142. * @param {number} y - Y position of the debug info to be rendered.
  44143. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  44144. */
  44145. Phaser.Physics.Arcade.Body.renderBodyInfo = function (debug, body) {
  44146. debug.line('x: ' + body.x.toFixed(2), 'y: ' + body.y.toFixed(2), 'width: ' + body.width, 'height: ' + body.height);
  44147. 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));
  44148. 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));
  44149. debug.line('gravity x: ' + body.gravity.x, 'y: ' + body.gravity.y, 'bounce x: ' + body.bounce.x.toFixed(2), 'y: ' + body.bounce.y.toFixed(2));
  44150. debug.line('touching left: ' + body.touching.left, 'right: ' + body.touching.right, 'up: ' + body.touching.up, 'down: ' + body.touching.down);
  44151. debug.line('blocked left: ' + body.blocked.left, 'right: ' + body.blocked.right, 'up: ' + body.blocked.up, 'down: ' + body.blocked.down);
  44152. };
  44153. Phaser.Physics.Arcade.Body.prototype.constructor = Phaser.Physics.Arcade.Body;
  44154. /**
  44155. * @author Richard Davey <rich@photonstorm.com>
  44156. * @copyright 2014 Photon Storm Ltd.
  44157. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  44158. */
  44159. /**
  44160. * 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.
  44161. *
  44162. * @class Phaser.Particles
  44163. * @classdesc Phaser Particles
  44164. * @constructor
  44165. * @param {Phaser.Game} game - A reference to the currently running game.
  44166. */
  44167. Phaser.Particles = function (game) {
  44168. /**
  44169. * @property {Phaser.Game} game - A reference to the currently running Game.
  44170. */
  44171. this.game = game;
  44172. /**
  44173. * @property {object} emitters - Internal emitters store.
  44174. */
  44175. this.emitters = {};
  44176. /**
  44177. * @property {number} ID -
  44178. * @default
  44179. */
  44180. this.ID = 0;
  44181. };
  44182. Phaser.Particles.prototype = {
  44183. /**
  44184. * Adds a new Particle Emitter to the Particle Manager.
  44185. * @method Phaser.Particles#add
  44186. * @param {Phaser.Emitter} emitter - The emitter to be added to the particle manager.
  44187. * @return {Phaser.Emitter} The emitter that was added.
  44188. */
  44189. add: function (emitter) {
  44190. this.emitters[emitter.name] = emitter;
  44191. return emitter;
  44192. },
  44193. /**
  44194. * Removes an existing Particle Emitter from the Particle Manager.
  44195. * @method Phaser.Particles#remove
  44196. * @param {Phaser.Emitter} emitter - The emitter to remove.
  44197. */
  44198. remove: function (emitter) {
  44199. delete this.emitters[emitter.name];
  44200. },
  44201. /**
  44202. * Called by the core game loop. Updates all Emitters who have their exists value set to true.
  44203. * @method Phaser.Particles#update
  44204. * @protected
  44205. */
  44206. update: function () {
  44207. for (var key in this.emitters)
  44208. {
  44209. if (this.emitters[key].exists)
  44210. {
  44211. this.emitters[key].update();
  44212. }
  44213. }
  44214. }
  44215. };
  44216. Phaser.Particles.prototype.constructor = Phaser.Particles;
  44217. Phaser.Particles.Arcade = {};
  44218. /**
  44219. * @author Richard Davey <rich@photonstorm.com>
  44220. * @copyright 2014 Photon Storm Ltd.
  44221. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  44222. */
  44223. /**
  44224. * @class Phaser.Particles.Arcade.Emitter
  44225. *
  44226. * @classdesc Emitter is a lightweight particle emitter that uses Arcade Physics.
  44227. * It can be used for one-time explosions or for continuous effects like rain and fire.
  44228. * All it really does is launch Particle objects out at set intervals, and fixes their positions and velocities accorindgly.
  44229. *
  44230. * @constructor
  44231. * @extends Phaser.Group
  44232. * @param {Phaser.Game} game - Current game instance.
  44233. * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
  44234. * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
  44235. * @param {number} [maxParticles=50] - The total number of particles in this emitter.
  44236. */
  44237. Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) {
  44238. /**
  44239. * @property {number} maxParticles - The total number of particles in this emitter.
  44240. * @default
  44241. */
  44242. this.maxParticles = maxParticles || 50;
  44243. Phaser.Group.call(this, game);
  44244. /**
  44245. * @property {string} name - A handy string name for this emitter. Can be set to anything.
  44246. */
  44247. this.name = 'emitter' + this.game.particles.ID++;
  44248. /**
  44249. * @property {number} type - Internal Phaser Type value.
  44250. * @protected
  44251. */
  44252. this.type = Phaser.EMITTER;
  44253. /**
  44254. * @property {Phaser.Rectangle} area - The area of the emitter. Particles can be randomly generated from anywhere within this rectangle.
  44255. * @default
  44256. */
  44257. this.area = new Phaser.Rectangle(x, y, 1, 1);
  44258. /**
  44259. * @property {Phaser.Point} minParticleSpeed - The minimum possible velocity of a particle.
  44260. * @default
  44261. */
  44262. this.minParticleSpeed = new Phaser.Point(-100, -100);
  44263. /**
  44264. * @property {Phaser.Point} maxParticleSpeed - The maximum possible velocity of a particle.
  44265. * @default
  44266. */
  44267. this.maxParticleSpeed = new Phaser.Point(100, 100);
  44268. /**
  44269. * @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.
  44270. * @default
  44271. */
  44272. this.minParticleScale = 1;
  44273. /**
  44274. * @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.
  44275. * @default
  44276. */
  44277. this.maxParticleScale = 1;
  44278. /**
  44279. * @property {array} scaleData - An array of the calculated scale easing data applied to particles with scaleRates > 0.
  44280. */
  44281. this.scaleData = null;
  44282. /**
  44283. * @property {number} minRotation - The minimum possible angular velocity of a particle.
  44284. * @default
  44285. */
  44286. this.minRotation = -360;
  44287. /**
  44288. * @property {number} maxRotation - The maximum possible angular velocity of a particle.
  44289. * @default
  44290. */
  44291. this.maxRotation = 360;
  44292. /**
  44293. * @property {number} minParticleAlpha - The minimum possible alpha value of a particle.
  44294. * @default
  44295. */
  44296. this.minParticleAlpha = 1;
  44297. /**
  44298. * @property {number} maxParticleAlpha - The maximum possible alpha value of a particle.
  44299. * @default
  44300. */
  44301. this.maxParticleAlpha = 1;
  44302. /**
  44303. * @property {array} alphaData - An array of the calculated alpha easing data applied to particles with alphaRates > 0.
  44304. */
  44305. this.alphaData = null;
  44306. /**
  44307. * @property {number} gravity - Sets the `body.gravity.y` of each particle sprite to this value on launch.
  44308. * @default
  44309. */
  44310. this.gravity = 100;
  44311. /**
  44312. * @property {any} particleClass - For emitting your own particle class types. They must extend Phaser.Particle.
  44313. * @default
  44314. */
  44315. this.particleClass = Phaser.Particle;
  44316. /**
  44317. * @property {Phaser.Point} particleDrag - The X and Y drag component of particles launched from the emitter.
  44318. */
  44319. this.particleDrag = new Phaser.Point();
  44320. /**
  44321. * @property {number} angularDrag - The angular drag component of particles launched from the emitter if they are rotating.
  44322. * @default
  44323. */
  44324. this.angularDrag = 0;
  44325. /**
  44326. * @property {boolean} frequency - How often a particle is emitted in ms (if emitter is started with Explode === false).
  44327. * @default
  44328. */
  44329. this.frequency = 100;
  44330. /**
  44331. * @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.
  44332. * @default
  44333. */
  44334. this.lifespan = 2000;
  44335. /**
  44336. * @property {Phaser.Point} bounce - How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce.
  44337. */
  44338. this.bounce = new Phaser.Point();
  44339. /**
  44340. * @property {boolean} on - Determines whether the emitter is currently emitting particles. It is totally safe to directly toggle this.
  44341. * @default
  44342. */
  44343. this.on = false;
  44344. /**
  44345. * @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)
  44346. * @default
  44347. */
  44348. this.particleAnchor = new Phaser.Point(0.5, 0.5);
  44349. /**
  44350. * @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)
  44351. * @default
  44352. */
  44353. this.blendMode = Phaser.blendModes.NORMAL;
  44354. /**
  44355. * The point the particles are emitted from.
  44356. * Emitter.x and Emitter.y control the containers location, which updates all current particles
  44357. * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position.
  44358. * @property {number} emitX
  44359. */
  44360. this.emitX = x;
  44361. /**
  44362. * The point the particles are emitted from.
  44363. * Emitter.x and Emitter.y control the containers location, which updates all current particles
  44364. * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position.
  44365. * @property {number} emitY
  44366. */
  44367. this.emitY = y;
  44368. /**
  44369. * @property {boolean} autoScale - When a new Particle is emitted this controls if it will automatically scale in size. Use Emitter.setScale to configure.
  44370. */
  44371. this.autoScale = false;
  44372. /**
  44373. * @property {boolean} autoAlpha - When a new Particle is emitted this controls if it will automatically change alpha. Use Emitter.setAlpha to configure.
  44374. */
  44375. this.autoAlpha = false;
  44376. /**
  44377. * @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.
  44378. * @default
  44379. */
  44380. this.particleBringToTop = false;
  44381. /**
  44382. * @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.
  44383. * @default
  44384. */
  44385. this.particleSendToBack = false;
  44386. /**
  44387. * @property {Phaser.Point} _minParticleScale - Internal particle scale var.
  44388. * @private
  44389. */
  44390. this._minParticleScale = new Phaser.Point(1, 1);
  44391. /**
  44392. * @property {Phaser.Point} _maxParticleScale - Internal particle scale var.
  44393. * @private
  44394. */
  44395. this._maxParticleScale = new Phaser.Point(1, 1);
  44396. /**
  44397. * @property {number} _quantity - Internal helper for deciding how many particles to launch.
  44398. * @private
  44399. */
  44400. this._quantity = 0;
  44401. /**
  44402. * @property {number} _timer - Internal helper for deciding when to launch particles or kill them.
  44403. * @private
  44404. */
  44405. this._timer = 0;
  44406. /**
  44407. * @property {number} _counter - Internal counter for figuring out how many particles to launch.
  44408. * @private
  44409. */
  44410. this._counter = 0;
  44411. /**
  44412. * @property {boolean} _explode - Internal helper for the style of particle emission (all at once, or one at a time).
  44413. * @private
  44414. */
  44415. this._explode = true;
  44416. /**
  44417. * @property {any} _frames - Internal helper for the particle frame.
  44418. * @private
  44419. */
  44420. this._frames = null;
  44421. };
  44422. Phaser.Particles.Arcade.Emitter.prototype = Object.create(Phaser.Group.prototype);
  44423. Phaser.Particles.Arcade.Emitter.prototype.constructor = Phaser.Particles.Arcade.Emitter;
  44424. /**
  44425. * Called automatically by the game loop, decides when to launch particles and when to "die".
  44426. * @method Phaser.Particles.Arcade.Emitter#update
  44427. */
  44428. Phaser.Particles.Arcade.Emitter.prototype.update = function () {
  44429. if (this.on)
  44430. {
  44431. if (this._explode)
  44432. {
  44433. this._counter = 0;
  44434. do
  44435. {
  44436. this.emitParticle();
  44437. this._counter++;
  44438. }
  44439. while (this._counter < this._quantity);
  44440. this.on = false;
  44441. }
  44442. else
  44443. {
  44444. if (this.game.time.now >= this._timer)
  44445. {
  44446. this.emitParticle();
  44447. this._counter++;
  44448. if (this._quantity > 0)
  44449. {
  44450. if (this._counter >= this._quantity)
  44451. {
  44452. this.on = false;
  44453. }
  44454. }
  44455. this._timer = this.game.time.now + this.frequency;
  44456. }
  44457. }
  44458. }
  44459. var i = this.children.length;
  44460. while (i--)
  44461. {
  44462. if (this.children[i].exists)
  44463. {
  44464. this.children[i].update();
  44465. }
  44466. }
  44467. };
  44468. /**
  44469. * This function generates a new set of particles for use by this emitter.
  44470. * The particles are stored internally waiting to be emitted via Emitter.start.
  44471. *
  44472. * @method Phaser.Particles.Arcade.Emitter#makeParticles
  44473. * @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.
  44474. * @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.
  44475. * @param {number} [quantity] - The number of particles to generate. If not given it will use the value of Emitter.maxParticles.
  44476. * @param {boolean} [collide=false] - If you want the particles to be able to collide with other Arcade Physics bodies then set this to true.
  44477. * @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.
  44478. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  44479. */
  44480. Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames, quantity, collide, collideWorldBounds) {
  44481. if (typeof frames === 'undefined') { frames = 0; }
  44482. if (typeof quantity === 'undefined') { quantity = this.maxParticles; }
  44483. if (typeof collide === 'undefined') { collide = false; }
  44484. if (typeof collideWorldBounds === 'undefined') { collideWorldBounds = false; }
  44485. var particle;
  44486. var i = 0;
  44487. var rndKey = keys;
  44488. var rndFrame = frames;
  44489. this._frames = frames;
  44490. while (i < quantity)
  44491. {
  44492. if (Array.isArray(keys))
  44493. {
  44494. rndKey = this.game.rnd.pick(keys);
  44495. }
  44496. if (Array.isArray(frames))
  44497. {
  44498. rndFrame = this.game.rnd.pick(frames);
  44499. }
  44500. particle = new this.particleClass(this.game, 0, 0, rndKey, rndFrame);
  44501. this.game.physics.arcade.enable(particle, false);
  44502. if (collide)
  44503. {
  44504. particle.body.checkCollision.any = true;
  44505. particle.body.checkCollision.none = false;
  44506. }
  44507. else
  44508. {
  44509. particle.body.checkCollision.none = true;
  44510. }
  44511. particle.body.collideWorldBounds = collideWorldBounds;
  44512. particle.exists = false;
  44513. particle.visible = false;
  44514. particle.anchor.copyFrom(this.particleAnchor);
  44515. this.add(particle);
  44516. i++;
  44517. }
  44518. return this;
  44519. };
  44520. /**
  44521. * Call this function to turn off all the particles and the emitter.
  44522. *
  44523. * @method Phaser.Particles.Arcade.Emitter#kill
  44524. */
  44525. Phaser.Particles.Arcade.Emitter.prototype.kill = function () {
  44526. this.on = false;
  44527. this.alive = false;
  44528. this.exists = false;
  44529. };
  44530. /**
  44531. * Handy for bringing game objects "back to life". Just sets alive and exists back to true.
  44532. *
  44533. * @method Phaser.Particles.Arcade.Emitter#revive
  44534. */
  44535. Phaser.Particles.Arcade.Emitter.prototype.revive = function () {
  44536. this.alive = true;
  44537. this.exists = true;
  44538. };
  44539. /**
  44540. * Call this function to emit the given quantity of particles at all once (an explosion)
  44541. *
  44542. * @method Phaser.Particles.Arcade.Emitter#explode
  44543. * @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever.
  44544. * @param {number} [quantity=0] - How many particles to launch.
  44545. */
  44546. Phaser.Particles.Arcade.Emitter.prototype.explode = function (lifespan, quantity) {
  44547. this.start(true, lifespan, 0, quantity, false);
  44548. };
  44549. /**
  44550. * Call this function to start emitting a flow of particles at the given frequency.
  44551. *
  44552. * @method Phaser.Particles.Arcade.Emitter#flow
  44553. * @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever.
  44554. * @param {number} [frequency=250] - Frequency is how often to emit a particle, given in ms.
  44555. * @param {number} [quantity=0] - How many particles to launch.
  44556. */
  44557. Phaser.Particles.Arcade.Emitter.prototype.flow = function (lifespan, frequency, quantity) {
  44558. this.start(false, lifespan, frequency, quantity, true);
  44559. };
  44560. /**
  44561. * Call this function to start emitting particles.
  44562. *
  44563. * @method Phaser.Particles.Arcade.Emitter#start
  44564. * @param {boolean} [explode=true] - Whether the particles should all burst out at once (true) or at the frequency given (false).
  44565. * @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever.
  44566. * @param {number} [frequency=250] - Ignored if Explode is set to true. Frequency is how often to emit 1 particle. Value given in ms.
  44567. * @param {number} [quantity=0] - How many particles to launch. 0 = "all of the particles".
  44568. * @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.
  44569. */
  44570. Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, frequency, quantity, forceQuantity) {
  44571. if (typeof explode === 'undefined') { explode = true; }
  44572. if (typeof lifespan === 'undefined') { lifespan = 0; }
  44573. if (typeof frequency === 'undefined' || frequency === null) { frequency = 250; }
  44574. if (typeof quantity === 'undefined') { quantity = 0; }
  44575. if (typeof forceQuantity === 'undefined') { forceQuantity = false; }
  44576. this.revive();
  44577. this.visible = true;
  44578. this.on = true;
  44579. this._explode = explode;
  44580. this.lifespan = lifespan;
  44581. this.frequency = frequency;
  44582. if (explode || forceQuantity)
  44583. {
  44584. this._quantity = quantity;
  44585. }
  44586. else
  44587. {
  44588. this._quantity += quantity;
  44589. }
  44590. this._counter = 0;
  44591. this._timer = this.game.time.now + frequency;
  44592. };
  44593. /**
  44594. * This function can be used both internally and externally to emit the next particle in the queue.
  44595. *
  44596. * @method Phaser.Particles.Arcade.Emitter#emitParticle
  44597. */
  44598. Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function () {
  44599. var particle = this.getFirstExists(false);
  44600. if (particle === null)
  44601. {
  44602. return;
  44603. }
  44604. if (this.width > 1 || this.height > 1)
  44605. {
  44606. particle.reset(this.game.rnd.integerInRange(this.left, this.right), this.game.rnd.integerInRange(this.top, this.bottom));
  44607. }
  44608. else
  44609. {
  44610. particle.reset(this.emitX, this.emitY);
  44611. }
  44612. particle.angle = 0;
  44613. particle.lifespan = this.lifespan;
  44614. if (this.particleBringToTop)
  44615. {
  44616. this.bringToTop(particle);
  44617. }
  44618. else if (this.particleSendToBack)
  44619. {
  44620. this.sendToBack(particle);
  44621. }
  44622. if (this.autoScale)
  44623. {
  44624. particle.setScaleData(this.scaleData);
  44625. }
  44626. else if (this.minParticleScale !== 1 || this.maxParticleScale !== 1)
  44627. {
  44628. particle.scale.set(this.game.rnd.realInRange(this.minParticleScale, this.maxParticleScale));
  44629. }
  44630. else if ((this._minParticleScale.x !== this._maxParticleScale.x) || (this._minParticleScale.y !== this._maxParticleScale.y))
  44631. {
  44632. particle.scale.set(this.game.rnd.realInRange(this._minParticleScale.x, this._maxParticleScale.x), this.game.rnd.realInRange(this._minParticleScale.y, this._maxParticleScale.y));
  44633. }
  44634. if (Array.isArray(this._frames === 'object'))
  44635. {
  44636. particle.frame = this.game.rnd.pick(this._frames);
  44637. }
  44638. else
  44639. {
  44640. particle.frame = this._frames;
  44641. }
  44642. if (this.autoAlpha)
  44643. {
  44644. particle.setAlphaData(this.alphaData);
  44645. }
  44646. else
  44647. {
  44648. particle.alpha = this.game.rnd.realInRange(this.minParticleAlpha, this.maxParticleAlpha);
  44649. }
  44650. particle.blendMode = this.blendMode;
  44651. particle.body.updateBounds();
  44652. particle.body.bounce.setTo(this.bounce.x, this.bounce.y);
  44653. particle.body.velocity.x = this.game.rnd.integerInRange(this.minParticleSpeed.x, this.maxParticleSpeed.x);
  44654. particle.body.velocity.y = this.game.rnd.integerInRange(this.minParticleSpeed.y, this.maxParticleSpeed.y);
  44655. particle.body.angularVelocity = this.game.rnd.integerInRange(this.minRotation, this.maxRotation);
  44656. particle.body.gravity.y = this.gravity;
  44657. particle.body.drag.x = this.particleDrag.x;
  44658. particle.body.drag.y = this.particleDrag.y;
  44659. particle.body.angularDrag = this.angularDrag;
  44660. particle.onEmit();
  44661. };
  44662. /**
  44663. * A more compact way of setting the width and height of the emitter.
  44664. *
  44665. * @method Phaser.Particles.Arcade.Emitter#setSize
  44666. * @param {number} width - The desired width of the emitter (particles are spawned randomly within these dimensions).
  44667. * @param {number} height - The desired height of the emitter.
  44668. */
  44669. Phaser.Particles.Arcade.Emitter.prototype.setSize = function (width, height) {
  44670. this.area.width = width;
  44671. this.area.height = height;
  44672. };
  44673. /**
  44674. * A more compact way of setting the X velocity range of the emitter.
  44675. * @method Phaser.Particles.Arcade.Emitter#setXSpeed
  44676. * @param {number} [min=0] - The minimum value for this range.
  44677. * @param {number} [max=0] - The maximum value for this range.
  44678. */
  44679. Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) {
  44680. min = min || 0;
  44681. max = max || 0;
  44682. this.minParticleSpeed.x = min;
  44683. this.maxParticleSpeed.x = max;
  44684. };
  44685. /**
  44686. * A more compact way of setting the Y velocity range of the emitter.
  44687. * @method Phaser.Particles.Arcade.Emitter#setYSpeed
  44688. * @param {number} [min=0] - The minimum value for this range.
  44689. * @param {number} [max=0] - The maximum value for this range.
  44690. */
  44691. Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) {
  44692. min = min || 0;
  44693. max = max || 0;
  44694. this.minParticleSpeed.y = min;
  44695. this.maxParticleSpeed.y = max;
  44696. };
  44697. /**
  44698. * A more compact way of setting the angular velocity constraints of the particles.
  44699. *
  44700. * @method Phaser.Particles.Arcade.Emitter#setRotation
  44701. * @param {number} [min=0] - The minimum value for this range.
  44702. * @param {number} [max=0] - The maximum value for this range.
  44703. */
  44704. Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) {
  44705. min = min || 0;
  44706. max = max || 0;
  44707. this.minRotation = min;
  44708. this.maxRotation = max;
  44709. };
  44710. /**
  44711. * A more compact way of setting the alpha constraints of the particles.
  44712. * 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.
  44713. * 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.
  44714. *
  44715. * @method Phaser.Particles.Arcade.Emitter#setAlpha
  44716. * @param {number} [min=1] - The minimum value for this range.
  44717. * @param {number} [max=1] - The maximum value for this range.
  44718. * @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.
  44719. * @param {number} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values.
  44720. * @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)
  44721. */
  44722. Phaser.Particles.Arcade.Emitter.prototype.setAlpha = function (min, max, rate, ease, yoyo) {
  44723. if (typeof min === 'undefined') { min = 1; }
  44724. if (typeof max === 'undefined') { max = 1; }
  44725. if (typeof rate === 'undefined') { rate = 0; }
  44726. if (typeof ease === 'undefined') { ease = Phaser.Easing.Linear.None; }
  44727. if (typeof yoyo === 'undefined') { yoyo = false; }
  44728. this.minParticleAlpha = min;
  44729. this.maxParticleAlpha = max;
  44730. this.autoAlpha = false;
  44731. if (rate > 0 && min !== max)
  44732. {
  44733. var tweenData = { v: min };
  44734. var tween = this.game.make.tween(tweenData).to( { v: max }, rate, ease);
  44735. tween.yoyo(yoyo);
  44736. this.alphaData = tween.generateData(60);
  44737. // Inverse it so we don't have to do array length look-ups in Particle update loops
  44738. this.alphaData.reverse();
  44739. this.autoAlpha = true;
  44740. }
  44741. };
  44742. /**
  44743. * A more compact way of setting the scale constraints of the particles.
  44744. * 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.
  44745. * 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.
  44746. *
  44747. * @method Phaser.Particles.Arcade.Emitter#setScale
  44748. * @param {number} [minX=1] - The minimum value of Particle.scale.x.
  44749. * @param {number} [maxX=1] - The maximum value of Particle.scale.x.
  44750. * @param {number} [minY=1] - The minimum value of Particle.scale.y.
  44751. * @param {number} [maxY=1] - The maximum value of Particle.scale.y.
  44752. * @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.
  44753. * @param {number} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values.
  44754. * @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)
  44755. */
  44756. Phaser.Particles.Arcade.Emitter.prototype.setScale = function (minX, maxX, minY, maxY, rate, ease, yoyo) {
  44757. if (typeof minX === 'undefined') { minX = 1; }
  44758. if (typeof maxX === 'undefined') { maxX = 1; }
  44759. if (typeof minY === 'undefined') { minY = 1; }
  44760. if (typeof maxY === 'undefined') { maxY = 1; }
  44761. if (typeof rate === 'undefined') { rate = 0; }
  44762. if (typeof ease === 'undefined') { ease = Phaser.Easing.Linear.None; }
  44763. if (typeof yoyo === 'undefined') { yoyo = false; }
  44764. // Reset these
  44765. this.minParticleScale = 1;
  44766. this.maxParticleScale = 1;
  44767. this._minParticleScale.set(minX, minY);
  44768. this._maxParticleScale.set(maxX, maxY);
  44769. this.autoScale = false;
  44770. if (rate > 0 && (minX !== maxX) || (minY !== maxY))
  44771. {
  44772. var tweenData = { x: minX, y: minY };
  44773. var tween = this.game.make.tween(tweenData).to( { x: maxX, y: maxY }, rate, ease);
  44774. tween.yoyo(yoyo);
  44775. this.scaleData = tween.generateData(60);
  44776. // Inverse it so we don't have to do array length look-ups in Particle update loops
  44777. this.scaleData.reverse();
  44778. this.autoScale = true;
  44779. }
  44780. };
  44781. /**
  44782. * Change the emitters center to match the center of any object with a `center` property, such as a Sprite.
  44783. * If the object doesn't have a center property it will be set to object.x + object.width / 2
  44784. *
  44785. * @method Phaser.Particles.Arcade.Emitter#at
  44786. * @param {object|Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text|PIXI.DisplayObject} object - The object that you wish to match the center with.
  44787. */
  44788. Phaser.Particles.Arcade.Emitter.prototype.at = function (object) {
  44789. if (object.center)
  44790. {
  44791. this.emitX = object.center.x;
  44792. this.emitY = object.center.y;
  44793. }
  44794. else
  44795. {
  44796. this.emitX = object.world.x + (object.anchor.x * object.width);
  44797. this.emitY = object.world.y + (object.anchor.y * object.height);
  44798. }
  44799. };
  44800. /**
  44801. * @name Phaser.Particles.Arcade.Emitter#width
  44802. * @property {number} width - Gets or sets the width of the Emitter. This is the region in which a particle can be emitted.
  44803. */
  44804. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "width", {
  44805. get: function () {
  44806. return this.area.width;
  44807. },
  44808. set: function (value) {
  44809. this.area.width = value;
  44810. }
  44811. });
  44812. /**
  44813. * @name Phaser.Particles.Arcade.Emitter#height
  44814. * @property {number} height - Gets or sets the height of the Emitter. This is the region in which a particle can be emitted.
  44815. */
  44816. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "height", {
  44817. get: function () {
  44818. return this.area.height;
  44819. },
  44820. set: function (value) {
  44821. this.area.height = value;
  44822. }
  44823. });
  44824. /**
  44825. * @name Phaser.Particles.Arcade.Emitter#x
  44826. * @property {number} x - Gets or sets the x position of the Emitter.
  44827. */
  44828. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "x", {
  44829. get: function () {
  44830. return this.emitX;
  44831. },
  44832. set: function (value) {
  44833. this.emitX = value;
  44834. }
  44835. });
  44836. /**
  44837. * @name Phaser.Particles.Arcade.Emitter#y
  44838. * @property {number} y - Gets or sets the y position of the Emitter.
  44839. */
  44840. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "y", {
  44841. get: function () {
  44842. return this.emitY;
  44843. },
  44844. set: function (value) {
  44845. this.emitY = value;
  44846. }
  44847. });
  44848. /**
  44849. * @name Phaser.Particles.Arcade.Emitter#left
  44850. * @property {number} left - Gets the left position of the Emitter.
  44851. * @readonly
  44852. */
  44853. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "left", {
  44854. get: function () {
  44855. return Math.floor(this.x - (this.area.width / 2));
  44856. }
  44857. });
  44858. /**
  44859. * @name Phaser.Particles.Arcade.Emitter#right
  44860. * @property {number} right - Gets the right position of the Emitter.
  44861. * @readonly
  44862. */
  44863. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "right", {
  44864. get: function () {
  44865. return Math.floor(this.x + (this.area.width / 2));
  44866. }
  44867. });
  44868. /**
  44869. * @name Phaser.Particles.Arcade.Emitter#top
  44870. * @property {number} top - Gets the top position of the Emitter.
  44871. * @readonly
  44872. */
  44873. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "top", {
  44874. get: function () {
  44875. return Math.floor(this.y - (this.area.height / 2));
  44876. }
  44877. });
  44878. /**
  44879. * @name Phaser.Particles.Arcade.Emitter#bottom
  44880. * @property {number} bottom - Gets the bottom position of the Emitter.
  44881. * @readonly
  44882. */
  44883. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "bottom", {
  44884. get: function () {
  44885. return Math.floor(this.y + (this.area.height / 2));
  44886. }
  44887. });
  44888. /**
  44889. * @author Richard Davey <rich@photonstorm.com>
  44890. * @copyright 2014 Photon Storm Ltd.
  44891. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  44892. */
  44893. /**
  44894. * Create a new `Tile` object.
  44895. *
  44896. * @class Phaser.Tile
  44897. * @classdesc A Tile is a representation of a single tile within the Tilemap.
  44898. * @constructor
  44899. * @param {object} layer - The layer in the Tilemap data that this tile belongs to.
  44900. * @param {number} index - The index of this tile type in the core map data.
  44901. * @param {number} x - The x coordinate of this tile.
  44902. * @param {number} y - The y coordinate of this tile.
  44903. * @param {number} width - Width of the tile.
  44904. * @param {number} height - Height of the tile.
  44905. */
  44906. Phaser.Tile = function (layer, index, x, y, width, height) {
  44907. /**
  44908. * @property {object} layer - The layer in the Tilemap data that this tile belongs to.
  44909. */
  44910. this.layer = layer;
  44911. /**
  44912. * @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.
  44913. */
  44914. this.index = index;
  44915. /**
  44916. * @property {number} x - The x map coordinate of this tile.
  44917. */
  44918. this.x = x;
  44919. /**
  44920. * @property {number} y - The y map coordinate of this tile.
  44921. */
  44922. this.y = y;
  44923. /**
  44924. * @property {number} x - The x map coordinate of this tile.
  44925. */
  44926. this.worldX = x * width;
  44927. /**
  44928. * @property {number} y - The y map coordinate of this tile.
  44929. */
  44930. this.worldY = y * height;
  44931. /**
  44932. * @property {number} width - The width of the tile in pixels.
  44933. */
  44934. this.width = width;
  44935. /**
  44936. * @property {number} height - The height of the tile in pixels.
  44937. */
  44938. this.height = height;
  44939. /**
  44940. * @property {number} width - The width of the tile in pixels.
  44941. */
  44942. this.centerX = Math.abs(width / 2);
  44943. /**
  44944. * @property {number} height - The height of the tile in pixels.
  44945. */
  44946. this.centerY = Math.abs(height / 2);
  44947. /**
  44948. * @property {number} alpha - The alpha value at which this tile is drawn to the canvas.
  44949. */
  44950. this.alpha = 1;
  44951. /**
  44952. * @property {object} properties - Tile specific properties.
  44953. */
  44954. this.properties = {};
  44955. /**
  44956. * @property {boolean} scanned - Has this tile been walked / turned into a poly?
  44957. */
  44958. this.scanned = false;
  44959. /**
  44960. * @property {boolean} faceTop - Is the top of this tile an interesting edge?
  44961. */
  44962. this.faceTop = false;
  44963. /**
  44964. * @property {boolean} faceBottom - Is the bottom of this tile an interesting edge?
  44965. */
  44966. this.faceBottom = false;
  44967. /**
  44968. * @property {boolean} faceLeft - Is the left of this tile an interesting edge?
  44969. */
  44970. this.faceLeft = false;
  44971. /**
  44972. * @property {boolean} faceRight - Is the right of this tile an interesting edge?
  44973. */
  44974. this.faceRight = false;
  44975. /**
  44976. * @property {boolean} collideLeft - Indicating collide with any object on the left.
  44977. * @default
  44978. */
  44979. this.collideLeft = false;
  44980. /**
  44981. * @property {boolean} collideRight - Indicating collide with any object on the right.
  44982. * @default
  44983. */
  44984. this.collideRight = false;
  44985. /**
  44986. * @property {boolean} collideUp - Indicating collide with any object on the top.
  44987. * @default
  44988. */
  44989. this.collideUp = false;
  44990. /**
  44991. * @property {boolean} collideDown - Indicating collide with any object on the bottom.
  44992. * @default
  44993. */
  44994. this.collideDown = false;
  44995. /**
  44996. * @property {function} collisionCallback - Tile collision callback.
  44997. * @default
  44998. */
  44999. this.collisionCallback = null;
  45000. /**
  45001. * @property {object} collisionCallbackContext - The context in which the collision callback will be called.
  45002. * @default
  45003. */
  45004. this.collisionCallbackContext = this;
  45005. };
  45006. Phaser.Tile.prototype = {
  45007. /**
  45008. * Check if the given x and y world coordinates are within this Tile.
  45009. *
  45010. * @method Phaser.Tile#containsPoint
  45011. * @param {number} x - The x coordinate to test.
  45012. * @param {number} y - The y coordinate to test.
  45013. * @return {boolean} True if the coordinates are within this Tile, otherwise false.
  45014. */
  45015. containsPoint: function (x, y) {
  45016. return !(x < this.worldX || y < this.worldY || x > this.right || y > this.bottom);
  45017. },
  45018. /**
  45019. * Check for intersection with this tile.
  45020. *
  45021. * @method Phaser.Tile#intersects
  45022. * @param {number} x - The x axis in pixels.
  45023. * @param {number} y - The y axis in pixels.
  45024. * @param {number} right - The right point.
  45025. * @param {number} bottom - The bottom point.
  45026. */
  45027. intersects: function (x, y, right, bottom) {
  45028. if (right <= this.worldX)
  45029. {
  45030. return false;
  45031. }
  45032. if (bottom <= this.worldY)
  45033. {
  45034. return false;
  45035. }
  45036. if (x >= this.worldX + this.width)
  45037. {
  45038. return false;
  45039. }
  45040. if (y >= this.worldY + this.height)
  45041. {
  45042. return false;
  45043. }
  45044. return true;
  45045. },
  45046. /**
  45047. * Set a callback to be called when this tile is hit by an object.
  45048. * The callback must true true for collision processing to take place.
  45049. *
  45050. * @method Phaser.Tile#setCollisionCallback
  45051. * @param {function} callback - Callback function.
  45052. * @param {object} context - Callback will be called within this context.
  45053. */
  45054. setCollisionCallback: function (callback, context) {
  45055. this.collisionCallback = callback;
  45056. this.collisionCallbackContext = context;
  45057. },
  45058. /**
  45059. * Clean up memory.
  45060. *
  45061. * @method Phaser.Tile#destroy
  45062. */
  45063. destroy: function () {
  45064. this.collisionCallback = null;
  45065. this.collisionCallbackContext = null;
  45066. this.properties = null;
  45067. },
  45068. /**
  45069. * Set collision settings on this tile.
  45070. *
  45071. * @method Phaser.Tile#setCollision
  45072. * @param {boolean} left - Indicating collide with any object on the left.
  45073. * @param {boolean} right - Indicating collide with any object on the right.
  45074. * @param {boolean} up - Indicating collide with any object on the top.
  45075. * @param {boolean} down - Indicating collide with any object on the bottom.
  45076. */
  45077. setCollision: function (left, right, up, down) {
  45078. this.collideLeft = left;
  45079. this.collideRight = right;
  45080. this.collideUp = up;
  45081. this.collideDown = down;
  45082. },
  45083. /**
  45084. * Reset collision status flags.
  45085. *
  45086. * @method Phaser.Tile#resetCollision
  45087. */
  45088. resetCollision: function () {
  45089. this.collideLeft = false;
  45090. this.collideRight = false;
  45091. this.collideUp = false;
  45092. this.collideDown = false;
  45093. this.faceTop = false;
  45094. this.faceBottom = false;
  45095. this.faceLeft = false;
  45096. this.faceRight = false;
  45097. },
  45098. /**
  45099. * Is this tile interesting?
  45100. *
  45101. * @method Phaser.Tile#isInteresting
  45102. * @param {boolean} collides - If true will check any collides value.
  45103. * @param {boolean} faces - If true will check any face value.
  45104. * @return {boolean} True if the Tile is interesting, otherwise false.
  45105. */
  45106. isInteresting: function (collides, faces) {
  45107. if (collides && faces)
  45108. {
  45109. // Does this tile have any collide flags OR interesting face?
  45110. return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.faceTop || this.faceBottom || this.faceLeft || this.faceRight || this.collisionCallback);
  45111. }
  45112. else if (collides)
  45113. {
  45114. // Does this tile collide?
  45115. return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown);
  45116. }
  45117. else if (faces)
  45118. {
  45119. // Does this tile have an interesting face?
  45120. return (this.faceTop || this.faceBottom || this.faceLeft || this.faceRight);
  45121. }
  45122. return false;
  45123. },
  45124. /**
  45125. * Copies the tile data and properties from the given tile to this tile.
  45126. *
  45127. * @method Phaser.Tile#copy
  45128. * @param {Phaser.Tile} tile - The tile to copy from.
  45129. */
  45130. copy: function (tile) {
  45131. this.index = tile.index;
  45132. this.alpha = tile.alpha;
  45133. this.properties = tile.properties;
  45134. this.collideUp = tile.collideUp;
  45135. this.collideDown = tile.collideDown;
  45136. this.collideLeft = tile.collideLeft;
  45137. this.collideRight = tile.collideRight;
  45138. this.collisionCallback = tile.collisionCallback;
  45139. this.collisionCallbackContext = tile.collisionCallbackContext;
  45140. }
  45141. };
  45142. Phaser.Tile.prototype.constructor = Phaser.Tile;
  45143. /**
  45144. * @name Phaser.Tile#collides
  45145. * @property {boolean} collides - True if this tile can collide on any of its faces.
  45146. * @readonly
  45147. */
  45148. Object.defineProperty(Phaser.Tile.prototype, "collides", {
  45149. get: function () {
  45150. return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown);
  45151. }
  45152. });
  45153. /**
  45154. * @name Phaser.Tile#canCollide
  45155. * @property {boolean} canCollide - True if this tile can collide on any of its faces or has a collision callback set.
  45156. * @readonly
  45157. */
  45158. Object.defineProperty(Phaser.Tile.prototype, "canCollide", {
  45159. get: function () {
  45160. return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.collisionCallback);
  45161. }
  45162. });
  45163. /**
  45164. * @name Phaser.Tile#left
  45165. * @property {number} left - The x value in pixels.
  45166. * @readonly
  45167. */
  45168. Object.defineProperty(Phaser.Tile.prototype, "left", {
  45169. get: function () {
  45170. return this.worldX;
  45171. }
  45172. });
  45173. /**
  45174. * @name Phaser.Tile#right
  45175. * @property {number} right - The sum of the x and width properties.
  45176. * @readonly
  45177. */
  45178. Object.defineProperty(Phaser.Tile.prototype, "right", {
  45179. get: function () {
  45180. return this.worldX + this.width;
  45181. }
  45182. });
  45183. /**
  45184. * @name Phaser.Tile#top
  45185. * @property {number} top - The y value.
  45186. * @readonly
  45187. */
  45188. Object.defineProperty(Phaser.Tile.prototype, "top", {
  45189. get: function () {
  45190. return this.worldY;
  45191. }
  45192. });
  45193. /**
  45194. * @name Phaser.Tile#bottom
  45195. * @property {number} bottom - The sum of the y and height properties.
  45196. * @readonly
  45197. */
  45198. Object.defineProperty(Phaser.Tile.prototype, "bottom", {
  45199. get: function () {
  45200. return this.worldY + this.height;
  45201. }
  45202. });
  45203. /**
  45204. * @author Richard Davey <rich@photonstorm.com>
  45205. * @copyright 2014 Photon Storm Ltd.
  45206. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  45207. */
  45208. /**
  45209. * Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file.
  45210. * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
  45211. * When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
  45212. * 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.
  45213. * 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.
  45214. * A Tile map is rendered to the display using a TilemapLayer. It is not added to the display list directly itself.
  45215. * A map may have multiple layers. You can perform operations on the map data such as copying, pasting, filling and shuffling the tiles around.
  45216. *
  45217. * @class Phaser.Tilemap
  45218. * @constructor
  45219. * @param {Phaser.Game} game - Game reference to the currently running game.
  45220. * @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`.
  45221. * @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.
  45222. * @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.
  45223. * @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.
  45224. * @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.
  45225. */
  45226. Phaser.Tilemap = function (game, key, tileWidth, tileHeight, width, height) {
  45227. /**
  45228. * @property {Phaser.Game} game - A reference to the currently running Game.
  45229. */
  45230. this.game = game;
  45231. /**
  45232. * @property {string} key - The key of this map data in the Phaser.Cache.
  45233. */
  45234. this.key = key;
  45235. var data = Phaser.TilemapParser.parse(this.game, key, tileWidth, tileHeight, width, height);
  45236. if (data === null)
  45237. {
  45238. return;
  45239. }
  45240. /**
  45241. * @property {number} width - The width of the map (in tiles).
  45242. */
  45243. this.width = data.width;
  45244. /**
  45245. * @property {number} height - The height of the map (in tiles).
  45246. */
  45247. this.height = data.height;
  45248. /**
  45249. * @property {number} tileWidth - The base width of the tiles in the map (in pixels).
  45250. */
  45251. this.tileWidth = data.tileWidth;
  45252. /**
  45253. * @property {number} tileHeight - The base height of the tiles in the map (in pixels).
  45254. */
  45255. this.tileHeight = data.tileHeight;
  45256. /**
  45257. * @property {string} orientation - The orientation of the map data (as specified in Tiled), usually 'orthogonal'.
  45258. */
  45259. this.orientation = data.orientation;
  45260. /**
  45261. * @property {number} format - The format of the map data, either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON.
  45262. */
  45263. this.format = data.format;
  45264. /**
  45265. * @property {number} version - The version of the map data (as specified in Tiled, usually 1).
  45266. */
  45267. this.version = data.version;
  45268. /**
  45269. * @property {object} properties - Map specific properties as specified in Tiled.
  45270. */
  45271. this.properties = data.properties;
  45272. /**
  45273. * @property {number} widthInPixels - The width of the map in pixels based on width * tileWidth.
  45274. */
  45275. this.widthInPixels = data.widthInPixels;
  45276. /**
  45277. * @property {number} heightInPixels - The height of the map in pixels based on height * tileHeight.
  45278. */
  45279. this.heightInPixels = data.heightInPixels;
  45280. /**
  45281. * @property {array} layers - An array of Tilemap layer data.
  45282. */
  45283. this.layers = data.layers;
  45284. /**
  45285. * @property {array} tilesets - An array of Tilesets.
  45286. */
  45287. this.tilesets = data.tilesets;
  45288. /**
  45289. * @property {array} tiles - The super array of Tiles.
  45290. */
  45291. this.tiles = data.tiles;
  45292. /**
  45293. * @property {array} objects - An array of Tiled Object Layers.
  45294. */
  45295. this.objects = data.objects;
  45296. /**
  45297. * @property {array} collideIndexes - An array of tile indexes that collide.
  45298. */
  45299. this.collideIndexes = [];
  45300. /**
  45301. * @property {array} collision - An array of collision data (polylines, etc).
  45302. */
  45303. this.collision = data.collision;
  45304. /**
  45305. * @property {array} images - An array of Tiled Image Layers.
  45306. */
  45307. this.images = data.images;
  45308. /**
  45309. * @property {number} currentLayer - The current layer.
  45310. */
  45311. this.currentLayer = 0;
  45312. /**
  45313. * @property {array} debugMap - Map data used for debug values only.
  45314. */
  45315. this.debugMap = [];
  45316. /**
  45317. * @property {array} _results - Internal var.
  45318. * @private
  45319. */
  45320. this._results = [];
  45321. /**
  45322. * @property {number} _tempA - Internal var.
  45323. * @private
  45324. */
  45325. this._tempA = 0;
  45326. /**
  45327. * @property {number} _tempB - Internal var.
  45328. * @private
  45329. */
  45330. this._tempB = 0;
  45331. };
  45332. /**
  45333. * @constant
  45334. * @type {number}
  45335. */
  45336. Phaser.Tilemap.CSV = 0;
  45337. /**
  45338. * @constant
  45339. * @type {number}
  45340. */
  45341. Phaser.Tilemap.TILED_JSON = 1;
  45342. /**
  45343. * @constant
  45344. * @type {number}
  45345. */
  45346. Phaser.Tilemap.NORTH = 0;
  45347. /**
  45348. * @constant
  45349. * @type {number}
  45350. */
  45351. Phaser.Tilemap.EAST = 1;
  45352. /**
  45353. * @constant
  45354. * @type {number}
  45355. */
  45356. Phaser.Tilemap.SOUTH = 2;
  45357. /**
  45358. * @constant
  45359. * @type {number}
  45360. */
  45361. Phaser.Tilemap.WEST = 3;
  45362. Phaser.Tilemap.prototype = {
  45363. /**
  45364. * Creates an empty map of the given dimensions and one blank layer. If layers already exist they are erased.
  45365. *
  45366. * @method Phaser.Tilemap#create
  45367. * @param {string} name - The name of the default layer of the map.
  45368. * @param {number} width - The width of the map in tiles.
  45369. * @param {number} height - The height of the map in tiles.
  45370. * @param {number} tileWidth - The width of the tiles the map uses for calculations.
  45371. * @param {number} tileHeight - The height of the tiles the map uses for calculations.
  45372. * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group.
  45373. * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly.
  45374. */
  45375. create: function (name, width, height, tileWidth, tileHeight, group) {
  45376. if (typeof group === 'undefined') { group = this.game.world; }
  45377. this.width = width;
  45378. this.height = height;
  45379. this.setTileSize(tileWidth, tileHeight);
  45380. this.layers.length = 0;
  45381. return this.createBlankLayer(name, width, height, tileWidth, tileHeight, group);
  45382. },
  45383. /**
  45384. * Sets the base tile size for the map.
  45385. *
  45386. * @method Phaser.Tilemap#setTileSize
  45387. * @param {number} tileWidth - The width of the tiles the map uses for calculations.
  45388. * @param {number} tileHeight - The height of the tiles the map uses for calculations.
  45389. */
  45390. setTileSize: function (tileWidth, tileHeight) {
  45391. this.tileWidth = tileWidth;
  45392. this.tileHeight = tileHeight;
  45393. this.widthInPixels = this.width * tileWidth;
  45394. this.heightInPixels = this.height * tileHeight;
  45395. },
  45396. /**
  45397. * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets.
  45398. * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled editor.
  45399. *
  45400. * @method Phaser.Tilemap#addTilesetImage
  45401. * @param {string} tileset - The name of the tileset as specified in the map data.
  45402. * @param {string} [key] - The key of the Phaser.Cache image used for this tileset. If not specified it will look for an image with a key matching the tileset parameter.
  45403. * @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.
  45404. * @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.
  45405. * @param {number} [tileMargin=0] - The width of the tiles in the Tileset Image. If not given it will default to the map.tileWidth value.
  45406. * @param {number} [tileSpacing=0] - The height of the tiles in the Tileset Image. If not given it will default to the map.tileHeight value.
  45407. * @param {number} [gid=0] - If adding multiple tilesets to a blank/dynamic map, specify the starting GID the set will use here.
  45408. * @return {Phaser.Tileset} Returns the Tileset object that was created or updated, or null if it failed.
  45409. */
  45410. addTilesetImage: function (tileset, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) {
  45411. if (typeof tileWidth === 'undefined') { tileWidth = this.tileWidth; }
  45412. if (typeof tileHeight === 'undefined') { tileHeight = this.tileHeight; }
  45413. if (typeof tileMargin === 'undefined') { tileMargin = 0; }
  45414. if (typeof tileSpacing === 'undefined') { tileSpacing = 0; }
  45415. if (typeof gid === 'undefined') { gid = 0; }
  45416. // In-case we're working from a blank map
  45417. if (tileWidth === 0)
  45418. {
  45419. tileWidth = 32;
  45420. }
  45421. if (tileHeight === 0)
  45422. {
  45423. tileHeight = 32;
  45424. }
  45425. if (typeof key === 'undefined')
  45426. {
  45427. if (typeof tileset === 'string')
  45428. {
  45429. key = tileset;
  45430. if (!this.game.cache.checkImageKey(key))
  45431. {
  45432. console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "' + key + '"');
  45433. return null;
  45434. }
  45435. }
  45436. else
  45437. {
  45438. return null;
  45439. }
  45440. }
  45441. if (typeof tileset === 'string')
  45442. {
  45443. tileset = this.getTilesetIndex(tileset);
  45444. if (tileset === null && this.format === Phaser.Tilemap.TILED_JSON)
  45445. {
  45446. console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "' + key + '"');
  45447. return null;
  45448. }
  45449. }
  45450. if (this.tilesets[tileset])
  45451. {
  45452. this.tilesets[tileset].setImage(this.game.cache.getImage(key));
  45453. return this.tilesets[tileset];
  45454. }
  45455. else
  45456. {
  45457. var newSet = new Phaser.Tileset(key, gid, tileWidth, tileHeight, tileMargin, tileSpacing, {});
  45458. newSet.setImage(this.game.cache.getImage(key));
  45459. this.tilesets.push(newSet);
  45460. var i = this.tilesets.length - 1;
  45461. var x = tileMargin;
  45462. var y = tileMargin;
  45463. var count = 0;
  45464. var countX = 0;
  45465. var countY = 0;
  45466. for (var t = gid; t < gid + newSet.total; t++)
  45467. {
  45468. this.tiles[t] = [x, y, i];
  45469. x += tileWidth + tileSpacing;
  45470. count++;
  45471. if (count === newSet.total)
  45472. {
  45473. break;
  45474. }
  45475. countX++;
  45476. if (countX === newSet.columns)
  45477. {
  45478. x = tileMargin;
  45479. y += tileHeight + tileSpacing;
  45480. countX = 0;
  45481. countY++;
  45482. if (countY === newSet.rows)
  45483. {
  45484. break;
  45485. }
  45486. }
  45487. }
  45488. return newSet;
  45489. }
  45490. return null;
  45491. },
  45492. /**
  45493. * 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
  45494. * 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
  45495. * 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
  45496. * Sprite is created. You could also give it a value like: body.velocity.x: 100 to set it moving automatically.
  45497. *
  45498. * @method Phaser.Tilemap#createFromObjects
  45499. * @param {string} name - The name of the Object Group to create Sprites from.
  45500. * @param {number} gid - The layer array index value, or if a string is given the layer name within the map data.
  45501. * @param {string} key - The Game.cache key of the image that this Sprite will use.
  45502. * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here.
  45503. * @param {boolean} [exists=true] - The default exists state of the Sprite.
  45504. * @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.
  45505. * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group.
  45506. * @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.
  45507. * @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.
  45508. */
  45509. createFromObjects: function (name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY) {
  45510. if (typeof exists === 'undefined') { exists = true; }
  45511. if (typeof autoCull === 'undefined') { autoCull = false; }
  45512. if (typeof group === 'undefined') { group = this.game.world; }
  45513. if (typeof CustomClass === 'undefined') { CustomClass = Phaser.Sprite; }
  45514. if (typeof adjustY === 'undefined') { adjustY = true; }
  45515. if (!this.objects[name])
  45516. {
  45517. console.warn('Tilemap.createFromObjects: Invalid objectgroup name given: ' + name);
  45518. return;
  45519. }
  45520. var sprite;
  45521. for (var i = 0, len = this.objects[name].length; i < len; i++)
  45522. {
  45523. if (this.objects[name][i].gid === gid)
  45524. {
  45525. sprite = new CustomClass(this.game, this.objects[name][i].x, this.objects[name][i].y, key, frame);
  45526. sprite.name = this.objects[name][i].name;
  45527. sprite.visible = this.objects[name][i].visible;
  45528. sprite.autoCull = autoCull;
  45529. sprite.exists = exists;
  45530. if (adjustY)
  45531. {
  45532. sprite.y -= sprite.height;
  45533. }
  45534. group.add(sprite);
  45535. for (var property in this.objects[name][i].properties)
  45536. {
  45537. group.set(sprite, property, this.objects[name][i].properties[property], false, false, 0, true);
  45538. }
  45539. }
  45540. }
  45541. },
  45542. /**
  45543. * Creates a new TilemapLayer object. By default TilemapLayers are fixed to the camera.
  45544. * 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.
  45545. * Or you can open the JSON file it exports and look at the layers[].name value. Either way it must match.
  45546. * If you wish to create a blank layer to put your own tiles on then see Tilemap.createBlankLayer.
  45547. *
  45548. * @method Phaser.Tilemap#createLayer
  45549. * @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.
  45550. * @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.
  45551. * @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.
  45552. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  45553. * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Sprite and can be moved around the display list accordingly.
  45554. */
  45555. createLayer: function (layer, width, height, group) {
  45556. // Add Buffer support for the left of the canvas
  45557. if (typeof width === 'undefined') { width = this.game.width; }
  45558. if (typeof height === 'undefined') { height = this.game.height; }
  45559. if (typeof group === 'undefined') { group = this.game.world; }
  45560. var index = layer;
  45561. if (typeof layer === 'string')
  45562. {
  45563. index = this.getLayerIndex(layer);
  45564. }
  45565. if (index === null || index > this.layers.length)
  45566. {
  45567. console.warn('Tilemap.createLayer: Invalid layer ID given: ' + index);
  45568. return;
  45569. }
  45570. return group.add(new Phaser.TilemapLayer(this.game, this, index, width, height));
  45571. },
  45572. /**
  45573. * Creates a new and empty layer on this Tilemap. By default TilemapLayers are fixed to the camera.
  45574. *
  45575. * @method Phaser.Tilemap#createBlankLayer
  45576. * @param {string} name - The name of this layer. Must be unique within the map.
  45577. * @param {number} width - The width of the layer in tiles.
  45578. * @param {number} height - The height of the layer in tiles.
  45579. * @param {number} tileWidth - The width of the tiles the layer uses for calculations.
  45580. * @param {number} tileHeight - The height of the tiles the layer uses for calculations.
  45581. * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group.
  45582. * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly.
  45583. */
  45584. createBlankLayer: function (name, width, height, tileWidth, tileHeight, group) {
  45585. if (typeof group === 'undefined') { group = this.game.world; }
  45586. if (this.getLayerIndex(name) !== null)
  45587. {
  45588. console.warn('Tilemap.createBlankLayer: Layer with matching name already exists');
  45589. return;
  45590. }
  45591. var layer = {
  45592. name: name,
  45593. x: 0,
  45594. y: 0,
  45595. width: width,
  45596. height: height,
  45597. widthInPixels: width * tileWidth,
  45598. heightInPixels: height * tileHeight,
  45599. alpha: 1,
  45600. visible: true,
  45601. properties: {},
  45602. indexes: [],
  45603. callbacks: [],
  45604. bodies: [],
  45605. data: null
  45606. };
  45607. var row;
  45608. var output = [];
  45609. for (var y = 0; y < height; y++)
  45610. {
  45611. row = [];
  45612. for (var x = 0; x < width; x++)
  45613. {
  45614. // row.push(null);
  45615. row.push(new Phaser.Tile(layer, -1, x, y, tileWidth, tileHeight));
  45616. }
  45617. output.push(row);
  45618. }
  45619. layer.data = output;
  45620. this.layers.push(layer);
  45621. this.currentLayer = this.layers.length - 1;
  45622. var w = layer.widthInPixels;
  45623. var h = layer.heightInPixels;
  45624. if (w > this.game.width)
  45625. {
  45626. w = this.game.width;
  45627. }
  45628. if (h > this.game.height)
  45629. {
  45630. h = this.game.height;
  45631. }
  45632. var output = new Phaser.TilemapLayer(this.game, this, this.layers.length - 1, w, h);
  45633. output.name = name;
  45634. return group.add(output);
  45635. },
  45636. /**
  45637. * Gets the layer index based on the layers name.
  45638. *
  45639. * @method Phaser.Tilemap#getIndex
  45640. * @protected
  45641. * @param {array} location - The local array to search.
  45642. * @param {string} name - The name of the array element to get.
  45643. * @return {number} The index of the element in the array, or null if not found.
  45644. */
  45645. getIndex: function (location, name) {
  45646. for (var i = 0; i < location.length; i++)
  45647. {
  45648. if (location[i].name === name)
  45649. {
  45650. return i;
  45651. }
  45652. }
  45653. return null;
  45654. },
  45655. /**
  45656. * Gets the layer index based on its name.
  45657. *
  45658. * @method Phaser.Tilemap#getLayerIndex
  45659. * @param {string} name - The name of the layer to get.
  45660. * @return {number} The index of the layer in this tilemap, or null if not found.
  45661. */
  45662. getLayerIndex: function (name) {
  45663. return this.getIndex(this.layers, name);
  45664. },
  45665. /**
  45666. * Gets the tileset index based on its name.
  45667. *
  45668. * @method Phaser.Tilemap#getTilesetIndex
  45669. * @param {string} name - The name of the tileset to get.
  45670. * @return {number} The index of the tileset in this tilemap, or null if not found.
  45671. */
  45672. getTilesetIndex: function (name) {
  45673. return this.getIndex(this.tilesets, name);
  45674. },
  45675. /**
  45676. * Gets the image index based on its name.
  45677. *
  45678. * @method Phaser.Tilemap#getImageIndex
  45679. * @param {string} name - The name of the image to get.
  45680. * @return {number} The index of the image in this tilemap, or null if not found.
  45681. */
  45682. getImageIndex: function (name) {
  45683. return this.getIndex(this.images, name);
  45684. },
  45685. /**
  45686. * Gets the object index based on its name.
  45687. *
  45688. * @method Phaser.Tilemap#getObjectIndex
  45689. * @param {string} name - The name of the object to get.
  45690. * @return {number} The index of the object in this tilemap, or null if not found.
  45691. */
  45692. getObjectIndex: function (name) {
  45693. return this.getIndex(this.objects, name);
  45694. },
  45695. /**
  45696. * 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.
  45697. * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it.
  45698. * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback.
  45699. *
  45700. * @method Phaser.Tilemap#setTileIndexCallback
  45701. * @param {number|array} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for.
  45702. * @param {function} callback - The callback that will be invoked when the tile is collided with.
  45703. * @param {object} callbackContext - The context under which the callback is called.
  45704. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
  45705. */
  45706. setTileIndexCallback: function (indexes, callback, callbackContext, layer) {
  45707. layer = this.getLayer(layer);
  45708. if (typeof indexes === 'number')
  45709. {
  45710. // This may seem a bit wasteful, because it will cause empty array elements to be created, but the look-up cost is much
  45711. // less than having to iterate through the callbacks array hunting down tile indexes each frame, so I'll take the small memory hit.
  45712. this.layers[layer].callbacks[indexes] = { callback: callback, callbackContext: callbackContext };
  45713. }
  45714. else
  45715. {
  45716. for (var i = 0, len = indexes.length; i < len; i++)
  45717. {
  45718. this.layers[layer].callbacks[indexes[i]] = { callback: callback, callbackContext: callbackContext };
  45719. }
  45720. }
  45721. },
  45722. /**
  45723. * 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.
  45724. * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it.
  45725. * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback.
  45726. *
  45727. * @method Phaser.Tilemap#setTileLocationCallback
  45728. * @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels)
  45729. * @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels)
  45730. * @param {number} width - The width of the area to copy (given in tiles, not pixels)
  45731. * @param {number} height - The height of the area to copy (given in tiles, not pixels)
  45732. * @param {function} callback - The callback that will be invoked when the tile is collided with.
  45733. * @param {object} callbackContext - The context under which the callback is called.
  45734. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
  45735. */
  45736. setTileLocationCallback: function (x, y, width, height, callback, callbackContext, layer) {
  45737. layer = this.getLayer(layer);
  45738. this.copy(x, y, width, height, layer);
  45739. if (this._results.length < 2)
  45740. {
  45741. return;
  45742. }
  45743. for (var i = 1; i < this._results.length; i++)
  45744. {
  45745. this._results[i].setCollisionCallback(callback, callbackContext);
  45746. }
  45747. },
  45748. /**
  45749. * 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].
  45750. * The `collides` parameter controls if collision will be enabled (true) or disabled (false).
  45751. *
  45752. * @method Phaser.Tilemap#setCollision
  45753. * @param {number|array} indexes - Either a single tile index, or an array of tile IDs to be checked for collision.
  45754. * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision.
  45755. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
  45756. * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update.
  45757. */
  45758. setCollision: function (indexes, collides, layer, recalculate) {
  45759. if (typeof collides === 'undefined') { collides = true; }
  45760. if (typeof recalculate === 'undefined') { recalculate = true; }
  45761. layer = this.getLayer(layer);
  45762. if (typeof indexes === 'number')
  45763. {
  45764. return this.setCollisionByIndex(indexes, collides, layer, true);
  45765. }
  45766. else
  45767. {
  45768. // Collide all of the IDs given in the indexes array
  45769. for (var i = 0, len = indexes.length; i < len; i++)
  45770. {
  45771. this.setCollisionByIndex(indexes[i], collides, layer, false);
  45772. }
  45773. if (recalculate)
  45774. {
  45775. // Now re-calculate interesting faces
  45776. this.calculateFaces(layer);
  45777. }
  45778. }
  45779. },
  45780. /**
  45781. * Sets collision on a range of tiles where the tile IDs increment sequentially.
  45782. * 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.
  45783. * The `collides` parameter controls if collision will be enabled (true) or disabled (false).
  45784. *
  45785. * @method Phaser.Tilemap#setCollisionBetween
  45786. * @param {number} start - The first index of the tile to be set for collision.
  45787. * @param {number} stop - The last index of the tile to be set for collision.
  45788. * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision.
  45789. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
  45790. * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update.
  45791. */
  45792. setCollisionBetween: function (start, stop, collides, layer, recalculate) {
  45793. if (typeof collides === 'undefined') { collides = true; }
  45794. if (typeof recalculate === 'undefined') { recalculate = true; }
  45795. layer = this.getLayer(layer);
  45796. if (start > stop)
  45797. {
  45798. return;
  45799. }
  45800. for (var index = start; index <= stop; index++)
  45801. {
  45802. this.setCollisionByIndex(index, collides, layer, false);
  45803. }
  45804. if (recalculate)
  45805. {
  45806. // Now re-calculate interesting faces
  45807. this.calculateFaces(layer);
  45808. }
  45809. },
  45810. /**
  45811. * Sets collision on all tiles in the given layer, except for the IDs of those in the given array.
  45812. * The `collides` parameter controls if collision will be enabled (true) or disabled (false).
  45813. *
  45814. * @method Phaser.Tilemap#setCollisionByExclusion
  45815. * @param {array} indexes - An array of the tile IDs to not be counted for collision.
  45816. * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision.
  45817. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
  45818. * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update.
  45819. */
  45820. setCollisionByExclusion: function (indexes, collides, layer, recalculate) {
  45821. if (typeof collides === 'undefined') { collides = true; }
  45822. if (typeof recalculate === 'undefined') { recalculate = true; }
  45823. layer = this.getLayer(layer);
  45824. // Collide everything, except the IDs given in the indexes array
  45825. for (var i = 0, len = this.tiles.length; i < len; i++)
  45826. {
  45827. if (indexes.indexOf(i) === -1)
  45828. {
  45829. this.setCollisionByIndex(i, collides, layer, false);
  45830. }
  45831. }
  45832. if (recalculate)
  45833. {
  45834. // Now re-calculate interesting faces
  45835. this.calculateFaces(layer);
  45836. }
  45837. },
  45838. /**
  45839. * Sets collision values on a tile in the set.
  45840. * You shouldn't usually call this method directly, instead use setCollision, setCollisionBetween or setCollisionByExclusion.
  45841. *
  45842. * @method Phaser.Tilemap#setCollisionByIndex
  45843. * @protected
  45844. * @param {number} index - The index of the tile on the layer.
  45845. * @param {boolean} [collides=true] - If true it will enable collision on the tile. If false it will clear collision values from the tile.
  45846. * @param {number} [layer] - The layer to operate on. If not given will default to this.currentLayer.
  45847. * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update.
  45848. */
  45849. setCollisionByIndex: function (index, collides, layer, recalculate) {
  45850. if (typeof collides === 'undefined') { collides = true; }
  45851. if (typeof layer === 'undefined') { layer = this.currentLayer; }
  45852. if (typeof recalculate === 'undefined') { recalculate = true; }
  45853. if (collides)
  45854. {
  45855. this.collideIndexes.push(index);
  45856. }
  45857. else
  45858. {
  45859. var i = this.collideIndexes.indexOf(index);
  45860. if (i > -1)
  45861. {
  45862. this.collideIndexes.splice(i, 1);
  45863. }
  45864. }
  45865. for (var y = 0; y < this.layers[layer].height; y++)
  45866. {
  45867. for (var x = 0; x < this.layers[layer].width; x++)
  45868. {
  45869. var tile = this.layers[layer].data[y][x];
  45870. if (tile && tile.index === index)
  45871. {
  45872. if (collides)
  45873. {
  45874. tile.setCollision(true, true, true, true);
  45875. }
  45876. else
  45877. {
  45878. tile.resetCollision();
  45879. }
  45880. tile.faceTop = collides;
  45881. tile.faceBottom = collides;
  45882. tile.faceLeft = collides;
  45883. tile.faceRight = collides;
  45884. }
  45885. }
  45886. }
  45887. if (recalculate)
  45888. {
  45889. // Now re-calculate interesting faces
  45890. this.calculateFaces(layer);
  45891. }
  45892. return layer;
  45893. },
  45894. /**
  45895. * Gets the TilemapLayer index as used in the setCollision calls.
  45896. *
  45897. * @method Phaser.Tilemap#getLayer
  45898. * @protected
  45899. * @param {number|string|Phaser.TilemapLayer} layer - The layer to operate on. If not given will default to this.currentLayer.
  45900. * @return {number} The TilemapLayer index.
  45901. */
  45902. getLayer: function (layer) {
  45903. if (typeof layer === 'undefined')
  45904. {
  45905. layer = this.currentLayer;
  45906. }
  45907. // else if (typeof layer === 'number')
  45908. // {
  45909. // layer = layer;
  45910. // }
  45911. else if (typeof layer === 'string')
  45912. {
  45913. layer = this.getLayerIndex(layer);
  45914. }
  45915. else if (layer instanceof Phaser.TilemapLayer)
  45916. {
  45917. layer = layer.index;
  45918. }
  45919. return layer;
  45920. },
  45921. /**
  45922. * Turn off/on the recalculation of faces for tile or collission updates.
  45923. * setPreventRecalculate(true) puts recalculation on hold while
  45924. * setPreventRecalculate(false) recalculates all the changed layers.
  45925. *
  45926. * @method Phaser.Tilemap#setPreventRecalculate
  45927. * @param {boolean} if true it will put the recalculation on hold.
  45928. */
  45929. setPreventRecalculate: function (value) {
  45930. if((value===true)&&(this.preventingRecalculate!==true)){
  45931. this.preventingRecalculate = true;
  45932. this.needToRecalculate = {};
  45933. }
  45934. if((value===false)&&(this.preventingRecalculate===true)){
  45935. this.preventingRecalculate = false;
  45936. for(var i in this.needToRecalculate){
  45937. this.calculateFaces(i);
  45938. }
  45939. this.needToRecalculate = false;
  45940. }
  45941. },
  45942. /**
  45943. * Internal function.
  45944. *
  45945. * @method Phaser.Tilemap#calculateFaces
  45946. * @protected
  45947. * @param {number} layer - The index of the TilemapLayer to operate on.
  45948. */
  45949. calculateFaces: function (layer) {
  45950. if(this.preventingRecalculate===true){
  45951. this.needToRecalculate[layer] = true;
  45952. return;
  45953. }
  45954. var above = null;
  45955. var below = null;
  45956. var left = null;
  45957. var right = null;
  45958. for (var y = 0, h = this.layers[layer].height; y < h; y++)
  45959. {
  45960. for (var x = 0, w = this.layers[layer].width; x < w; x++)
  45961. {
  45962. var tile = this.layers[layer].data[y][x];
  45963. if (tile)
  45964. {
  45965. above = this.getTileAbove(layer, x, y);
  45966. below = this.getTileBelow(layer, x, y);
  45967. left = this.getTileLeft(layer, x, y);
  45968. right = this.getTileRight(layer, x, y);
  45969. if (tile.collides)
  45970. {
  45971. tile.faceTop = true;
  45972. tile.faceBottom = true;
  45973. tile.faceLeft = true;
  45974. tile.faceRight = true;
  45975. }
  45976. if (above && above.collides)
  45977. {
  45978. // There is a tile above this one that also collides, so the top of this tile is no longer interesting
  45979. tile.faceTop = false;
  45980. }
  45981. if (below && below.collides)
  45982. {
  45983. // There is a tile below this one that also collides, so the bottom of this tile is no longer interesting
  45984. tile.faceBottom = false;
  45985. }
  45986. if (left && left.collides)
  45987. {
  45988. // There is a tile left this one that also collides, so the left of this tile is no longer interesting
  45989. tile.faceLeft = false;
  45990. }
  45991. if (right && right.collides)
  45992. {
  45993. // There is a tile right this one that also collides, so the right of this tile is no longer interesting
  45994. tile.faceRight = false;
  45995. }
  45996. }
  45997. }
  45998. }
  45999. },
  46000. /**
  46001. * Gets the tile above the tile coordinates given.
  46002. * Mostly used as an internal function by calculateFaces.
  46003. *
  46004. * @method Phaser.Tilemap#getTileAbove
  46005. * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
  46006. * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
  46007. * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
  46008. */
  46009. getTileAbove: function (layer, x, y) {
  46010. if (y > 0)
  46011. {
  46012. return this.layers[layer].data[y - 1][x];
  46013. }
  46014. return null;
  46015. },
  46016. /**
  46017. * Gets the tile below the tile coordinates given.
  46018. * Mostly used as an internal function by calculateFaces.
  46019. *
  46020. * @method Phaser.Tilemap#getTileBelow
  46021. * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
  46022. * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
  46023. * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
  46024. */
  46025. getTileBelow: function (layer, x, y) {
  46026. if (y < this.layers[layer].height - 1)
  46027. {
  46028. return this.layers[layer].data[y + 1][x];
  46029. }
  46030. return null;
  46031. },
  46032. /**
  46033. * Gets the tile to the left of the tile coordinates given.
  46034. * Mostly used as an internal function by calculateFaces.
  46035. *
  46036. * @method Phaser.Tilemap#getTileLeft
  46037. * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
  46038. * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
  46039. * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
  46040. */
  46041. getTileLeft: function (layer, x, y) {
  46042. if (x > 0)
  46043. {
  46044. return this.layers[layer].data[y][x - 1];
  46045. }
  46046. return null;
  46047. },
  46048. /**
  46049. * Gets the tile to the right of the tile coordinates given.
  46050. * Mostly used as an internal function by calculateFaces.
  46051. *
  46052. * @method Phaser.Tilemap#getTileRight
  46053. * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
  46054. * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
  46055. * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
  46056. */
  46057. getTileRight: function (layer, x, y) {
  46058. if (x < this.layers[layer].width - 1)
  46059. {
  46060. return this.layers[layer].data[y][x + 1];
  46061. }
  46062. return null;
  46063. },
  46064. /**
  46065. * Sets the current layer to the given index.
  46066. *
  46067. * @method Phaser.Tilemap#setLayer
  46068. * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current.
  46069. */
  46070. setLayer: function (layer) {
  46071. layer = this.getLayer(layer);
  46072. if (this.layers[layer])
  46073. {
  46074. this.currentLayer = layer;
  46075. }
  46076. },
  46077. /**
  46078. * Checks if there is a tile at the given location.
  46079. *
  46080. * @method Phaser.Tilemap#hasTile
  46081. * @param {number} x - X position to check if a tile exists at (given in tile units, not pixels)
  46082. * @param {number} y - Y position to check if a tile exists at (given in tile units, not pixels)
  46083. * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current.
  46084. * @return {boolean} True if there is a tile at the given location, otherwise false.
  46085. */
  46086. hasTile: function (x, y, layer) {
  46087. layer = this.getLayer(layer);
  46088. return (this.layers[layer].data[y] !== null && this.layers[layer].data[y][x] !== null);
  46089. },
  46090. /**
  46091. * Removes the tile located at the given coordinates and updates the collision data.
  46092. *
  46093. * @method Phaser.Tilemap#removeTile
  46094. * @param {number} x - X position to place the tile (given in tile units, not pixels)
  46095. * @param {number} y - Y position to place the tile (given in tile units, not pixels)
  46096. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify.
  46097. * @return {Phaser.Tile} The Tile object that was removed from this map.
  46098. */
  46099. removeTile: function (x, y, layer) {
  46100. layer = this.getLayer(layer);
  46101. if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height)
  46102. {
  46103. if (this.hasTile(x, y, layer))
  46104. {
  46105. var tile = this.layers[layer].data[y][x];
  46106. this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], -1, x, y, this.tileWidth, this.tileHeight);
  46107. this.layers[layer].dirty = true;
  46108. this.calculateFaces(layer);
  46109. return tile;
  46110. }
  46111. }
  46112. },
  46113. /**
  46114. * Removes the tile located at the given coordinates and updates the collision data. The coordinates are given in pixel values.
  46115. *
  46116. * @method Phaser.Tilemap#removeTileWorldXY
  46117. * @param {number} x - X position to insert the tile (given in pixels)
  46118. * @param {number} y - Y position to insert the tile (given in pixels)
  46119. * @param {number} tileWidth - The width of the tile in pixels.
  46120. * @param {number} tileHeight - The height of the tile in pixels.
  46121. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify.
  46122. * @return {Phaser.Tile} The Tile object that was removed from this map.
  46123. */
  46124. removeTileWorldXY: function (x, y, tileWidth, tileHeight, layer) {
  46125. layer = this.getLayer(layer);
  46126. x = this.game.math.snapToFloor(x, tileWidth) / tileWidth;
  46127. y = this.game.math.snapToFloor(y, tileHeight) / tileHeight;
  46128. return this.removeTile(x, y, layer);
  46129. },
  46130. /**
  46131. * Puts a tile of the given index value at the coordinate specified.
  46132. * If you pass `null` as the tile it will pass your call over to Tilemap.removeTile instead.
  46133. *
  46134. * @method Phaser.Tilemap#putTile
  46135. * @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.
  46136. * @param {number} x - X position to place the tile (given in tile units, not pixels)
  46137. * @param {number} y - Y position to place the tile (given in tile units, not pixels)
  46138. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify.
  46139. * @return {Phaser.Tile} The Tile object that was created or added to this map.
  46140. */
  46141. putTile: function (tile, x, y, layer) {
  46142. if (tile === null)
  46143. {
  46144. return this.removeTile(x, y, layer);
  46145. }
  46146. layer = this.getLayer(layer);
  46147. if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height)
  46148. {
  46149. var index;
  46150. if (tile instanceof Phaser.Tile)
  46151. {
  46152. index = tile.index;
  46153. if (this.hasTile(x, y, layer))
  46154. {
  46155. this.layers[layer].data[y][x].copy(tile);
  46156. }
  46157. else
  46158. {
  46159. this.layers[layer].data[y][x] = new Phaser.Tile(layer, index, x, y, tile.width, tile.height);
  46160. }
  46161. }
  46162. else
  46163. {
  46164. index = tile;
  46165. if (this.hasTile(x, y, layer))
  46166. {
  46167. this.layers[layer].data[y][x].index = index;
  46168. }
  46169. else
  46170. {
  46171. this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], index, x, y, this.tileWidth, this.tileHeight);
  46172. }
  46173. }
  46174. if (this.collideIndexes.indexOf(index) > -1)
  46175. {
  46176. this.layers[layer].data[y][x].setCollision(true, true, true, true);
  46177. }
  46178. else
  46179. {
  46180. this.layers[layer].data[y][x].resetCollision();
  46181. }
  46182. this.layers[layer].dirty = true;
  46183. this.calculateFaces(layer);
  46184. return this.layers[layer].data[y][x];
  46185. }
  46186. return null;
  46187. },
  46188. /**
  46189. * Puts a tile into the Tilemap layer. The coordinates are given in pixel values.
  46190. *
  46191. * @method Phaser.Tilemap#putTileWorldXY
  46192. * @param {Phaser.Tile|number} tile - The index of this tile to set or a Phaser.Tile object.
  46193. * @param {number} x - X position to insert the tile (given in pixels)
  46194. * @param {number} y - Y position to insert the tile (given in pixels)
  46195. * @param {number} tileWidth - The width of the tile in pixels.
  46196. * @param {number} tileHeight - The height of the tile in pixels.
  46197. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify.
  46198. * @return {Phaser.Tile} The Tile object that was created or added to this map.
  46199. */
  46200. putTileWorldXY: function (tile, x, y, tileWidth, tileHeight, layer) {
  46201. layer = this.getLayer(layer);
  46202. x = this.game.math.snapToFloor(x, tileWidth) / tileWidth;
  46203. y = this.game.math.snapToFloor(y, tileHeight) / tileHeight;
  46204. return this.putTile(tile, x, y, layer);
  46205. },
  46206. /**
  46207. * Searches the entire map layer for the first tile matching the given index, then returns that Phaser.Tile object.
  46208. * If no match is found it returns null.
  46209. * 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.
  46210. * If the reverse boolean is true, it scans starting from the bottom-right corner travelling up to the top-left.
  46211. *
  46212. * @method Phaser.Tilemap#searchTileIndex
  46213. * @param {number} index - The tile index value to search for.
  46214. * @param {number} [skip=0] - The number of times to skip a matching tile before returning.
  46215. * @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.
  46216. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from.
  46217. * @return {Phaser.Tile} The first (or n skipped) tile with the matching index.
  46218. */
  46219. searchTileIndex: function (index, skip, reverse, layer) {
  46220. if (typeof skip === 'undefined') { skip = 0; }
  46221. if (typeof reverse === 'undefined') { reverse = false; }
  46222. layer = this.getLayer(layer);
  46223. var c = 0;
  46224. if (reverse)
  46225. {
  46226. for (var y = this.layers[layer].height - 1; y >= 0; y--)
  46227. {
  46228. for (var x = this.layers[layer].width - 1; x >= 0; x--)
  46229. {
  46230. if (this.layers[layer].data[y][x].index === index)
  46231. {
  46232. if (c === skip)
  46233. {
  46234. return this.layers[layer].data[y][x];
  46235. }
  46236. else
  46237. {
  46238. c++;
  46239. }
  46240. }
  46241. }
  46242. }
  46243. }
  46244. else
  46245. {
  46246. for (var y = 0; y < this.layers[layer].height; y++)
  46247. {
  46248. for (var x = 0; x < this.layers[layer].width; x++)
  46249. {
  46250. if (this.layers[layer].data[y][x].index === index)
  46251. {
  46252. if (c === skip)
  46253. {
  46254. return this.layers[layer].data[y][x];
  46255. }
  46256. else
  46257. {
  46258. c++;
  46259. }
  46260. }
  46261. }
  46262. }
  46263. }
  46264. return null;
  46265. },
  46266. /**
  46267. * Gets a tile from the Tilemap Layer. The coordinates are given in tile values.
  46268. *
  46269. * @method Phaser.Tilemap#getTile
  46270. * @param {number} x - X position to get the tile from (given in tile units, not pixels)
  46271. * @param {number} y - Y position to get the tile from (given in tile units, not pixels)
  46272. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from.
  46273. * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1.
  46274. * @return {Phaser.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid.
  46275. */
  46276. getTile: function (x, y, layer, nonNull) {
  46277. if (typeof nonNull === 'undefined') { nonNull = false; }
  46278. layer = this.getLayer(layer);
  46279. if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height)
  46280. {
  46281. if (this.layers[layer].data[y][x].index === -1)
  46282. {
  46283. if (nonNull)
  46284. {
  46285. return this.layers[layer].data[y][x];
  46286. }
  46287. else
  46288. {
  46289. return null;
  46290. }
  46291. }
  46292. else
  46293. {
  46294. return this.layers[layer].data[y][x];
  46295. }
  46296. }
  46297. else
  46298. {
  46299. return null;
  46300. }
  46301. },
  46302. /**
  46303. * Gets a tile from the Tilemap layer. The coordinates are given in pixel values.
  46304. *
  46305. * @method Phaser.Tilemap#getTileWorldXY
  46306. * @param {number} x - X position to get the tile from (given in pixels)
  46307. * @param {number} y - Y position to get the tile from (given in pixels)
  46308. * @param {number} [tileWidth] - The width of the tiles. If not given the map default is used.
  46309. * @param {number} [tileHeight] - The height of the tiles. If not given the map default is used.
  46310. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from.
  46311. * @return {Phaser.Tile} The tile at the given coordinates.
  46312. */
  46313. getTileWorldXY: function (x, y, tileWidth, tileHeight, layer) {
  46314. if (typeof tileWidth === 'undefined') { tileWidth = this.tileWidth; }
  46315. if (typeof tileHeight === 'undefined') { tileHeight = this.tileHeight; }
  46316. layer = this.getLayer(layer);
  46317. x = this.game.math.snapToFloor(x, tileWidth) / tileWidth;
  46318. y = this.game.math.snapToFloor(y, tileHeight) / tileHeight;
  46319. return this.getTile(x, y, layer);
  46320. },
  46321. /**
  46322. * Copies all of the tiles in the given rectangular block into the tilemap data buffer.
  46323. *
  46324. * @method Phaser.Tilemap#copy
  46325. * @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels)
  46326. * @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels)
  46327. * @param {number} width - The width of the area to copy (given in tiles, not pixels)
  46328. * @param {number} height - The height of the area to copy (given in tiles, not pixels)
  46329. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to copy the tiles from.
  46330. * @return {array} An array of the tiles that were copied.
  46331. */
  46332. copy: function (x, y, width, height, layer) {
  46333. layer = this.getLayer(layer);
  46334. if (!this.layers[layer])
  46335. {
  46336. this._results.length = 0;
  46337. return;
  46338. }
  46339. if (typeof x === "undefined") { x = 0; }
  46340. if (typeof y === "undefined") { y = 0; }
  46341. if (typeof width === "undefined") { width = this.layers[layer].width; }
  46342. if (typeof height === "undefined") { height = this.layers[layer].height; }
  46343. if (x < 0)
  46344. {
  46345. x = 0;
  46346. }
  46347. if (y < 0)
  46348. {
  46349. y = 0;
  46350. }
  46351. if (width > this.layers[layer].width)
  46352. {
  46353. width = this.layers[layer].width;
  46354. }
  46355. if (height > this.layers[layer].height)
  46356. {
  46357. height = this.layers[layer].height;
  46358. }
  46359. this._results.length = 0;
  46360. this._results.push({ x: x, y: y, width: width, height: height, layer: layer });
  46361. for (var ty = y; ty < y + height; ty++)
  46362. {
  46363. for (var tx = x; tx < x + width; tx++)
  46364. {
  46365. this._results.push(this.layers[layer].data[ty][tx]);
  46366. }
  46367. }
  46368. return this._results;
  46369. },
  46370. /**
  46371. * Pastes a previously copied block of tile data into the given x/y coordinates. Data should have been prepared with Tilemap.copy.
  46372. *
  46373. * @method Phaser.Tilemap#paste
  46374. * @param {number} x - X position of the top left of the area to paste to (given in tiles, not pixels)
  46375. * @param {number} y - Y position of the top left of the area to paste to (given in tiles, not pixels)
  46376. * @param {array} tileblock - The block of tiles to paste.
  46377. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to paste the tiles into.
  46378. */
  46379. paste: function (x, y, tileblock, layer) {
  46380. if (typeof x === "undefined") { x = 0; }
  46381. if (typeof y === "undefined") { y = 0; }
  46382. layer = this.getLayer(layer);
  46383. if (!tileblock || tileblock.length < 2)
  46384. {
  46385. return;
  46386. }
  46387. // 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
  46388. var diffX = tileblock[1].x - x;
  46389. var diffY = tileblock[1].y - y;
  46390. for (var i = 1; i < tileblock.length; i++)
  46391. {
  46392. this.layers[layer].data[ diffY + tileblock[i].y ][ diffX + tileblock[i].x ].copy(tileblock[i]);
  46393. }
  46394. this.layers[layer].dirty = true;
  46395. this.calculateFaces(layer);
  46396. },
  46397. /**
  46398. * Scans the given area for tiles with an index matching tileA and swaps them with tileB.
  46399. *
  46400. * @method Phaser.Tilemap#swap
  46401. * @param {number} tileA - First tile index.
  46402. * @param {number} tileB - Second tile index.
  46403. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  46404. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  46405. * @param {number} width - The width in tiles of the area to operate on.
  46406. * @param {number} height - The height in tiles of the area to operate on.
  46407. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  46408. */
  46409. swap: function (tileA, tileB, x, y, width, height, layer) {
  46410. layer = this.getLayer(layer);
  46411. this.copy(x, y, width, height, layer);
  46412. if (this._results.length < 2)
  46413. {
  46414. return;
  46415. }
  46416. this._tempA = tileA;
  46417. this._tempB = tileB;
  46418. this._results.forEach(this.swapHandler, this);
  46419. this.paste(x, y, this._results, layer);
  46420. },
  46421. /**
  46422. * Internal function that handles the swapping of tiles.
  46423. *
  46424. * @method Phaser.Tilemap#swapHandler
  46425. * @private
  46426. * @param {number} value
  46427. */
  46428. swapHandler: function (value) {
  46429. if (value.index === this._tempA)
  46430. {
  46431. // Swap A with B
  46432. value.index = this._tempB;
  46433. }
  46434. else if (value.index === this._tempB)
  46435. {
  46436. // Swap B with A
  46437. value.index = this._tempA;
  46438. }
  46439. },
  46440. /**
  46441. * For each tile in the given area defined by x/y and width/height run the given callback.
  46442. *
  46443. * @method Phaser.Tilemap#forEach
  46444. * @param {number} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter.
  46445. * @param {number} context - The context under which the callback should be run.
  46446. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  46447. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  46448. * @param {number} width - The width in tiles of the area to operate on.
  46449. * @param {number} height - The height in tiles of the area to operate on.
  46450. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  46451. */
  46452. forEach: function (callback, context, x, y, width, height, layer) {
  46453. layer = this.getLayer(layer);
  46454. this.copy(x, y, width, height, layer);
  46455. if (this._results.length < 2)
  46456. {
  46457. return;
  46458. }
  46459. this._results.forEach(callback, context);
  46460. this.paste(x, y, this._results, layer);
  46461. },
  46462. /**
  46463. * Scans the given area for tiles with an index matching `source` and updates their index to match `dest`.
  46464. *
  46465. * @method Phaser.Tilemap#replace
  46466. * @param {number} source - The tile index value to scan for.
  46467. * @param {number} dest - The tile index value to replace found tiles with.
  46468. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  46469. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  46470. * @param {number} width - The width in tiles of the area to operate on.
  46471. * @param {number} height - The height in tiles of the area to operate on.
  46472. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  46473. */
  46474. replace: function (source, dest, x, y, width, height, layer) {
  46475. layer = this.getLayer(layer);
  46476. this.copy(x, y, width, height, layer);
  46477. if (this._results.length < 2)
  46478. {
  46479. return;
  46480. }
  46481. for (var i = 1; i < this._results.length; i++)
  46482. {
  46483. if (this._results[i].index === source)
  46484. {
  46485. this._results[i].index = dest;
  46486. }
  46487. }
  46488. this.paste(x, y, this._results, layer);
  46489. },
  46490. /**
  46491. * Randomises a set of tiles in a given area.
  46492. *
  46493. * @method Phaser.Tilemap#random
  46494. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  46495. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  46496. * @param {number} width - The width in tiles of the area to operate on.
  46497. * @param {number} height - The height in tiles of the area to operate on.
  46498. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  46499. */
  46500. random: function (x, y, width, height, layer) {
  46501. layer = this.getLayer(layer);
  46502. this.copy(x, y, width, height, layer);
  46503. if (this._results.length < 2)
  46504. {
  46505. return;
  46506. }
  46507. var indexes = [];
  46508. for (var t = 1; t < this._results.length; t++)
  46509. {
  46510. if (this._results[t].index)
  46511. {
  46512. var idx = this._results[t].index;
  46513. if (indexes.indexOf(idx) === -1)
  46514. {
  46515. indexes.push(idx);
  46516. }
  46517. }
  46518. }
  46519. for (var i = 1; i < this._results.length; i++)
  46520. {
  46521. this._results[i].index = this.game.rnd.pick(indexes);
  46522. }
  46523. this.paste(x, y, this._results, layer);
  46524. },
  46525. /**
  46526. * 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!
  46527. *
  46528. * @method Phaser.Tilemap#shuffle
  46529. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  46530. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  46531. * @param {number} width - The width in tiles of the area to operate on.
  46532. * @param {number} height - The height in tiles of the area to operate on.
  46533. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  46534. */
  46535. shuffle: function (x, y, width, height, layer) {
  46536. layer = this.getLayer(layer);
  46537. this.copy(x, y, width, height, layer);
  46538. if (this._results.length < 2)
  46539. {
  46540. return;
  46541. }
  46542. var indexes = [];
  46543. for (var t = 1; t < this._results.length; t++)
  46544. {
  46545. if (this._results[t].index)
  46546. {
  46547. indexes.push(this._results[t].index);
  46548. }
  46549. }
  46550. Phaser.Utils.shuffle(indexes);
  46551. for (var i = 1; i < this._results.length; i++)
  46552. {
  46553. this._results[i].index = indexes[i - 1];
  46554. }
  46555. this.paste(x, y, this._results, layer);
  46556. },
  46557. /**
  46558. * Fills the given area with the specified tile.
  46559. *
  46560. * @method Phaser.Tilemap#fill
  46561. * @param {number} index - The index of the tile that the area will be filled with.
  46562. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  46563. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  46564. * @param {number} width - The width in tiles of the area to operate on.
  46565. * @param {number} height - The height in tiles of the area to operate on.
  46566. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  46567. */
  46568. fill: function (index, x, y, width, height, layer) {
  46569. layer = this.getLayer(layer);
  46570. this.copy(x, y, width, height, layer);
  46571. if (this._results.length < 2)
  46572. {
  46573. return;
  46574. }
  46575. for (var i = 1; i < this._results.length; i++)
  46576. {
  46577. this._results[i].index = index;
  46578. }
  46579. this.paste(x, y, this._results, layer);
  46580. },
  46581. /**
  46582. * Removes all layers from this tile map.
  46583. *
  46584. * @method Phaser.Tilemap#removeAllLayers
  46585. */
  46586. removeAllLayers: function () {
  46587. this.layers.length = 0;
  46588. this.currentLayer = 0;
  46589. },
  46590. /**
  46591. * Dumps the tilemap data out to the console.
  46592. *
  46593. * @method Phaser.Tilemap#dump
  46594. */
  46595. dump: function () {
  46596. var txt = '';
  46597. var args = [''];
  46598. for (var y = 0; y < this.layers[this.currentLayer].height; y++)
  46599. {
  46600. for (var x = 0; x < this.layers[this.currentLayer].width; x++)
  46601. {
  46602. txt += "%c ";
  46603. if (this.layers[this.currentLayer].data[y][x] > 1)
  46604. {
  46605. if (this.debugMap[this.layers[this.currentLayer].data[y][x]])
  46606. {
  46607. args.push("background: " + this.debugMap[this.layers[this.currentLayer].data[y][x]]);
  46608. }
  46609. else
  46610. {
  46611. args.push("background: #ffffff");
  46612. }
  46613. }
  46614. else
  46615. {
  46616. args.push("background: rgb(0, 0, 0)");
  46617. }
  46618. }
  46619. txt += "\n";
  46620. }
  46621. args[0] = txt;
  46622. console.log.apply(console, args);
  46623. },
  46624. /**
  46625. * Removes all layer data from this tile map and nulls the game reference.
  46626. * Note: You are responsible for destroying any TilemapLayer objects you generated yourself, as Tilemap doesn't keep a reference to them.
  46627. *
  46628. * @method Phaser.Tilemap#destroy
  46629. */
  46630. destroy: function () {
  46631. this.removeAllLayers();
  46632. this.data = [];
  46633. this.game = null;
  46634. }
  46635. };
  46636. Phaser.Tilemap.prototype.constructor = Phaser.Tilemap;
  46637. /**
  46638. * @name Phaser.Tilemap#layer
  46639. * @property {number|string|Phaser.TilemapLayer} layer - The current layer object.
  46640. */
  46641. Object.defineProperty(Phaser.Tilemap.prototype, "layer", {
  46642. get: function () {
  46643. return this.layers[this.currentLayer];
  46644. },
  46645. set: function (value) {
  46646. if (value !== this.currentLayer)
  46647. {
  46648. this.setLayer(value);
  46649. }
  46650. }
  46651. });
  46652. /**
  46653. * @author Richard Davey <rich@photonstorm.com>
  46654. * @copyright 2014 Photon Storm Ltd.
  46655. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  46656. */
  46657. /**
  46658. * A Tilemap Layer is a set of map data combined with a Tileset in order to render that data to the game.
  46659. *
  46660. * @class Phaser.TilemapLayer
  46661. * @constructor
  46662. * @param {Phaser.Game} game - Game reference to the currently running game.
  46663. * @param {Phaser.Tilemap} tilemap - The tilemap to which this layer belongs.
  46664. * @param {number} index - The layer index within the map that this TilemapLayer represents.
  46665. * @param {number} width - Width of the renderable area of the layer.
  46666. * @param {number} height - Height of the renderable area of the layer.
  46667. */
  46668. Phaser.TilemapLayer = function (game, tilemap, index, width, height) {
  46669. /**
  46670. * @property {Phaser.Game} game - A reference to the currently running Game.
  46671. */
  46672. this.game = game;
  46673. /**
  46674. * @property {Phaser.Tilemap} map - The Tilemap to which this layer is bound.
  46675. */
  46676. this.map = tilemap;
  46677. /**
  46678. * @property {number} index - The index of this layer within the Tilemap.
  46679. */
  46680. this.index = index;
  46681. /**
  46682. * @property {object} layer - The layer object within the Tilemap that this layer represents.
  46683. */
  46684. this.layer = tilemap.layers[index];
  46685. /**
  46686. * @property {HTMLCanvasElement} canvas - The canvas to which this TilemapLayer draws.
  46687. */
  46688. this.canvas = Phaser.Canvas.create(width, height, '', true);
  46689. /**
  46690. * @property {CanvasRenderingContext2D} context - The 2d context of the canvas.
  46691. */
  46692. this.context = this.canvas.getContext('2d');
  46693. /**
  46694. * @property {PIXI.BaseTexture} baseTexture - Required Pixi var.
  46695. */
  46696. this.baseTexture = new PIXI.BaseTexture(this.canvas);
  46697. /**
  46698. * @property {PIXI.Texture} texture - Required Pixi var.
  46699. */
  46700. this.texture = new PIXI.Texture(this.baseTexture);
  46701. /**
  46702. * @property {Phaser.Frame} textureFrame - Dimensions of the renderable area.
  46703. */
  46704. this.textureFrame = new Phaser.Frame(0, 0, 0, width, height, 'tilemapLayer', game.rnd.uuid());
  46705. Phaser.Image.call(this, this.game, 0, 0, this.texture, this.textureFrame);
  46706. /**
  46707. * @property {string} name - The name of the layer.
  46708. */
  46709. this.name = '';
  46710. /**
  46711. * @property {number} type - The const type of this object.
  46712. * @default
  46713. */
  46714. this.type = Phaser.TILEMAPLAYER;
  46715. /**
  46716. * An object that is fixed to the camera ignores the position of any ancestors in the display list and uses its x/y coordinates as offsets from the top left of the camera.
  46717. * @property {boolean} fixedToCamera - Fixes this object to the Camera.
  46718. * @default
  46719. */
  46720. this.fixedToCamera = true;
  46721. /**
  46722. * @property {Phaser.Point} cameraOffset - If this object is fixed to the camera then use this Point to specify how far away from the Camera x/y it's rendered.
  46723. */
  46724. this.cameraOffset = new Phaser.Point(0, 0);
  46725. /**
  46726. * @property {string} tileColor - If no tileset is given the tiles will be rendered as rectangles in this color. Provide in hex or rgb/rgba string format.
  46727. * @default
  46728. */
  46729. this.tileColor = 'rgb(255, 255, 255)';
  46730. /**
  46731. * @property {boolean} debug - If set to true the collideable tile edges path will be rendered. Only works when game is running in Phaser.CANVAS mode.
  46732. * @default
  46733. */
  46734. this.debug = false;
  46735. /**
  46736. * @property {number} debugAlpha - If debug is true then the tileset is rendered with this alpha level, to make the tile edges clearer.
  46737. * @default
  46738. */
  46739. this.debugAlpha = 0.5;
  46740. /**
  46741. * @property {string} debugColor - If debug is true this is the color used to outline the edges of collidable tiles. Provide in hex or rgb/rgba string format.
  46742. * @default
  46743. */
  46744. this.debugColor = 'rgba(0, 255, 0, 1)';
  46745. /**
  46746. * @property {boolean} debugFill - If true the debug tiles are filled with debugFillColor AND stroked around.
  46747. * @default
  46748. */
  46749. this.debugFill = false;
  46750. /**
  46751. * @property {string} debugFillColor - If debugFill is true this is the color used to fill the tiles. Provide in hex or rgb/rgba string format.
  46752. * @default
  46753. */
  46754. this.debugFillColor = 'rgba(0, 255, 0, 0.2)';
  46755. /**
  46756. * @property {string} debugCallbackColor - If debug is true this is the color used to outline the edges of tiles that have collision callbacks. Provide in hex or rgb/rgba string format.
  46757. * @default
  46758. */
  46759. this.debugCallbackColor = 'rgba(255, 0, 0, 1)';
  46760. /**
  46761. * @property {number} scrollFactorX - speed at which this layer scrolls
  46762. * horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls
  46763. * half as quickly as the 'normal' camera-locked layers do)
  46764. * @default 1
  46765. */
  46766. this.scrollFactorX = 1;
  46767. /**
  46768. * @property {number} scrollFactorY - speed at which this layer scrolls
  46769. * vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls
  46770. * half as quickly as the 'normal' camera-locked layers do)
  46771. * @default 1
  46772. */
  46773. this.scrollFactorY = 1;
  46774. /**
  46775. * @property {boolean} dirty - Flag controlling when to re-render the layer.
  46776. */
  46777. this.dirty = true;
  46778. /**
  46779. * @property {number} rayStepRate - 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.
  46780. * @default
  46781. */
  46782. this.rayStepRate = 4;
  46783. /**
  46784. * @property {boolean} wrap - Flag controlling if the layer tiles wrap at the edges. Only works if the World size matches the Map size.
  46785. * @default false
  46786. */
  46787. this.wrap = false;
  46788. /**
  46789. * @property {object} _mc - Local map data and calculation cache.
  46790. * @private
  46791. */
  46792. this._mc = {
  46793. cw: tilemap.tileWidth,
  46794. ch: tilemap.tileHeight,
  46795. ga: 1,
  46796. dx: 0,
  46797. dy: 0,
  46798. dw: 0,
  46799. dh: 0,
  46800. tx: 0,
  46801. ty: 0,
  46802. tw: 0,
  46803. th: 0,
  46804. tl: 0,
  46805. maxX: 0,
  46806. maxY: 0,
  46807. startX: 0,
  46808. startY: 0,
  46809. x: 0,
  46810. y: 0,
  46811. prevX: 0,
  46812. prevY: 0
  46813. };
  46814. /**
  46815. * @property {array} _results - Local render loop var to help avoid gc spikes.
  46816. * @private
  46817. */
  46818. this._results = [];
  46819. this.updateMax();
  46820. };
  46821. Phaser.TilemapLayer.prototype = Object.create(Phaser.Image.prototype);
  46822. Phaser.TilemapLayer.prototype.constructor = Phaser.TilemapLayer;
  46823. /**
  46824. * Automatically called by World.postUpdate. Handles cache updates.
  46825. *
  46826. * @method Phaser.TilemapLayer#postUpdate
  46827. * @memberof Phaser.TilemapLayer
  46828. */
  46829. Phaser.TilemapLayer.prototype.postUpdate = function () {
  46830. Phaser.Image.prototype.postUpdate.call(this);
  46831. // Stops you being able to auto-scroll the camera if it's not following a sprite
  46832. this.scrollX = this.game.camera.x * this.scrollFactorX;
  46833. this.scrollY = this.game.camera.y * this.scrollFactorY;
  46834. this.render();
  46835. // Fixed to Camera?
  46836. if (this._cache[7] === 1)
  46837. {
  46838. this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
  46839. this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
  46840. }
  46841. // Update any Children
  46842. // for (var i = 0, len = this.children.length; i < len; i++)
  46843. // {
  46844. // this.children[i].postUpdate();
  46845. // }
  46846. };
  46847. /**
  46848. * Sets the world size to match the size of this layer.
  46849. *
  46850. * @method Phaser.TilemapLayer#resizeWorld
  46851. * @memberof Phaser.TilemapLayer
  46852. */
  46853. Phaser.TilemapLayer.prototype.resizeWorld = function () {
  46854. this.game.world.setBounds(0, 0, this.layer.widthInPixels, this.layer.heightInPixels);
  46855. };
  46856. /**
  46857. * Take an x coordinate that doesn't account for scrollFactorX and 'fix' it
  46858. * into a scrolled local space. Used primarily internally
  46859. * @method Phaser.TilemapLayer#_fixX
  46860. * @memberof Phaser.TilemapLayer
  46861. * @private
  46862. * @param {number} x - x coordinate in camera space
  46863. * @return {number} x coordinate in scrollFactor-adjusted dimensions
  46864. */
  46865. Phaser.TilemapLayer.prototype._fixX = function(x) {
  46866. if (x < 0)
  46867. {
  46868. x = 0;
  46869. }
  46870. if (this.scrollFactorX === 1)
  46871. {
  46872. return x;
  46873. }
  46874. return this._mc.x + (x - (this._mc.x / this.scrollFactorX));
  46875. };
  46876. /**
  46877. * Take an x coordinate that _does_ account for scrollFactorX and 'unfix' it
  46878. * back to camera space. Used primarily internally
  46879. * @method Phaser.TilemapLayer#_unfixX
  46880. * @memberof Phaser.TilemapLayer
  46881. * @private
  46882. * @param {number} x - x coordinate in scrollFactor-adjusted dimensions
  46883. * @return {number} x coordinate in camera space
  46884. */
  46885. Phaser.TilemapLayer.prototype._unfixX = function(x) {
  46886. if (this.scrollFactorX === 1)
  46887. {
  46888. return x;
  46889. }
  46890. return (this._mc.x / this.scrollFactorX) + (x - this._mc.x);
  46891. };
  46892. /**
  46893. * Take a y coordinate that doesn't account for scrollFactorY and 'fix' it
  46894. * into a scrolled local space. Used primarily internally
  46895. * @method Phaser.TilemapLayer#_fixY
  46896. * @memberof Phaser.TilemapLayer
  46897. * @private
  46898. * @param {number} y - y coordinate in camera space
  46899. * @return {number} y coordinate in scrollFactor-adjusted dimensions
  46900. */
  46901. Phaser.TilemapLayer.prototype._fixY = function(y) {
  46902. if (y < 0)
  46903. {
  46904. y = 0;
  46905. }
  46906. if (this.scrollFactorY === 1)
  46907. {
  46908. return y;
  46909. }
  46910. return this._mc.y + (y - (this._mc.y / this.scrollFactorY));
  46911. };
  46912. /**
  46913. * Take a y coordinate that _does_ account for scrollFactorY and 'unfix' it
  46914. * back to camera space. Used primarily internally
  46915. * @method Phaser.TilemapLayer#_unfixY
  46916. * @memberof Phaser.TilemapLayer
  46917. * @private
  46918. * @param {number} y - y coordinate in scrollFactor-adjusted dimensions
  46919. * @return {number} y coordinate in camera space
  46920. */
  46921. Phaser.TilemapLayer.prototype._unfixY = function(y) {
  46922. if (this.scrollFactorY === 1)
  46923. {
  46924. return y;
  46925. }
  46926. return (this._mc.y / this.scrollFactorY) + (y - this._mc.y);
  46927. };
  46928. /**
  46929. * Convert a pixel value to a tile coordinate.
  46930. * @method Phaser.TilemapLayer#getTileX
  46931. * @memberof Phaser.TilemapLayer
  46932. * @param {number} x - X position of the point in target tile.
  46933. * @return {Phaser.Tile} The tile with specific properties.
  46934. */
  46935. Phaser.TilemapLayer.prototype.getTileX = function (x) {
  46936. // var tileWidth = this.tileWidth * this.scale.x;
  46937. return this.game.math.snapToFloor(this._fixX(x), this.map.tileWidth) / this.map.tileWidth;
  46938. };
  46939. /**
  46940. * Convert a pixel value to a tile coordinate.
  46941. * @method Phaser.TilemapLayer#getTileY
  46942. * @memberof Phaser.TilemapLayer
  46943. * @param {number} y - Y position of the point in target tile.
  46944. * @return {Phaser.Tile} The tile with specific properties.
  46945. */
  46946. Phaser.TilemapLayer.prototype.getTileY = function (y) {
  46947. // var tileHeight = this.tileHeight * this.scale.y;
  46948. return this.game.math.snapToFloor(this._fixY(y), this.map.tileHeight) / this.map.tileHeight;
  46949. };
  46950. /**
  46951. * Convert a pixel value to a tile coordinate.
  46952. * @method Phaser.TilemapLayer#getTileXY
  46953. * @memberof Phaser.TilemapLayer
  46954. * @param {number} x - X position of the point in target tile.
  46955. * @param {number} y - Y position of the point in target tile.
  46956. * @param {Phaser.Point|object} point - The Point object to set the x and y values on.
  46957. * @return {Phaser.Point|object} A Point object with its x and y properties set.
  46958. */
  46959. Phaser.TilemapLayer.prototype.getTileXY = function (x, y, point) {
  46960. point.x = this.getTileX(x);
  46961. point.y = this.getTileY(y);
  46962. return point;
  46963. };
  46964. /**
  46965. * Gets all tiles that intersect with the given line.
  46966. *
  46967. * @method Phaser.TilemapLayer#getRayCastTiles
  46968. * @memberof Phaser.TilemapLayer
  46969. * @param {Phaser.Line} line - The line used to determine which tiles to return.
  46970. * @param {number} [stepRate] - How many steps through the ray will we check? If undefined or null it uses TilemapLayer.rayStepRate.
  46971. * @param {boolean} [collides=false] - If true only return tiles that collide on one or more faces.
  46972. * @param {boolean} [interestingFace=false] - If true only return tiles that have interesting faces.
  46973. * @return {array<Phaser.Tile>} An array of Phaser.Tiles.
  46974. */
  46975. Phaser.TilemapLayer.prototype.getRayCastTiles = function (line, stepRate, collides, interestingFace) {
  46976. if (typeof stepRate === 'undefined' || stepRate === null) { stepRate = this.rayStepRate; }
  46977. if (typeof collides === 'undefined') { collides = false; }
  46978. if (typeof interestingFace === 'undefined') { interestingFace = false; }
  46979. // First get all tiles that touch the bounds of the line
  46980. var tiles = this.getTiles(line.x, line.y, line.width, line.height, collides, interestingFace);
  46981. if (tiles.length === 0)
  46982. {
  46983. return [];
  46984. }
  46985. // Now we only want the tiles that intersect with the points on this line
  46986. var coords = line.coordinatesOnLine(stepRate);
  46987. var total = coords.length;
  46988. var results = [];
  46989. for (var i = 0; i < tiles.length; i++)
  46990. {
  46991. for (var t = 0; t < total; t++)
  46992. {
  46993. if (tiles[i].containsPoint(coords[t][0], coords[t][1]))
  46994. {
  46995. results.push(tiles[i]);
  46996. break;
  46997. }
  46998. }
  46999. }
  47000. return results;
  47001. };
  47002. /**
  47003. * 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.
  47004. * @method Phaser.TilemapLayer#getTiles
  47005. * @memberof Phaser.TilemapLayer
  47006. * @param {number} x - X position of the top left corner.
  47007. * @param {number} y - Y position of the top left corner.
  47008. * @param {number} width - Width of the area to get.
  47009. * @param {number} height - Height of the area to get.
  47010. * @param {boolean} [collides=false] - If true only return tiles that collide on one or more faces.
  47011. * @param {boolean} [interestingFace=false] - If true only return tiles that have interesting faces.
  47012. * @return {array<Phaser.Tile>} An array of Phaser.Tiles.
  47013. */
  47014. Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides, interestingFace) {
  47015. // Should we only get tiles that have at least one of their collision flags set? (true = yes, false = no just get them all)
  47016. if (typeof collides === 'undefined') { collides = false; }
  47017. if (typeof interestingFace === 'undefined') { interestingFace = false; }
  47018. // adjust the x,y coordinates for scrollFactor
  47019. x = this._fixX(x);
  47020. y = this._fixY(y);
  47021. if (width > this.layer.widthInPixels)
  47022. {
  47023. width = this.layer.widthInPixels;
  47024. }
  47025. if (height > this.layer.heightInPixels)
  47026. {
  47027. height = this.layer.heightInPixels;
  47028. }
  47029. // Convert the pixel values into tile coordinates
  47030. this._mc.tx = this.game.math.snapToFloor(x, this._mc.cw) / this._mc.cw;
  47031. this._mc.ty = this.game.math.snapToFloor(y, this._mc.ch) / this._mc.ch;
  47032. this._mc.tw = (this.game.math.snapToCeil(width, this._mc.cw) + this._mc.cw) / this._mc.cw;
  47033. this._mc.th = (this.game.math.snapToCeil(height, this._mc.ch) + this._mc.ch) / this._mc.ch;
  47034. // This should apply the layer x/y here
  47035. this._results.length = 0;
  47036. for (var wy = this._mc.ty; wy < this._mc.ty + this._mc.th; wy++)
  47037. {
  47038. for (var wx = this._mc.tx; wx < this._mc.tx + this._mc.tw; wx++)
  47039. {
  47040. if (this.layer.data[wy] && this.layer.data[wy][wx])
  47041. {
  47042. if ((!collides && !interestingFace) || this.layer.data[wy][wx].isInteresting(collides, interestingFace))
  47043. {
  47044. this._results.push(this.layer.data[wy][wx]);
  47045. }
  47046. }
  47047. }
  47048. }
  47049. return this._results;
  47050. };
  47051. /**
  47052. * Internal function to update maximum values.
  47053. * @method Phaser.TilemapLayer#updateMax
  47054. * @memberof Phaser.TilemapLayer
  47055. */
  47056. Phaser.TilemapLayer.prototype.updateMax = function () {
  47057. this._mc.maxX = this.game.math.ceil(this.canvas.width / this.map.tileWidth) + 1;
  47058. this._mc.maxY = this.game.math.ceil(this.canvas.height / this.map.tileHeight) + 1;
  47059. this.dirty = true;
  47060. };
  47061. /**
  47062. * Renders the tiles to the layer canvas and pushes to the display.
  47063. * @method Phaser.TilemapLayer#render
  47064. * @memberof Phaser.TilemapLayer
  47065. */
  47066. Phaser.TilemapLayer.prototype.render = function () {
  47067. if (this.layer.dirty)
  47068. {
  47069. this.dirty = true;
  47070. }
  47071. if (!this.dirty || !this.visible)
  47072. {
  47073. return;
  47074. }
  47075. this._mc.prevX = this._mc.dx;
  47076. this._mc.prevY = this._mc.dy;
  47077. this._mc.dx = -(this._mc.x - (this._mc.startX * this.map.tileWidth));
  47078. this._mc.dy = -(this._mc.y - (this._mc.startY * this.map.tileHeight));
  47079. this._mc.tx = this._mc.dx;
  47080. this._mc.ty = this._mc.dy;
  47081. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  47082. this.context.fillStyle = this.tileColor;
  47083. var tile;
  47084. var set;
  47085. if (this.debug)
  47086. {
  47087. this.context.globalAlpha = this.debugAlpha;
  47088. }
  47089. for (var y = this._mc.startY, lenY = this._mc.startY + this._mc.maxY; y < lenY; y++)
  47090. {
  47091. this._column = null;
  47092. if (y < 0 && this.wrap)
  47093. {
  47094. this._column = this.layer.data[y + this.map.height];
  47095. }
  47096. else if (y >= this.map.height && this.wrap)
  47097. {
  47098. this._column = this.layer.data[y - this.map.height];
  47099. }
  47100. else if (this.layer.data[y])
  47101. {
  47102. this._column = this.layer.data[y];
  47103. }
  47104. if (this._column)
  47105. {
  47106. for (var x = this._mc.startX, lenX = this._mc.startX + this._mc.maxX; x < lenX; x++)
  47107. {
  47108. var tile = null;
  47109. if (x < 0 && this.wrap)
  47110. {
  47111. tile = this._column[x + this.map.width];
  47112. }
  47113. else if (x >= this.map.width && this.wrap)
  47114. {
  47115. tile = this._column[x - this.map.width];
  47116. }
  47117. else if (this._column[x])
  47118. {
  47119. tile = this._column[x];
  47120. }
  47121. if (tile && tile.index > -1)
  47122. {
  47123. set = this.map.tilesets[this.map.tiles[tile.index][2]];
  47124. if (this.debug === false && tile.alpha !== this.context.globalAlpha)
  47125. {
  47126. this.context.globalAlpha = tile.alpha;
  47127. }
  47128. set.draw(this.context, Math.floor(this._mc.tx), Math.floor(this._mc.ty), tile.index);
  47129. if (tile.debug)
  47130. {
  47131. this.context.fillStyle = 'rgba(0, 255, 0, 0.4)';
  47132. this.context.fillRect(Math.floor(this._mc.tx), Math.floor(this._mc.ty), this.map.tileWidth, this.map.tileHeight);
  47133. }
  47134. }
  47135. this._mc.tx += this.map.tileWidth;
  47136. }
  47137. }
  47138. this._mc.tx = this._mc.dx;
  47139. this._mc.ty += this.map.tileHeight;
  47140. }
  47141. if (this.debug)
  47142. {
  47143. this.context.globalAlpha = 1;
  47144. this.renderDebug();
  47145. }
  47146. if (this.game.renderType === Phaser.WEBGL)
  47147. {
  47148. // PIXI.updateWebGLTexture(this.baseTexture, renderSession.gl);
  47149. PIXI.updateWebGLTexture(this.baseTexture, this.game.renderer.gl);
  47150. }
  47151. this.dirty = false;
  47152. this.layer.dirty = false;
  47153. return true;
  47154. };
  47155. /**
  47156. * Renders a collision debug overlay on-top of the canvas. Called automatically by render when debug = true.
  47157. * @method Phaser.TilemapLayer#renderDebug
  47158. * @memberof Phaser.TilemapLayer
  47159. */
  47160. Phaser.TilemapLayer.prototype.renderDebug = function () {
  47161. this._mc.tx = this._mc.dx;
  47162. this._mc.ty = this._mc.dy;
  47163. this.context.strokeStyle = this.debugColor;
  47164. this.context.fillStyle = this.debugFillColor;
  47165. for (var y = this._mc.startY, lenY = this._mc.startY + this._mc.maxY; y < lenY; y++)
  47166. {
  47167. this._column = null;
  47168. if (y < 0 && this.wrap)
  47169. {
  47170. this._column = this.layer.data[y + this.map.height];
  47171. }
  47172. else if (y >= this.map.height && this.wrap)
  47173. {
  47174. this._column = this.layer.data[y - this.map.height];
  47175. }
  47176. else if (this.layer.data[y])
  47177. {
  47178. this._column = this.layer.data[y];
  47179. }
  47180. if (this._column)
  47181. {
  47182. for (var x = this._mc.startX, lenX = this._mc.startX + this._mc.maxX; x < lenX; x++)
  47183. {
  47184. var tile = null;
  47185. if (x < 0 && this.wrap)
  47186. {
  47187. tile = this._column[x + this.map.width];
  47188. }
  47189. else if (x >= this.map.width && this.wrap)
  47190. {
  47191. tile = this._column[x - this.map.width];
  47192. }
  47193. else if (this._column[x])
  47194. {
  47195. tile = this._column[x];
  47196. }
  47197. if (tile && (tile.faceTop || tile.faceBottom || tile.faceLeft || tile.faceRight))
  47198. {
  47199. this._mc.tx = Math.floor(this._mc.tx);
  47200. if (this.debugFill)
  47201. {
  47202. this.context.fillRect(this._mc.tx, this._mc.ty, this._mc.cw, this._mc.ch);
  47203. }
  47204. this.context.beginPath();
  47205. if (tile.faceTop)
  47206. {
  47207. this.context.moveTo(this._mc.tx, this._mc.ty);
  47208. this.context.lineTo(this._mc.tx + this._mc.cw, this._mc.ty);
  47209. }
  47210. if (tile.faceBottom)
  47211. {
  47212. this.context.moveTo(this._mc.tx, this._mc.ty + this._mc.ch);
  47213. this.context.lineTo(this._mc.tx + this._mc.cw, this._mc.ty + this._mc.ch);
  47214. }
  47215. if (tile.faceLeft)
  47216. {
  47217. this.context.moveTo(this._mc.tx, this._mc.ty);
  47218. this.context.lineTo(this._mc.tx, this._mc.ty + this._mc.ch);
  47219. }
  47220. if (tile.faceRight)
  47221. {
  47222. this.context.moveTo(this._mc.tx + this._mc.cw, this._mc.ty);
  47223. this.context.lineTo(this._mc.tx + this._mc.cw, this._mc.ty + this._mc.ch);
  47224. }
  47225. this.context.stroke();
  47226. }
  47227. this._mc.tx += this.map.tileWidth;
  47228. }
  47229. }
  47230. this._mc.tx = this._mc.dx;
  47231. this._mc.ty += this.map.tileHeight;
  47232. }
  47233. };
  47234. /**
  47235. * @name Phaser.TilemapLayer#scrollX
  47236. * @property {number} scrollX - Scrolls the map horizontally or returns the current x position.
  47237. */
  47238. Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollX", {
  47239. get: function () {
  47240. return this._mc.x;
  47241. },
  47242. set: function (value) {
  47243. if (value !== this._mc.x)
  47244. {
  47245. this._mc.x = value;
  47246. this._mc.startX = this.game.math.floor(this._mc.x / this.map.tileWidth);
  47247. this.dirty = true;
  47248. }
  47249. }
  47250. });
  47251. /**
  47252. * @name Phaser.TilemapLayer#scrollY
  47253. * @property {number} scrollY - Scrolls the map vertically or returns the current y position.
  47254. */
  47255. Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollY", {
  47256. get: function () {
  47257. return this._mc.y;
  47258. },
  47259. set: function (value) {
  47260. if (value !== this._mc.y)
  47261. {
  47262. this._mc.y = value;
  47263. this._mc.startY = this.game.math.floor(this._mc.y / this.map.tileHeight);
  47264. this.dirty = true;
  47265. }
  47266. }
  47267. });
  47268. /**
  47269. * @name Phaser.TilemapLayer#collisionWidth
  47270. * @property {number} collisionWidth - The width of the collision tiles.
  47271. */
  47272. Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionWidth", {
  47273. get: function () {
  47274. return this._mc.cw;
  47275. },
  47276. set: function (value) {
  47277. this._mc.cw = value;
  47278. this.dirty = true;
  47279. }
  47280. });
  47281. /**
  47282. * @name Phaser.TilemapLayer#collisionHeight
  47283. * @property {number} collisionHeight - The height of the collision tiles.
  47284. */
  47285. Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionHeight", {
  47286. get: function () {
  47287. return this._mc.ch;
  47288. },
  47289. set: function (value) {
  47290. this._mc.ch = value;
  47291. this.dirty = true;
  47292. }
  47293. });
  47294. /**
  47295. * @author Richard Davey <rich@photonstorm.com>
  47296. * @copyright 2014 Photon Storm Ltd.
  47297. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  47298. */
  47299. /**
  47300. * Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap.
  47301. *
  47302. * @class Phaser.TilemapParser
  47303. */
  47304. Phaser.TilemapParser = {
  47305. /**
  47306. * Parse tilemap data from the cache and creates a Tilemap object.
  47307. *
  47308. * @method Phaser.TilemapParser.parse
  47309. * @param {Phaser.Game} game - Game reference to the currently running game.
  47310. * @param {string} key - The key of the tilemap in the Cache.
  47311. * @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.
  47312. * @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.
  47313. * @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.
  47314. * @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.
  47315. * @return {object} The parsed map object.
  47316. */
  47317. parse: function (game, key, tileWidth, tileHeight, width, height) {
  47318. if (typeof tileWidth === 'undefined') { tileWidth = 32; }
  47319. if (typeof tileHeight === 'undefined') { tileHeight = 32; }
  47320. if (typeof width === 'undefined') { width = 10; }
  47321. if (typeof height === 'undefined') { height = 10; }
  47322. if (typeof key === 'undefined')
  47323. {
  47324. return this.getEmptyData();
  47325. }
  47326. if (key === null)
  47327. {
  47328. return this.getEmptyData(tileWidth, tileHeight, width, height);
  47329. }
  47330. var map = game.cache.getTilemapData(key);
  47331. if (map)
  47332. {
  47333. if (map.format === Phaser.Tilemap.CSV)
  47334. {
  47335. return this.parseCSV(key, map.data, tileWidth, tileHeight);
  47336. }
  47337. else if (!map.format || map.format === Phaser.Tilemap.TILED_JSON)
  47338. {
  47339. return this.parseTiledJSON(map.data);
  47340. }
  47341. }
  47342. else
  47343. {
  47344. console.warn('Phaser.TilemapParser.parse - No map data found for key ' + key);
  47345. }
  47346. },
  47347. /**
  47348. * Parses a CSV file into valid map data.
  47349. *
  47350. * @method Phaser.TilemapParser.parseCSV
  47351. * @param {string} data - The CSV file data.
  47352. * @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.
  47353. * @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.
  47354. * @return {object} Generated map data.
  47355. */
  47356. parseCSV: function (key, data, tileWidth, tileHeight) {
  47357. var map = this.getEmptyData();
  47358. // Trim any rogue whitespace from the data
  47359. data = data.trim();
  47360. var output = [];
  47361. var rows = data.split("\n");
  47362. var height = rows.length;
  47363. var width = 0;
  47364. for (var y = 0; y < rows.length; y++)
  47365. {
  47366. output[y] = [];
  47367. var column = rows[y].split(",");
  47368. for (var x = 0; x < column.length; x++)
  47369. {
  47370. output[y][x] = new Phaser.Tile(map.layers[0], parseInt(column[x], 10), x, y, tileWidth, tileHeight);
  47371. }
  47372. if (width === 0)
  47373. {
  47374. width = column.length;
  47375. }
  47376. }
  47377. map.format = Phaser.Tilemap.CSV;
  47378. map.name = key;
  47379. map.width = width;
  47380. map.height = height;
  47381. map.tileWidth = tileWidth;
  47382. map.tileHeight = tileHeight;
  47383. map.widthInPixels = width * tileWidth;
  47384. map.heightInPixels = height * tileHeight;
  47385. map.layers[0].width = width;
  47386. map.layers[0].height = height;
  47387. map.layers[0].widthInPixels = map.widthInPixels;
  47388. map.layers[0].heightInPixels = map.heightInPixels;
  47389. map.layers[0].data = output;
  47390. return map;
  47391. },
  47392. /**
  47393. * Returns an empty map data object.
  47394. *
  47395. * @method Phaser.TilemapParser.getEmptyData
  47396. * @return {object} Generated map data.
  47397. */
  47398. getEmptyData: function (tileWidth, tileHeight, width, height) {
  47399. var map = {};
  47400. map.width = 0;
  47401. map.height = 0;
  47402. map.tileWidth = 0;
  47403. map.tileHeight = 0;
  47404. if (typeof tileWidth !== 'undefined' && tileWidth !== null) { map.tileWidth = tileWidth; }
  47405. if (typeof tileHeight !== 'undefined' && tileHeight !== null) { map.tileHeight = tileHeight; }
  47406. if (typeof width !== 'undefined' && width !== null) { map.width = width; }
  47407. if (typeof height !== 'undefined' && height !== null) { map.height = height; }
  47408. map.orientation = 'orthogonal';
  47409. map.version = '1';
  47410. map.properties = {};
  47411. map.widthInPixels = 0;
  47412. map.heightInPixels = 0;
  47413. var layers = [];
  47414. var layer = {
  47415. name: 'layer',
  47416. x: 0,
  47417. y: 0,
  47418. width: 0,
  47419. height: 0,
  47420. widthInPixels: 0,
  47421. heightInPixels: 0,
  47422. alpha: 1,
  47423. visible: true,
  47424. properties: {},
  47425. indexes: [],
  47426. callbacks: [],
  47427. data: []
  47428. };
  47429. // fill with nulls?
  47430. layers.push(layer);
  47431. map.layers = layers;
  47432. map.images = [];
  47433. map.objects = {};
  47434. map.collision = {};
  47435. map.tilesets = [];
  47436. map.tiles = [];
  47437. return map;
  47438. },
  47439. /**
  47440. * Parses a Tiled JSON file into valid map data.
  47441. * @method Phaser.TilemapParser.parseJSON
  47442. * @param {object} json - The JSON map data.
  47443. * @return {object} Generated and parsed map data.
  47444. */
  47445. parseTiledJSON: function (json) {
  47446. if (json.orientation !== 'orthogonal')
  47447. {
  47448. console.warn('TilemapParser.parseTiledJSON: Only orthogonal map types are supported in this version of Phaser');
  47449. return null;
  47450. }
  47451. // Map data will consist of: layers, objects, images, tilesets, sizes
  47452. var map = {};
  47453. map.width = json.width;
  47454. map.height = json.height;
  47455. map.tileWidth = json.tilewidth;
  47456. map.tileHeight = json.tileheight;
  47457. map.orientation = json.orientation;
  47458. map.format = Phaser.Tilemap.TILED_JSON;
  47459. map.version = json.version;
  47460. map.properties = json.properties;
  47461. map.widthInPixels = map.width * map.tileWidth;
  47462. map.heightInPixels = map.height * map.tileHeight;
  47463. // Tile Layers
  47464. var layers = [];
  47465. for (var i = 0; i < json.layers.length; i++)
  47466. {
  47467. if (json.layers[i].type !== 'tilelayer')
  47468. {
  47469. continue;
  47470. }
  47471. var layer = {
  47472. name: json.layers[i].name,
  47473. x: json.layers[i].x,
  47474. y: json.layers[i].y,
  47475. width: json.layers[i].width,
  47476. height: json.layers[i].height,
  47477. widthInPixels: json.layers[i].width * json.tilewidth,
  47478. heightInPixels: json.layers[i].height * json.tileheight,
  47479. alpha: json.layers[i].opacity,
  47480. visible: json.layers[i].visible,
  47481. properties: {},
  47482. indexes: [],
  47483. callbacks: [],
  47484. bodies: []
  47485. };
  47486. if (json.layers[i].properties)
  47487. {
  47488. layer.properties = json.layers[i].properties;
  47489. }
  47490. var x = 0;
  47491. var row = [];
  47492. var output = [];
  47493. // Loop through the data field in the JSON.
  47494. // 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)
  47495. // If the map contains multiple tilesets then the indexes are relative to that which the set starts from.
  47496. // 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.
  47497. for (var t = 0, len = json.layers[i].data.length; t < len; t++)
  47498. {
  47499. // index, x, y, width, height
  47500. if (json.layers[i].data[t] > 0)
  47501. {
  47502. row.push(new Phaser.Tile(layer, json.layers[i].data[t], x, output.length, json.tilewidth, json.tileheight));
  47503. }
  47504. else
  47505. {
  47506. row.push(new Phaser.Tile(layer, -1, x, output.length, json.tilewidth, json.tileheight));
  47507. }
  47508. x++;
  47509. if (x === json.layers[i].width)
  47510. {
  47511. output.push(row);
  47512. x = 0;
  47513. row = [];
  47514. }
  47515. }
  47516. layer.data = output;
  47517. layers.push(layer);
  47518. }
  47519. map.layers = layers;
  47520. // Images
  47521. var images = [];
  47522. for (var i = 0; i < json.layers.length; i++)
  47523. {
  47524. if (json.layers[i].type !== 'imagelayer')
  47525. {
  47526. continue;
  47527. }
  47528. var image = {
  47529. name: json.layers[i].name,
  47530. image: json.layers[i].image,
  47531. x: json.layers[i].x,
  47532. y: json.layers[i].y,
  47533. alpha: json.layers[i].opacity,
  47534. visible: json.layers[i].visible,
  47535. properties: {}
  47536. };
  47537. if (json.layers[i].properties)
  47538. {
  47539. image.properties = json.layers[i].properties;
  47540. }
  47541. images.push(image);
  47542. }
  47543. map.images = images;
  47544. // Tilesets
  47545. var tilesets = [];
  47546. for (var i = 0; i < json.tilesets.length; i++)
  47547. {
  47548. // name, firstgid, width, height, margin, spacing, properties
  47549. var set = json.tilesets[i];
  47550. var newSet = new Phaser.Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties);
  47551. if (set.tileproperties)
  47552. {
  47553. newSet.tileProperties = set.tileproperties;
  47554. }
  47555. newSet.rows = Math.round((set.imageheight - set.margin) / (set.tileheight + set.spacing));
  47556. newSet.columns = Math.round((set.imagewidth - set.margin) / (set.tilewidth + set.spacing));
  47557. newSet.total = newSet.rows * newSet.columns;
  47558. if (newSet.rows % 1 !== 0 || newSet.columns % 1 !== 0)
  47559. {
  47560. console.warn('TileSet image dimensions do not match expected dimensions. Tileset width/height must be evenly divisible by Tilemap tile width/height.');
  47561. }
  47562. else
  47563. {
  47564. tilesets.push(newSet);
  47565. }
  47566. }
  47567. map.tilesets = tilesets;
  47568. // Objects & Collision Data (polylines, etc)
  47569. var objects = {};
  47570. var collision = {};
  47571. function slice (obj, fields) {
  47572. var sliced = {};
  47573. for (var k in fields) {
  47574. var key = fields[k];
  47575. sliced[key] = obj[key];
  47576. }
  47577. return sliced;
  47578. }
  47579. for (var i = 0; i < json.layers.length; i++)
  47580. {
  47581. if (json.layers[i].type !== 'objectgroup')
  47582. {
  47583. continue;
  47584. }
  47585. objects[json.layers[i].name] = [];
  47586. collision[json.layers[i].name] = [];
  47587. for (var v = 0, len = json.layers[i].objects.length; v < len; v++)
  47588. {
  47589. // Object Tiles
  47590. if (json.layers[i].objects[v].gid)
  47591. {
  47592. var object = {
  47593. gid: json.layers[i].objects[v].gid,
  47594. name: json.layers[i].objects[v].name,
  47595. x: json.layers[i].objects[v].x,
  47596. y: json.layers[i].objects[v].y,
  47597. visible: json.layers[i].objects[v].visible,
  47598. properties: json.layers[i].objects[v].properties
  47599. };
  47600. objects[json.layers[i].name].push(object);
  47601. }
  47602. else if (json.layers[i].objects[v].polyline)
  47603. {
  47604. var object = {
  47605. name: json.layers[i].objects[v].name,
  47606. x: json.layers[i].objects[v].x,
  47607. y: json.layers[i].objects[v].y,
  47608. width: json.layers[i].objects[v].width,
  47609. height: json.layers[i].objects[v].height,
  47610. visible: json.layers[i].objects[v].visible,
  47611. properties: json.layers[i].objects[v].properties
  47612. };
  47613. object.polyline = [];
  47614. // Parse the polyline into an array
  47615. for (var p = 0; p < json.layers[i].objects[v].polyline.length; p++)
  47616. {
  47617. object.polyline.push([ json.layers[i].objects[v].polyline[p].x, json.layers[i].objects[v].polyline[p].y ]);
  47618. }
  47619. collision[json.layers[i].name].push(object);
  47620. }
  47621. // polygon
  47622. else if (json.layers[i].objects[v].polygon)
  47623. {
  47624. var object = slice(json.layers[i].objects[v],
  47625. ["name", "x", "y", "visible", "properties" ]);
  47626. // Parse the polygon into an array
  47627. object.polygon = [];
  47628. for (var p = 0; p < json.layers[i].objects[v].polygon.length; p++)
  47629. {
  47630. object.polygon.push([ json.layers[i].objects[v].polygon[p].x, json.layers[i].objects[v].polygon[p].y ]);
  47631. }
  47632. objects[json.layers[i].name].push(object);
  47633. }
  47634. // ellipse
  47635. else if (json.layers[i].objects[v].ellipse)
  47636. {
  47637. var object = slice(json.layers[i].objects[v],
  47638. ["name", "ellipse", "x", "y", "width", "height", "visible", "properties" ]);
  47639. objects[json.layers[i].name].push(object);
  47640. }
  47641. // otherwise it's a rectangle
  47642. else
  47643. {
  47644. var object = slice(json.layers[i].objects[v],
  47645. ["name", "x", "y", "width", "height", "visible", "properties" ]);
  47646. object.rectangle = true;
  47647. objects[json.layers[i].name].push(object);
  47648. }
  47649. }
  47650. }
  47651. map.objects = objects;
  47652. map.collision = collision;
  47653. map.tiles = [];
  47654. // Finally lets build our super tileset index
  47655. for (var i = 0; i < map.tilesets.length; i++)
  47656. {
  47657. var set = map.tilesets[i];
  47658. var x = set.tileMargin;
  47659. var y = set.tileMargin;
  47660. var count = 0;
  47661. var countX = 0;
  47662. var countY = 0;
  47663. for (var t = set.firstgid; t < set.firstgid + set.total; t++)
  47664. {
  47665. // Can add extra properties here as needed
  47666. map.tiles[t] = [x, y, i];
  47667. x += set.tileWidth + set.tileSpacing;
  47668. count++;
  47669. if (count === set.total)
  47670. {
  47671. break;
  47672. }
  47673. countX++;
  47674. if (countX === set.columns)
  47675. {
  47676. x = set.tileMargin;
  47677. y += set.tileHeight + set.tileSpacing;
  47678. countX = 0;
  47679. countY++;
  47680. if (countY === set.rows)
  47681. {
  47682. break;
  47683. }
  47684. }
  47685. }
  47686. }
  47687. return map;
  47688. }
  47689. };
  47690. /**
  47691. * @author Richard Davey <rich@photonstorm.com>
  47692. * @copyright 2014 Photon Storm Ltd.
  47693. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  47694. */
  47695. /**
  47696. * A Tile set is a combination of an image containing the tiles and collision data per tile.
  47697. * You should not normally instantiate this class directly.
  47698. *
  47699. * @class Phaser.Tileset
  47700. * @constructor
  47701. * @param {string} name - The name of the tileset in the map data.
  47702. * @param {number} firstgid - The Tiled firstgid value. In non-Tiled data this should be considered the starting index value of the first tile in this set.
  47703. * @param {number} [width=32] - Width of each tile in pixels.
  47704. * @param {number} [height=32] - Height of each tile in pixels.
  47705. * @param {number} [margin=0] - The amount of margin around the tilesheet.
  47706. * @param {number} [spacing=0] - The amount of spacing between each tile in the sheet.
  47707. * @param {object} [properties] - Tileset properties.
  47708. */
  47709. Phaser.Tileset = function (name, firstgid, width, height, margin, spacing, properties) {
  47710. if (typeof width === 'undefined' || width <= 0) { width = 32; }
  47711. if (typeof height === 'undefined' || height <= 0) { height = 32; }
  47712. if (typeof margin === 'undefined') { margin = 0; }
  47713. if (typeof spacing === 'undefined') { spacing = 0; }
  47714. /**
  47715. * @property {string} name - The name of the Tileset.
  47716. */
  47717. this.name = name;
  47718. /**
  47719. * @property {number} firstgid - The Tiled firstgid value. In non-Tiled data this should be considered the starting index value of the first tile in this set.
  47720. */
  47721. this.firstgid = firstgid;
  47722. /**
  47723. * @property {number} tileWidth - The width of a tile in pixels.
  47724. */
  47725. this.tileWidth = width;
  47726. /**
  47727. * @property {number} tileHeight - The height of a tile in pixels.
  47728. */
  47729. this.tileHeight = height;
  47730. /**
  47731. * @property {number} tileMargin - The margin around the tiles in the tileset.
  47732. */
  47733. this.tileMargin = margin;
  47734. /**
  47735. * @property {number} tileSpacing - The spacing in pixels between each tile in the tileset.
  47736. */
  47737. this.tileSpacing = spacing;
  47738. /**
  47739. * @property {object} properties - Tileset specific properties (typically defined in the Tiled editor).
  47740. */
  47741. this.properties = properties;
  47742. /**
  47743. * @property {object} image - The image used for rendering. This is a reference to the image stored in Phaser.Cache.
  47744. */
  47745. this.image = null;
  47746. /**
  47747. * @property {number} rows - The number of rows in the tile sheet.
  47748. */
  47749. this.rows = 0;
  47750. /**
  47751. * @property {number} columns - The number of columns in the tile sheet.
  47752. */
  47753. this.columns = 0;
  47754. /**
  47755. * @property {number} total - The total number of tiles in the tilesheet.
  47756. */
  47757. this.total = 0;
  47758. /**
  47759. * @property {array} draw - The tile drawImage look-up table
  47760. * @private
  47761. */
  47762. this.drawCoords = [];
  47763. };
  47764. Phaser.Tileset.prototype = {
  47765. /**
  47766. * Draws a tile from this Tileset at the given coordinates on the context.
  47767. *
  47768. * @method Phaser.Tileset#draw
  47769. * @param {HTMLCanvasContext} context - The context to draw the tile onto.
  47770. * @param {number} x - The x coordinate to draw to.
  47771. * @param {number} y - The y coordinate to draw to.
  47772. * @param {number} index - The index of the tile within the set to draw.
  47773. */
  47774. draw: function (context, x, y, index) {
  47775. if (!this.image || !this.drawCoords[index])
  47776. {
  47777. return;
  47778. }
  47779. context.drawImage(
  47780. this.image,
  47781. this.drawCoords[index][0],
  47782. this.drawCoords[index][1],
  47783. this.tileWidth,
  47784. this.tileHeight,
  47785. x,
  47786. y,
  47787. this.tileWidth,
  47788. this.tileHeight
  47789. );
  47790. },
  47791. /**
  47792. * Adds a reference from this Tileset to an Image stored in the Phaser.Cache.
  47793. *
  47794. * @method Phaser.Tileset#setImage
  47795. * @param {Image} image - The image this tileset will use to draw with.
  47796. */
  47797. setImage: function (image) {
  47798. this.image = image;
  47799. this.rows = Math.round((image.height - this.tileMargin) / (this.tileHeight + this.tileSpacing));
  47800. this.columns = Math.round((image.width - this.tileMargin) / (this.tileWidth + this.tileSpacing));
  47801. this.total = this.rows * this.columns;
  47802. // Create the index look-up
  47803. this.drawCoords.length = 0;
  47804. var tx = this.tileMargin;
  47805. var ty = this.tileMargin;
  47806. var i = this.firstgid;
  47807. for (var y = 0; y < this.rows; y++)
  47808. {
  47809. for (var x = 0; x < this.columns; x++)
  47810. {
  47811. this.drawCoords[i] = [ tx, ty ];
  47812. tx += this.tileWidth + this.tileSpacing;
  47813. i++;
  47814. }
  47815. tx = this.tileMargin;
  47816. ty += this.tileHeight + this.tileSpacing;
  47817. }
  47818. },
  47819. /**
  47820. * Sets tile spacing and margins.
  47821. *
  47822. * @method Phaser.Tileset#setSpacing
  47823. * @param {number} [tileMargin] - The margin around the tiles in the sheet.
  47824. * @param {number} [tileSpacing] - The spacing between the tiles in the sheet.
  47825. */
  47826. setSpacing: function (margin, spacing) {
  47827. this.tileMargin = margin;
  47828. this.tileSpacing = spacing;
  47829. this.setImage(this.image);
  47830. }
  47831. };
  47832. Phaser.Tileset.prototype.constructor = Phaser.Tileset;
  47833. /**
  47834. * @author Richard Davey <rich@photonstorm.com>
  47835. * @copyright 2014 Photon Storm Ltd.
  47836. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  47837. */
  47838. if (typeof exports !== 'undefined') {
  47839. if (typeof module !== 'undefined' && module.exports) {
  47840. exports = module.exports = Phaser;
  47841. }
  47842. exports.Phaser = Phaser;
  47843. } else if (typeof define !== 'undefined' && define.amd) {
  47844. define('Phaser', (function() { return root.Phaser = Phaser; }) ());
  47845. } else {
  47846. root.Phaser = Phaser;
  47847. }
  47848. }).call(this);
  47849. /*
  47850. * "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
  47851. */
  47852. if (/iPhone/i.test(navigator.userAgent)) {
  47853. DPI = 2
  47854. } else {
  47855. DPI = 1
  47856. }
  47857. // 游戏参数
  47858. var DEBUG = false;
  47859. // 前进速度
  47860. var SPEED = 200 * DPI;
  47861. // 重力
  47862. var GRAVITY = 900*DPI;
  47863. // 飞行高度
  47864. var FLAP = 250*DPI;
  47865. // 水管频率
  47866. var SPAWN_RATE = 1 / 1.2;
  47867. // 洞口大小
  47868. var OPENING = 150*DPI;
  47869. // 获取游戏区域高宽
  47870. var parent = document.querySelector('#screen');
  47871. // 设置高宽,以浏览器窗口内高/宽度优先
  47872. var w = parent.clientWidth > window.innerWidth ? window.innerWidth : parent.clientWidth;
  47873. var h = parent.clientHeight > window.innerHeight || parent.clientHeight == 0 ? window.innerHeight : parent.clientHeight;
  47874. w *= DPI
  47875. h *= DPI
  47876. var gameStarted,
  47877. gameOver,
  47878. score,
  47879. bg,
  47880. background,
  47881. credits,
  47882. fingers,
  47883. invs,
  47884. birdie,
  47885. fence,
  47886. scoreText,
  47887. instText,
  47888. gameOverText,
  47889. fingersTimer,
  47890. _stpipenumber;
  47891. score = 0;
  47892. _stpipenumber = 10;
  47893. // 游戏容器
  47894. Game = {};
  47895. // 游戏启动加载器
  47896. Game.Boot = function (game) { };
  47897. Game.Boot.prototype = {
  47898. // 加载 loading 图片
  47899. preload: function () {
  47900. //game.stage.disableVisibilityChange = true;
  47901. this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
  47902. this.scale.setScreenSize(true);
  47903. //document.getElementById('screen').style.width = w/2 + 'px'
  47904. //document.getElementById('screen').style.height = h/2 + 'px'
  47905. // 背景颜色
  47906. game.stage.backgroundColor = '#ffffff';
  47907. // 生成背景
  47908. var bg = game.add.graphics(0, 0);
  47909. // 0x+颜色、透明度
  47910. bg.beginFill(0xffffff, 1);
  47911. // 坐标位置,宽高
  47912. bg.drawRect(0, 0, w, h);
  47913. // 结束
  47914. bg.endFill();
  47915. // 加载图片
  47916. //
  47917. if (DPI == 2) {
  47918. game.load.image('loading_2x', './resource/image/game/flappyfish/loading_2x.png');
  47919. } else {
  47920. game.load.image('loading', './resource/image/game/flappyfish/loading.png');
  47921. };
  47922. game.load.image('loading', './resource/image/game/flappyfish/loading.png');
  47923. game.load.image('loading2', './resource/image/game/flappyfish/loading2.png');
  47924. game.load.image('logo', './resource/image/game/flappyfish/logo-h.png');
  47925. },
  47926. // 完成后启动资源预加载器
  47927. create: function() {
  47928. this.game.state.start('Load');
  47929. }
  47930. };
  47931. // 资源预加载器
  47932. Game.Load = function (game) { };
  47933. Game.Load.prototype = {
  47934. preload: function () {
  47935. // 设置触控数量
  47936. this.input.maxPointers = 1;
  47937. // 设置 loading 文案
  47938. // todo 切换字体
  47939. if (DPI == 2) {
  47940. var font = '40px "Microsoft YaHei"'
  47941. var label2_y = 90
  47942. } else {
  47943. var font = '20px "Microsoft YaHei"'
  47944. var label2_y = 70
  47945. }
  47946. label2 = game.add.text((w/2), (h/2)-label2_y, '游戏加载中', {font: font});
  47947. // 文案居中
  47948. label2.x -= label2.width/2;
  47949. // 每日Q logo
  47950. logo = game.add.sprite(w/2, h-70, 'logo');
  47951. // logo 缩小
  47952. if (DPI === 1) {logo.scale.setTo(0.7, 0.7);};
  47953. // logo 居中
  47954. logo.x -= logo.width/2;
  47955. // loading 底图
  47956. preloading2 = game.add.sprite(w/2, h/2+15-50, 'loading2');
  47957. preloading2.scale.setTo(DPI,DPI);
  47958. // X轴起始位置减去自身一半,居中
  47959. preloading2.x -= preloading2.width/2;
  47960. // loading 前置图
  47961. if (DPI == 2) {
  47962. preloading = game.add.sprite(w/2, h/2+15-50, 'loading_2x');
  47963. } else {
  47964. preloading = game.add.sprite(w/2, h/2+15-50, 'loading');
  47965. };
  47966. // X轴起始位置减去自身一半,居中
  47967. preloading.x -= preloading.width/2;
  47968. // 设置加载进度条
  47969. game.load.setPreloadSprite(preloading);
  47970. // 加载静态资源
  47971. game.load.spritesheet('medals', './resource/image/game/flappyfish/medals.png', 110, 110, 3);
  47972. game.load.spritesheet('button', './resource/image/game/flappyfish/button.png', 261.5, 145, 2);
  47973. //game.load.image('birdie', '/application/views/games/games/feiyu/resource/image/game/flappyfish/birdie.png');
  47974. if (Math.random() > 0.5) {
  47975. game.load.spritesheet('birdie', './resource/image/game/flappyfish/birdie.png', 88, 72);
  47976. game.load.image('instructions', './resource/image/game/flappyfish/instructions.png');
  47977. } else {
  47978. game.load.spritesheet('birdie', './resource/image/game/flappyfish/pig.png', 88, 72);
  47979. game.load.image('instructions', './resource/image/game/flappyfish/instructions_pig.png');
  47980. }
  47981. game.load.image('background', './resource/image/game/flappyfish/BG_day.png');
  47982. game.load.image('finger', './resource/image/game/flappyfish/finger.png');
  47983. game.load.image('fence', './resource/image/game/flappyfish/fence.png');
  47984. game.load.image('gameover', './resource/image/game/flappyfish/gameover.png');
  47985. game.load.image('scoreboard', './resource/image/game/flappyfish/scoreboard.png');
  47986. game.load.bitmapFont('flappyfont', './resource/image/game/flappyfish/flappyfont.png', './resource/font/game/flappyfish/flappyfont.txt');
  47987. },
  47988. create: function () {
  47989. // 加载完成后,进入游戏
  47990. // 测试注释
  47991. endLoading();
  47992. finishLoadLog();
  47993. initScore();
  47994. // 部署取消注释
  47995. game.state.start('Play');
  47996. }
  47997. };
  47998. Game.Play = function (game) { };
  47999. Game.Play.prototype = {
  48000. // 创造一个世界
  48001. create: function () {
  48002. // 开启物理系统
  48003. game.physics.startSystem(Phaser.Physics.ARCADE);
  48004. // 设置宽高
  48005. game.world.width = w;
  48006. game.world.height = h;
  48007. // 增加背景图
  48008. this.background = game.add.sprite(0, 0, 'background');
  48009. // 设置背景图适应屏幕
  48010. this.background.width = game.world.width;
  48011. this.background.height = game.world.height;
  48012. // 积分显示
  48013. this.credits = game.add.text(
  48014. game.world.width / 2,
  48015. 10,
  48016. '',
  48017. {
  48018. align: 'center'
  48019. }
  48020. );
  48021. this.credits.anchor.x = 0.5;
  48022. // 指示文字
  48023. this.instructions = game.add.sprite(game.world.width/2, game.world.width/2,'instructions');
  48024. this.instructions.scale.setTo(0.5*DPI, 0.5*DPI);
  48025. this.instructions.x -= this.instructions.width/2;
  48026. // 水管
  48027. this.fingers = game.add.group();
  48028. // 洞口
  48029. this.invs = game.add.group();
  48030. // 小鸟
  48031. this.birdie = game.add.sprite(0, 0, 'birdie');
  48032. this.birdie.animations.add('fly', [0, 1], 10, true);
  48033. // 开启物理系统
  48034. game.physics.arcade.enable(this.birdie);
  48035. // 设置中心偏移
  48036. this.birdie.anchor.setTo(0.5, 0.5);
  48037. // TODO
  48038. this.birdie.inputEnabled = true;
  48039. // 碰撞检测
  48040. //birdie.body.collideWorldBounds = true;
  48041. // 重力系数
  48042. this.birdie.body.gravity.y = GRAVITY;
  48043. // 地板
  48044. this.fence = game.add.tileSprite(0, game.world.height - 62, game.world.width, 62, 'fence');
  48045. game.physics.arcade.enable(this.fence);
  48046. this.fence.body.immovable = true;
  48047. // 地板放大
  48048. //this.fence.tileScale.setTo(1, 1);
  48049. // 游戏结束
  48050. this.gameover = game.add.sprite(game.world.width/2, h, 'gameover');
  48051. this.gameover.scale.setTo(DPI,DPI);
  48052. this.gameover.anchor.setTo(0.5, 0.5);
  48053. this.gameover.exists = false;
  48054. this.scoreboard = game.add.sprite(game.world.width / 2, h, 'scoreboard');
  48055. this.scoreboard.anchor.setTo(0.5, 0.5);
  48056. this.scoreboard.scale.setTo(DPI, DPI);
  48057. this.scoreboard.exists = false;
  48058. this.scoreBoardText = game.add.bitmapText(w-(w-this.scoreboard.width)/2-50*DPI, h, 'flappyfont', '', 22*DPI);
  48059. this.bestText = game.add.bitmapText(w-(w-this.scoreboard.width)/2-50*DPI, h, 'flappyfont', '', 22*DPI);
  48060. // 分数显示
  48061. this.scoreText = game.add.bitmapText(game.world.width/2, 70, 'flappyfont',score.toString(), 24*DPI);
  48062. this.scoreText.scale.setTo(2,2);
  48063. this.scoreText.x -= this.scoreText.fontSize/2;
  48064. // 控制器,点击跳跃飞行
  48065. game.input.onDown.add(this.flap, this);
  48066. // 重置
  48067. this.reset();
  48068. },
  48069. // 重置游戏
  48070. reset: function () {
  48071. // 删除按钮
  48072. initScore();
  48073. if (this.share_button) {
  48074. this.share_button.exists = false;
  48075. this.start_button.exists = false;
  48076. // 重置滑出初始y值
  48077. this.scoreboard.y = h;
  48078. this.gameover.y = h;
  48079. this.start_button.y = h;
  48080. this.share_button.y = h;
  48081. this.scoreBoardText.y = h;
  48082. this.bestText.y = h;
  48083. }
  48084. // 删除勋章
  48085. if (this.medals) {this.medals.exists = false;}
  48086. this.bestText.setText('');
  48087. this.scoreBoardText.setText('');
  48088. this.gameover.exists = false;
  48089. this.scoreboard.exists = false;
  48090. this.instructions.exists = true;
  48091. // 游戏开始为否
  48092. this.gameStarted = false;
  48093. // 游戏结束为否
  48094. gameOver = false;
  48095. // 零分
  48096. score = 0;
  48097. this.scoreText.setText(score.toString());
  48098. // 渲染积分
  48099. this.credits.renderable = true;
  48100. // 小鸟不产生重力
  48101. this.birdie.body.allowGravity = false;
  48102. // 小鸟的旋转角度
  48103. this.birdie.angle = 0;
  48104. // 重置开始位置
  48105. this.birdie.reset(game.world.width / 4, game.world.height / 2);
  48106. // 小鸟放大
  48107. this.birdie.scale.setTo(0.5*DPI, 0.5*DPI);
  48108. // 飞行动画
  48109. this.birdie.animations.play('fly');
  48110. // 移除水管
  48111. this.fingers.removeAll();
  48112. // 移除隐藏的东西
  48113. this.invs.removeAll();
  48114. },
  48115. // 开始游戏
  48116. start: function () {
  48117. // 测试注释 部署运行
  48118. this.instructions.exists = false;
  48119. // 积分显示
  48120. this.credits.renderable = false;
  48121. // 小鸟开启重力
  48122. this.birdie.body.allowGravity = true;
  48123. // 水管循环
  48124. this.fingersTimer = game.time.create(false);
  48125. this.fingersTimer.loop(2000,this.spawnFingers,this);
  48126. this.fingersTimer.start();
  48127. // 显示分数
  48128. this.scoreText.setText(score.toString());
  48129. // 开始游戏
  48130. this.gameStarted = true;
  48131. },
  48132. // 跳动
  48133. flap: function () {
  48134. // 若游戏未开始,则开始
  48135. if (!this.gameStarted) {
  48136. this.start();
  48137. }
  48138. // 若游戏未结束,小鸟高度变化,播放音效
  48139. if (!gameOver) {
  48140. if (this.birdie.y > 10){
  48141. this.birdie.body.velocity.y = -FLAP;
  48142. }
  48143. }
  48144. },
  48145. // 洞口
  48146. o: function () {
  48147. if (score > _stpipenumber-2) {
  48148. return OPENING * .9// * DPI;
  48149. } else {
  48150. return OPENING * 1.2 //0.6 * DPI;
  48151. }
  48152. },
  48153. // 进击的水管 单个
  48154. spawnFinger: function (fingerY, flipped) {
  48155. // 新建水管
  48156. var finger = this.fingers.create(
  48157. game.world.width,
  48158. fingerY + (flipped ? -this.o() : this.o()) / 2,
  48159. 'finger'
  48160. );
  48161. // 开启物理系统
  48162. game.physics.arcade.enable(finger);
  48163. // 关闭重力
  48164. finger.body.allowGravity = false;
  48165. // 放大水管
  48166. finger.scale.setTo(0.5*DPI, flipped ? -0.5*DPI : 0.5*DPI);
  48167. // 水管水平高度,与放大倍数相关联
  48168. finger.body.offset.y = flipped? -finger.body.height*0.5*DPI : 0;
  48169. // 向左偏移
  48170. finger.body.velocity.x = -165*DPI
  48171. return finger;
  48172. },
  48173. // 进击的一组水管
  48174. spawnFingers: function () {
  48175. this.fingersTimer.stop();
  48176. var fingerY = ((game.world.height - 16 - this.o() / 2) / 2) + (Math.random() > 0.5 ? -1 : 1) * Math.random() * game.world.height / 6;
  48177. // 底部水管
  48178. var botFinger = this.spawnFinger(fingerY);
  48179. // 顶部水管
  48180. var topFinger = this.spawnFinger(fingerY, true);
  48181. // 隐藏部分
  48182. var inv = this.invs.create(topFinger.x + topFinger.width, 0);
  48183. inv.width = 2;
  48184. inv.height = game.world.height;
  48185. game.physics.arcade.enable(inv);
  48186. inv.body.allowGravity = false;
  48187. inv.body.velocity.x = -165 * DPI;
  48188. // 循环水管
  48189. this.fingersTimer.start();
  48190. this.fingersTimer.add(1 / SPAWN_RATE*1000, this.spawnFingers, this);
  48191. },
  48192. // 分数
  48193. addScore: function (_, inv) {
  48194. this.invs.remove(inv);
  48195. // 加一分
  48196. score += 1;
  48197. this.scoreText.setText(score);
  48198. },
  48199. // 分享
  48200. share: function() {
  48201. this.share_button.y -= 10;
  48202. //执行分享操作,弹出分享层
  48203. weixinShareWS();
  48204. //开启微信分享引导
  48205. // window.location.href = "meiriq://share"
  48206. },
  48207. // 游戏结束
  48208. setGameOver: function () {
  48209. // 分数面板
  48210. this.scoreboard.exists = true;
  48211. this.gameover.exists = true;
  48212. this.scoreText.setText('');
  48213. if (this.birdie.body.bottom >= game.world.bounds.bottom - 45){
  48214. this.birdie.body.allowGravity = false;
  48215. //birdie.body.immovable = true;
  48216. }
  48217. // 标记结束
  48218. gameOver = true;
  48219. // 历史分数
  48220. var hiscore = 0;
  48221. hiscore = hiscore ? hiscore : score;
  48222. // 更新最高分
  48223. hiscore = score > parseInt(hiscore, 10) ? score : hiscore;
  48224. setScore(score);
  48225. // 得分面板
  48226. this.bestText.setText(hiscore.toString());
  48227. this.scoreBoardText.setText(score.toString());
  48228. // 勋章 todo 修改区间
  48229. if (DPI === 1) {
  48230. var medals_y = 20
  48231. } else {
  48232. var medals_y = 220
  48233. }
  48234. if (score >= 0 && score < 50) {
  48235. this.medals = game.add.sprite(w-this.scoreboard.width-(w-this.scoreboard.width)/2+this.scoreboard.width*0.075, h/2-this.scoreboard.width*0.09, 'medals', 0);
  48236. } else if (score >= 50 && score < 100) {
  48237. this.medals = game.add.sprite(w-this.scoreboard.width-(w-this.scoreboard.width)/2+this.scoreboard.width*0.075, h/2-this.scoreboard.width*0.09, 'medals', 1);
  48238. } else if (score >= 100){
  48239. this.medals = game.add.sprite(w-this.scoreboard.width-(w-this.scoreboard.width)/2+this.scoreboard.width*0.075, h/2-this.scoreboard.width*0.09, 'medals', 2);
  48240. }
  48241. if (score >= 0) {
  48242. this.medals.scale.setTo(0.5*DPI, 0.5*DPI);
  48243. };
  48244. // 按钮
  48245. // 根据dpi的不一样调整按钮位置
  48246. if(DPI===1){
  48247. var button_x = 0;
  48248. var button_y = 15
  48249. }else{
  48250. var button_x = 60;
  48251. var button_y = 0
  48252. }
  48253. this.start_button = game.add.sprite(w/2-button_x, h, 'button', 0);
  48254. this.start_button.scale.setTo(0.4*DPI, 0.4*DPI);
  48255. this.start_button.x -= this.start_button.width/2+61;
  48256. //this.start_button.x -= this.start_button.width/2 - 61;
  48257. this.share_button = game.add.sprite(w/2+button_x, h, 'button', 1);
  48258. this.share_button.scale.setTo(0.4*DPI, 0.4*DPI);
  48259. this.share_button.x -= this.share_button.width/2-61;
  48260. this.start_button.inputEnabled = true;
  48261. this.share_button.inputEnabled = true;
  48262. // 停止水管
  48263. this.fingers.forEachAlive(function(finger) {
  48264. finger.body.velocity.x = 0;
  48265. });
  48266. this.invs.forEach(function(inv) {
  48267. inv.body.velocity.x = 0;
  48268. });
  48269. // 停止计时器
  48270. this.fingersTimer.stop();
  48271. // 此处应该用组TODO
  48272. game.add.tween(this.gameover).to({y: h/2-100*DPI}, 1000, Phaser.Easing.Bounce.Out, true);
  48273. game.add.tween(this.scoreboard).to({y: h/2}, 1000, Phaser.Easing.Bounce.Out, true);
  48274. game.add.tween(this.scoreBoardText).to({y: h/2-20*DPI}, 1000, Phaser.Easing.Bounce.Out, true);
  48275. game.add.tween(this.bestText).to({y: h/2+25*DPI}, 1000, Phaser.Easing.Bounce.Out, true);
  48276. game.add.tween(this.start_button).to({y: h/1.5-button_y}, 1000, Phaser.Easing.Bounce.Out, true);
  48277. game.add.tween(this.share_button).to({y: h/1.5-button_y}, 1000, Phaser.Easing.Bounce.Out, true);
  48278. if (this.medals) {
  48279. var medals_y = this.medals.y
  48280. this.medals.y = h
  48281. game.add.tween(this.medals).to({y: medals_y}, 1000, Phaser.Easing.Bounce.Out, true);
  48282. };
  48283. this.start_button.events.onInputDown.add(this.down, this);
  48284. this.share_button.events.onInputDown.add(this.down2, this);
  48285. },
  48286. down: function () {
  48287. this.start_button.y += 10;
  48288. game.time.events.add(Phaser.Timer.SECOND*0.2, this.reset, this);
  48289. },
  48290. down2: function() {
  48291. this.share_button.y += 10;
  48292. game.time.events.add(Phaser.Timer.SECOND*0.2, this.share, this);
  48293. },
  48294. update: function () {
  48295. game.physics.arcade.collide(this.birdie, this.fence);
  48296. if (this.gameStarted) {
  48297. // 小鸟下沉
  48298. var dvy = FLAP + this.birdie.body.velocity.y;
  48299. this.birdie.angle = (90 * dvy / FLAP) - 180;
  48300. if (this.birdie.angle < -30) {
  48301. this.birdie.angle = -30;
  48302. }
  48303. // 游戏结束 或 大于90度的时候 动画停止
  48304. if (gameOver || this.birdie.angle > 90 || this.birdie.angle < -90) {
  48305. this.birdie.angle = 90;
  48306. this.birdie.animations.stop();
  48307. }
  48308. else {
  48309. this.birdie.animations.play('fly');
  48310. }
  48311. // 游戏进行中
  48312. if (!gameOver) {
  48313. // 检查是否碰撞到水管 游戏结束
  48314. game.physics.arcade.overlap(this.birdie, this.fingers, this.setGameOver, null, this);
  48315. if (!gameOver && this.birdie.body.bottom >= game.world.bounds.bottom - 62) {
  48316. this.setGameOver();
  48317. }
  48318. // 小鸟与洞口碰撞,增加分数
  48319. game.physics.arcade.overlap(this.birdie, this.invs, this.addScore, null, this);
  48320. }
  48321. // 移除屏幕外的水管
  48322. this.fingers.forEachAlive(function(finger) {
  48323. if (finger.x + finger.width < game.world.bounds.left) {
  48324. finger.kill();
  48325. }
  48326. });
  48327. // 更新水管计时器
  48328. this.fingersTimer.update();
  48329. } else {
  48330. this.birdie.y = (game.world.height / 2) + 8 * Math.cos(game.time.now / 200);
  48331. }
  48332. // 滚动地板
  48333. if (!gameOver) {
  48334. this.fence.tilePosition.x -= game.time.physicsElapsed * SPEED / 2;
  48335. }
  48336. },
  48337. render: function () {
  48338. if (DEBUG) {
  48339. game.debug.body(this.birdie);
  48340. game.debug.body(this.fence);
  48341. game.debug.spriteInfo(this.birdie, 32, 32);
  48342. this.fingers.forEachAlive(function(finger) {
  48343. game.debug.body(finger);
  48344. });
  48345. this.invs.forEach(function(inv) {
  48346. game.debug.body(inv);
  48347. });
  48348. }
  48349. }
  48350. }
  48351. // 游戏初始化
  48352. var game = new Phaser.Game(w, h, Phaser.CANVAS, 'screen', null, false);
  48353. // 增加状态
  48354. game.state.add('Boot', Game.Boot);
  48355. game.state.add('Load', Game.Load);
  48356. game.state.add('Play', Game.Play);
  48357. // 游戏启动
  48358. game.state.start('Boot');