babylon.canvas2d.js 995 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329
  1. BABYLON.Effect.ShadersStore['ellipse2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
  2. BABYLON.Effect.ShadersStore['ellipse2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt vec3 renderingInfo;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat ms=properties.z;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<ms) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=ms;\n}\nfloat angle=TWOPI*segi/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat ms=properties.z;\nfloat angle=TWOPI*(index-1.0)/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\n}\n#endif\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\nfloat rx=dot(pos,transformX);\nfloat ry=dot(pos,transformY);\nif (renderingInfo.z == 1.0) {\nrx=floor((rx/renderingInfo.x)+0.5)*renderingInfo.x;\nry=floor((ry/renderingInfo.y)+0.5)*renderingInfo.y;\n}\ngl_Position=vec4(rx,ry,zBias.x,1);\n}";
  3. BABYLON.Effect.ShadersStore['lines2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
  4. BABYLON.Effect.ShadersStore['lines2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute vec2 position;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt vec3 renderingInfo;\natt float opacity;\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec2 boundingMin;\natt vec2 boundingMax;\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=position.xy;\npos.z=1.0;\npos.w=1.0;\nfloat rx=dot(pos,transformX);\nfloat ry=dot(pos,transformY);\nif (renderingInfo.z == 1.0) {\nrx=floor((rx/renderingInfo.x)+0.5)*renderingInfo.x;\nry=floor((ry/renderingInfo.y)+0.5)*renderingInfo.y;\n}\ngl_Position=vec4(rx,ry,zBias.x,1);\n}";
  5. BABYLON.Effect.ShadersStore['rect2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
  6. BABYLON.Effect.ShadersStore['rect2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt vec3 renderingInfo;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n\n#define rsub0 17.0\n#define rsub1 33.0\n#define rsub2 49.0\n#define rsub3 65.0\n#define rsub 64.0\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (properties.z == 0.0) {\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<4.0) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=4.0;\n}\nif (segi == 0.0) {\npos2=vec2(1.0,1.0);\n} \nelse if (segi == 1.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (segi == 2.0) {\npos2=vec2(0.0,0.0);\n} \nelse {\npos2=vec2(0.0,1.0);\n}\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse if (index == 1.0) {\npos2=vec2(1.0,1.0);\n}\nelse if (index == 2.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (index == 3.0) {\npos2=vec2(0.0,0.0);\n}\nelse {\npos2=vec2(0.0,1.0);\n}\n#endif\n}\nelse\n{\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<rsub) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=rsub;\n}\n\nif (segi<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (segi<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (segi<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\n\nif (index<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (index<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (index<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\n}\n#endif\n}\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\nfloat rx=dot(pos,transformX);\nfloat ry=dot(pos,transformY);\nif (renderingInfo.z == 1.0) {\nrx=floor((rx/renderingInfo.x)+0.5)*renderingInfo.x;\nry=floor((ry/renderingInfo.y)+0.5)*renderingInfo.y;\n}\ngl_Position=vec4(rx,ry,zBias.x,1);\n}";
  7. BABYLON.Effect.ShadersStore['sprite2dPixelShader'] = "varying vec2 vUV;\nvarying float vOpacity;\n#ifdef Scale9\nvarying vec2 vTopLeftUV;\nvarying vec2 vBottomRightUV;\nvarying vec4 vScale9;\nvarying vec2 vScaleFactor;\n#endif\nuniform bool alphaTest;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec2 uv=vUV;\n#ifdef Scale9\nvec2 sizeUV=vBottomRightUV-vTopLeftUV;\n\nfloat leftPartUV=vTopLeftUV.x+(vScale9.x/vScaleFactor.x);\nfloat rightPartUV=vTopLeftUV.x+sizeUV.x-((sizeUV.x-vScale9.z)/vScaleFactor.x);\nif (vUV.x<leftPartUV) {\nuv.x=vTopLeftUV.x+((vUV.x- vTopLeftUV.x)*vScaleFactor.x);\n}\nelse if (vUV.x>rightPartUV) {\nuv.x=vTopLeftUV.x+vScale9.z+((vUV.x-rightPartUV)*vScaleFactor.x);\n}\nelse {\nfloat r=(vUV.x-leftPartUV)/(rightPartUV-leftPartUV);\nuv.x=vTopLeftUV.x+vScale9.x+((vScale9.z-vScale9.x)*r);\n}\n\nfloat topPartUV=(vTopLeftUV.y+(vScale9.y/vScaleFactor.y));\nfloat bottomPartUV=(vTopLeftUV.y+sizeUV.y-((sizeUV.y-vScale9.w)/vScaleFactor.y));\nif (vUV.y<topPartUV) {\nuv.y=vTopLeftUV.y+((vUV.y-vTopLeftUV.y)*vScaleFactor.y);\n}\nelse if (vUV.y>bottomPartUV) {\nuv.y=vTopLeftUV.y+vScale9.w+((vUV.y-bottomPartUV)*vScaleFactor.y);\n}\nelse {\nfloat r=(vUV.y-topPartUV)/(bottomPartUV-topPartUV);\nuv.y=vTopLeftUV.y+vScale9.y+((vScale9.w-vScale9.y)*r);\n}\n#endif\nvec4 color=texture2D(diffuseSampler,uv);\nif (alphaTest)\n{\nif (color.a<0.95) {\ndiscard;\n}\n}\ncolor.a*=vOpacity;\ngl_FragColor=color;\n}";
  8. BABYLON.Effect.ShadersStore['sprite2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 topLeftUV;\natt vec2 sizeUV;\n#ifdef Scale9\natt vec2 scaleFactor;\n#endif\natt vec2 textureSize;\n\natt vec3 properties;\n#ifdef Scale9\natt vec4 scale9;\n#endif\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt vec3 renderingInfo;\natt float opacity;\n\n\nvarying vec2 vUV;\nvarying float vOpacity;\n#ifdef Scale9\nvarying vec2 vTopLeftUV;\nvarying vec2 vBottomRightUV;\nvarying vec4 vScale9;\nvarying vec2 vScaleFactor;\n#endif\nvoid main(void) {\nvec2 pos2;\nfloat frame=properties.x;\nfloat invertY=properties.y;\nfloat alignToPixel=properties.z;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x+(frame*sizeUV.x),topLeftUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x+(frame*sizeUV.x),(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 2.0) {\npos2=vec2( 1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 3.0) {\npos2=vec2( 1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),topLeftUV.y);\n}\nif (invertY == 1.0) {\nvUV.y=1.0-vUV.y;\n}\nvec4 pos;\nif (alignToPixel == 1.0)\n{\npos.xy=floor(pos2.xy*sizeUV*textureSize);\n} else {\npos.xy=pos2.xy*sizeUV*textureSize;\n}\n#ifdef Scale9\nif (invertY == 1.0) {\nvTopLeftUV=vec2(topLeftUV.x,1.0-(topLeftUV.y+sizeUV.y));\nvBottomRightUV=vec2(topLeftUV.x+sizeUV.x,1.0-topLeftUV.y);\nvScale9=vec4(scale9.x,sizeUV.y-scale9.w,scale9.z,sizeUV.y-scale9.y);\n}\nelse {\nvTopLeftUV=topLeftUV;\nvBottomRightUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y+sizeUV.y);\nvScale9=scale9;\n}\nvScaleFactor=scaleFactor;\n#endif\nvOpacity=opacity;\npos.z=1.0;\npos.w=1.0;\nfloat x=dot(pos,transformX);\nfloat y=dot(pos,transformY);\nif (renderingInfo.z == 1.0) {\nfloat rw=renderingInfo.x;\nfloat rh=renderingInfo.y;\nfloat irw=2.0/rw;\nfloat irh=2.0/rh;\nx=floor((x/irw)+0.5)*irw;\ny=floor((y/irh)+0.5)*irh;\n}\ngl_Position=vec4(x,y,zBias.x,1);\n} ";
  9. BABYLON.Effect.ShadersStore['text2dPixelShader'] = "\nvarying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\n#ifdef SignedDistanceField\nfloat dist=texture2D(diffuseSampler,vUV).r;\nif (dist<0.5) {\ndiscard;\n}\n\n\n\n\n\ngl_FragColor=vec4(vColor.xyz*dist,vColor.a);\n#else\nvec4 color=texture2D(diffuseSampler,vUV);\nif (color.a == 0.0) {\ndiscard;\n}\n#ifdef FontTexture\ngl_FragColor=vec4(color.xxxx)*vColor;\n#else\ngl_FragColor=color*vColor;\n#endif\n#endif\n}";
  10. BABYLON.Effect.ShadersStore['text2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt vec3 renderingInfo;\natt float opacity;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 textureSize;\natt vec4 color;\natt float superSampleFactor;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y+sizeUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y);\n}\n\nelse if (index == 2.0) {\npos2=vec2(1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y);\n}\n\nelse if (index == 3.0) {\npos2=vec2(1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y+sizeUV.y);\n}\n\nvUV=(floor(vUV*textureSize)+vec2(0.0,0.0))/textureSize;\nvColor=color;\nvColor.a*=opacity;\nvec4 pos;\npos.xy=floor(pos2.xy*superSampleFactor*sizeUV*textureSize); \npos.z=1.0;\npos.w=1.0;\nfloat x=dot(pos,transformX);\nfloat y=dot(pos,transformY);\nif (renderingInfo.z == 1.0) {\nfloat rw=renderingInfo.x;\nfloat rh=renderingInfo.y;\nfloat irw=2.0/rw;\nfloat irh=2.0/rh;\nx=floor((x/irw)+0.5)*irw;\ny=floor((y/irh)+0.5)*irh;\n}\ngl_Position=vec4(x,y,zBias.x,1);\n}";
  11. BABYLON.Effect.ShadersStore['wireframe2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
  12. BABYLON.Effect.ShadersStore['wireframe2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute vec2 pos;\nattribute vec4 col;\n\n\n\n\natt vec3 properties;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n\n\nvarying vec4 vColor;\nvoid main(void) {\nvec4 p=vec4(pos.xy,1.0,1.0);\nvColor=vec4(col.xyz,col.w*opacity);\nvec4 pp=vec4(dot(p,transformX),dot(p,transformY),zBias.x,1);\nif (properties.x == 1.0) {\npp.xy=pp.xy-mod(pp.xy,properties.yz)+(properties.yz*0.5);\n}\ngl_Position=pp;\n} ";
  13. var BABYLON;
  14. (function (BABYLON) {
  15. /**
  16. * This class stores the data to make 2D transformation using a Translation (tX, tY), a Scale (sX, sY) and a rotation around the Z axis (rZ).
  17. * You can multiply two Transform2D object to produce the result of their concatenation.
  18. * You can transform a given Point (a Vector2D instance) with a Transform2D object or with the Invert of the Transform2D object.
  19. * There no need to compute/store the Invert of a Transform2D as the invertTranform methods are almost as fast as the transform ones.
  20. * This class is as light as it could be and the transformation operations are pretty optimal.
  21. */
  22. var Transform2D = (function () {
  23. function Transform2D() {
  24. this.translation = BABYLON.Vector2.Zero();
  25. this.rotation = 0;
  26. this.scale = new BABYLON.Vector2(1, 1);
  27. }
  28. /**
  29. * Set the Transform2D object with the given values
  30. * @param translation The translation to set
  31. * @param rotation The rotation (in radian) to set
  32. * @param scale The scale to set
  33. */
  34. Transform2D.prototype.set = function (translation, rotation, scale) {
  35. this.translation.copyFrom(translation);
  36. this.rotation = rotation;
  37. this.scale.copyFrom(scale);
  38. };
  39. /**
  40. * Set the Transform2D object from float values
  41. * @param transX The translation on X axis, nothing is set if not specified
  42. * @param transY The translation on Y axis, nothing is set if not specified
  43. * @param rotation The rotation in radian, nothing is set if not specified
  44. * @param scaleX The scale along the X axis, nothing is set if not specified
  45. * @param scaleY The scale along the Y axis, nothing is set if not specified
  46. */
  47. Transform2D.prototype.setFromFloats = function (transX, transY, rotation, scaleX, scaleY) {
  48. if (transX) {
  49. this.translation.x = transX;
  50. }
  51. if (transY) {
  52. this.translation.y = transY;
  53. }
  54. if (rotation) {
  55. this.rotation = rotation;
  56. }
  57. if (scaleX) {
  58. this.scale.x = scaleX;
  59. }
  60. if (scaleY) {
  61. this.scale.y = scaleY;
  62. }
  63. };
  64. /**
  65. * Return a copy of the object
  66. */
  67. Transform2D.prototype.clone = function () {
  68. var res = new Transform2D();
  69. res.translation.copyFrom(this.translation);
  70. res.rotation = this.rotation;
  71. res.scale.copyFrom(this.scale);
  72. return res;
  73. };
  74. /**
  75. * Convert a given degree angle into its radian equivalent
  76. * @param angleDegree the number to convert
  77. */
  78. Transform2D.ToRadian = function (angleDegree) {
  79. return angleDegree * Math.PI * 2 / 360;
  80. };
  81. /**
  82. * Create a new instance and returns it
  83. * @param translation The translation to store, default is (0,0)
  84. * @param rotation The rotation to store, default is 0
  85. * @param scale The scale to store, default is (1,1)
  86. */
  87. Transform2D.Make = function (translation, rotation, scale) {
  88. var res = new Transform2D();
  89. if (translation) {
  90. res.translation.copyFrom(translation);
  91. }
  92. if (rotation) {
  93. res.rotation = rotation;
  94. }
  95. if (scale) {
  96. res.scale.copyFrom(scale);
  97. }
  98. return res;
  99. };
  100. /**
  101. * Set the given Transform2D object with the given values
  102. * @param translation The translation to store, default is (0,0)
  103. * @param rotation The rotation to store, default is 0
  104. * @param scale The scale to store, default is (1,1)
  105. */
  106. Transform2D.MakeToRef = function (res, translation, rotation, scale) {
  107. if (translation) {
  108. res.translation.copyFrom(translation);
  109. }
  110. else {
  111. res.translation.copyFromFloats(0, 0);
  112. }
  113. if (rotation) {
  114. res.rotation = rotation;
  115. }
  116. else {
  117. res.rotation = 0;
  118. }
  119. if (scale) {
  120. res.scale.copyFrom(scale);
  121. }
  122. else {
  123. res.scale.copyFromFloats(1, 1);
  124. }
  125. };
  126. /**
  127. * Create a Transform2D object from float values
  128. * @param transX The translation on X axis, 0 per default
  129. * @param transY The translation on Y axis, 0 per default
  130. * @param rotation The rotation in radian, 0 per default
  131. * @param scaleX The scale along the X axis, 1 per default
  132. * @param scaleY The scale along the Y axis, 1 per default
  133. */
  134. Transform2D.MakeFromFloats = function (transX, transY, rotation, scaleX, scaleY) {
  135. var res = new Transform2D();
  136. if (transX) {
  137. res.translation.x = transX;
  138. }
  139. if (transY) {
  140. res.translation.y = transY;
  141. }
  142. if (rotation) {
  143. res.rotation = rotation;
  144. }
  145. if (scaleX) {
  146. res.scale.x = scaleX;
  147. }
  148. if (scaleY) {
  149. res.scale.y = scaleY;
  150. }
  151. return res;
  152. };
  153. /**
  154. * Set the given Transform2D object with the given float values
  155. * @param transX The translation on X axis, 0 per default
  156. * @param transY The translation on Y axis, 0 per default
  157. * @param rotation The rotation in radian, 0 per default
  158. * @param scaleX The scale along the X axis, 1 per default
  159. * @param scaleY The scale along the Y axis, 1 per default
  160. */
  161. Transform2D.MakeFromFloatsToRef = function (res, transX, transY, rotation, scaleX, scaleY) {
  162. res.translation.x = (transX != null) ? transX : 0;
  163. res.translation.y = (transY != null) ? transY : 0;
  164. res.rotation = (rotation != null) ? rotation : 0;
  165. res.scale.x = (scaleX != null) ? scaleX : 1;
  166. res.scale.y = (scaleY != null) ? scaleY : 1;
  167. };
  168. /**
  169. * Create a Transform2D containing only Zeroed values
  170. */
  171. Transform2D.Zero = function () {
  172. var res = new Transform2D();
  173. res.scale.copyFromFloats(0, 0);
  174. return res;
  175. };
  176. /**
  177. * Copy the value of the other object into 'this'
  178. * @param other The other object to copy values from
  179. */
  180. Transform2D.prototype.copyFrom = function (other) {
  181. this.translation.copyFrom(other.translation);
  182. this.rotation = other.rotation;
  183. this.scale.copyFrom(other.scale);
  184. };
  185. Transform2D.prototype.toMatrix2D = function () {
  186. var res = new Matrix2D();
  187. this.toMatrix2DToRef(res);
  188. return res;
  189. };
  190. Transform2D.prototype.toMatrix2DToRef = function (res) {
  191. var tx = this.translation.x;
  192. var ty = this.translation.y;
  193. var r = this.rotation;
  194. var cosr = Math.cos(r);
  195. var sinr = Math.sin(r);
  196. var sx = this.scale.x;
  197. var sy = this.scale.y;
  198. res.m[0] = cosr * sx;
  199. res.m[1] = sinr * sy;
  200. res.m[2] = -sinr * sx;
  201. res.m[3] = cosr * sy;
  202. res.m[4] = tx;
  203. res.m[5] = ty;
  204. };
  205. /**
  206. * In place transformation from a parent matrix.
  207. * @param parent transform object. "this" will be the result of parent * this
  208. */
  209. Transform2D.prototype.multiplyToThis = function (parent) {
  210. this.multiplyToRef(parent, this);
  211. };
  212. /**
  213. * Transform this object with a parent and return the result. Result = parent * this
  214. * @param parent The parent transformation
  215. */
  216. Transform2D.prototype.multiply = function (parent) {
  217. var res = new Transform2D();
  218. this.multiplyToRef(parent, res);
  219. return res;
  220. };
  221. /**
  222. * Transform a point and store the result in the very same object
  223. * @param p Transform this point and change the values with the transformed ones
  224. */
  225. Transform2D.prototype.transformPointInPlace = function (p) {
  226. this.transformPointToRef(p, p);
  227. };
  228. /**
  229. * Transform a point and store the result into a reference object
  230. * @param p The point to transform
  231. * @param res Will contain the new transformed coordinates. Can be the object of 'p'.
  232. */
  233. Transform2D.prototype.transformPointToRef = function (p, res) {
  234. this.transformFloatsToRef(p.x, p.y, res);
  235. };
  236. /**
  237. * Transform this object with a parent and store the result in reference object
  238. * @param parent The parent transformation
  239. * @param result Will contain parent * this. Can be the object of either parent or 'this'
  240. */
  241. Transform2D.prototype.multiplyToRef = function (parent, result) {
  242. if (!parent || !result) {
  243. throw new Error("Valid parent and result objects must be specified");
  244. }
  245. var tx = this.translation.x;
  246. var ty = this.translation.y;
  247. var ptx = parent.translation.x;
  248. var pty = parent.translation.y;
  249. var pr = parent.rotation;
  250. var psx = parent.scale.x;
  251. var psy = parent.scale.y;
  252. var cosr = Math.cos(pr);
  253. var sinr = Math.sin(pr);
  254. result.translation.x = (((tx * cosr) - (ty * sinr)) * psx) + ptx;
  255. result.translation.y = (((tx * sinr) + (ty * cosr)) * psy) + pty;
  256. this.scale.multiplyToRef(parent.scale, result.scale);
  257. result.rotation = this.rotation;
  258. };
  259. /**
  260. * Transform the given coordinates and store the result in a Vector2 object
  261. * @param x The X coordinate to transform
  262. * @param y The Y coordinate to transform
  263. * @param res The Vector2 object that will contain the result of the transformation
  264. */
  265. Transform2D.prototype.transformFloatsToRef = function (x, y, res) {
  266. var tx = this.translation.x;
  267. var ty = this.translation.y;
  268. var pr = this.rotation;
  269. var sx = this.scale.x;
  270. var sy = this.scale.y;
  271. var cosr = Math.cos(pr);
  272. var sinr = Math.sin(pr);
  273. res.x = (((x * cosr) - (y * sinr)) * sx) + tx;
  274. res.y = (((x * sinr) + (y * cosr)) * sy) + ty;
  275. };
  276. /**
  277. * Invert transform the given coordinates and store the result in a reference object. res = invert(this) * (x,y)
  278. * @param p Transform this point and change the values with the transformed ones
  279. * @param res Will contain the result of the invert transformation.
  280. */
  281. Transform2D.prototype.invertTransformFloatsToRef = function (x, y, res) {
  282. var px = x - this.translation.x;
  283. var py = y - this.translation.y;
  284. var pr = -this.rotation;
  285. var sx = this.scale.x;
  286. var sy = this.scale.y;
  287. var psx = (sx === 1) ? 1 : (1 / sx);
  288. var psy = (sy === 1) ? 1 : (1 / sy);
  289. var cosr = Math.cos(pr);
  290. var sinr = Math.sin(pr);
  291. res.x = (((px * cosr) - (py * sinr)) * psx);
  292. res.y = (((px * sinr) + (py * cosr)) * psy);
  293. };
  294. /**
  295. * Transform a point and return the result
  296. * @param p the point to transform
  297. */
  298. Transform2D.prototype.transformPoint = function (p) {
  299. var res = BABYLON.Vector2.Zero();
  300. this.transformPointToRef(p, res);
  301. return res;
  302. };
  303. /**
  304. * Transform the given coordinates and return the result in a Vector2 object
  305. * @param x The X coordinate to transform
  306. * @param y The Y coordinate to transform
  307. */
  308. Transform2D.prototype.transformFloats = function (x, y) {
  309. var res = BABYLON.Vector2.Zero();
  310. this.transformFloatsToRef(x, y, res);
  311. return res;
  312. };
  313. /**
  314. * Invert transform a given point and store the result in the very same object. p = invert(this) * p
  315. * @param p Transform this point and change the values with the transformed ones
  316. */
  317. Transform2D.prototype.invertTransformPointInPlace = function (p) {
  318. this.invertTransformPointToRef(p, p);
  319. };
  320. /**
  321. * Invert transform a given point and store the result in a reference object. res = invert(this) * p
  322. * @param p Transform this point and change the values with the transformed ones
  323. * @param res Will contain the result of the invert transformation. 'res' can be the same object as 'p'
  324. */
  325. Transform2D.prototype.invertTransformPointToRef = function (p, res) {
  326. this.invertTransformFloatsToRef(p.x, p.y, res);
  327. };
  328. /**
  329. * Invert transform a given point and return the result. return = invert(this) * p
  330. * @param p The Point to transform
  331. */
  332. Transform2D.prototype.invertTransformPoint = function (p) {
  333. var res = BABYLON.Vector2.Zero();
  334. this.invertTransformPointToRef(p, res);
  335. return res;
  336. };
  337. /**
  338. * Invert transform the given coordinates and return the result. return = invert(this) * (x,y)
  339. * @param x The X coordinate to transform
  340. * @param y The Y coordinate to transform
  341. */
  342. Transform2D.prototype.invertTransformFloats = function (x, y) {
  343. var res = BABYLON.Vector2.Zero();
  344. this.invertTransformFloatsToRef(x, y, res);
  345. return res;
  346. };
  347. return Transform2D;
  348. }());
  349. BABYLON.Transform2D = Transform2D;
  350. /**
  351. * A class storing a Matrix for 2D transformations
  352. * The stored matrix is a 2*3 Matrix
  353. * I [0,1] [mX, mY] R [ CosZ, SinZ] T [ 0, 0] S [Sx, 0]
  354. * D = [2,3] = [nX, nY] O = [-SinZ, CosZ] R = [ 0, 0] C = [ 0, Sy]
  355. * X [4,5] [tX, tY] T [ 0 , 0 ] N [Tx, Ty] L [ 0, 0]
  356. *
  357. * IDX = index, zero based. ROT = Z axis Rotation. TRN = Translation. SCL = Scale.
  358. */
  359. var Matrix2D = (function () {
  360. function Matrix2D() {
  361. this.m = new Float32Array(6);
  362. }
  363. Matrix2D.Identity = function () {
  364. var res = new Matrix2D();
  365. Matrix2D.IdentityToRef(res);
  366. return res;
  367. };
  368. Matrix2D.IdentityToRef = function (res) {
  369. res.m[1] = res.m[2] = res.m[4] = res.m[5] = 0;
  370. res.m[0] = res.m[3] = 1;
  371. };
  372. Matrix2D.prototype.copyFrom = function (other) {
  373. for (var i = 0; i < 6; i++) {
  374. this.m[i] = other.m[i];
  375. }
  376. };
  377. Matrix2D.prototype.determinant = function () {
  378. return (this.m[0] * this.m[3]) - (this.m[1] * this.m[2]);
  379. };
  380. Matrix2D.prototype.invertToThis = function () {
  381. this.invertToRef(this);
  382. };
  383. Matrix2D.prototype.invert = function () {
  384. var res = new Matrix2D();
  385. this.invertToRef(res);
  386. return res;
  387. };
  388. Matrix2D.prototype.invertToRef = function (res) {
  389. var a00 = this.m[0], a01 = this.m[1], a10 = this.m[2], a11 = this.m[3], a20 = this.m[4], a21 = this.m[5];
  390. var det21 = a21 * a10 - a11 * a20;
  391. var det = (a00 * a11) - (a01 * a10);
  392. if (det < (BABYLON.Epsilon * BABYLON.Epsilon)) {
  393. throw new Error("Can't invert matrix, near null determinant");
  394. }
  395. det = 1 / det;
  396. res.m[0] = a11 * det;
  397. res.m[1] = -a01 * det;
  398. res.m[2] = -a10 * det;
  399. res.m[3] = a00 * det;
  400. res.m[4] = det21 * det;
  401. res.m[5] = (-a21 * a00 + a01 * a20) * det;
  402. };
  403. Matrix2D.prototype.multiplyToThis = function (other) {
  404. this.multiplyToRef(other, this);
  405. };
  406. Matrix2D.prototype.multiply = function (other) {
  407. var res = new Matrix2D();
  408. this.multiplyToRef(other, res);
  409. return res;
  410. };
  411. Matrix2D.prototype.multiplyToRef = function (other, result) {
  412. var tm0 = this.m[0];
  413. var tm1 = this.m[1];
  414. //var tm2 = this.m[2];
  415. //var tm3 = this.m[3];
  416. var tm4 = this.m[2];
  417. var tm5 = this.m[3];
  418. //var tm6 = this.m[6];
  419. //var tm7 = this.m[7];
  420. var tm8 = this.m[4];
  421. var tm9 = this.m[5];
  422. //var tm10 = this.m[10];
  423. //var tm11 = this.m[11];
  424. //var tm12 = this.m[12];
  425. //var tm13 = this.m[13];
  426. //var tm14 = this.m[14];
  427. //var tm15 = this.m[15];
  428. var om0 = other.m[0];
  429. var om1 = other.m[1];
  430. //var om2 = other.m[2];
  431. //var om3 = other.m[3];
  432. var om4 = other.m[2];
  433. var om5 = other.m[3];
  434. //var om6 = other.m[6];
  435. //var om7 = other.m[7];
  436. var om8 = other.m[4];
  437. var om9 = other.m[5];
  438. //var om10 = other.m[10];
  439. //var om11 = other.m[11];
  440. //var om12 = other.m[12];
  441. //var om13 = other.m[13];
  442. //var om14 = other.m[14];
  443. //var om15 = other.m[15];
  444. result.m[0] = tm0 * om0 + tm1 * om4;
  445. result.m[1] = tm0 * om1 + tm1 * om5;
  446. //result.m[2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  447. //result.m[3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  448. result.m[2] = tm4 * om0 + tm5 * om4;
  449. result.m[3] = tm4 * om1 + tm5 * om5;
  450. //result.m[6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  451. //result.m[7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  452. result.m[4] = tm8 * om0 + tm9 * om4 + om8;
  453. result.m[5] = tm8 * om1 + tm9 * om5 + om9;
  454. //result.m[10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  455. //result.m[11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  456. //result.m[12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  457. //result.m[13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  458. //result.m[14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  459. //result.m[15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  460. };
  461. Matrix2D.prototype.transformFloats = function (x, y) {
  462. var res = BABYLON.Vector2.Zero();
  463. this.transformFloatsToRef(x, y, res);
  464. return res;
  465. };
  466. Matrix2D.prototype.transformFloatsToRef = function (x, y, r) {
  467. r.x = x * this.m[0] + y * this.m[2] + this.m[4];
  468. r.y = x * this.m[1] + y * this.m[3] + this.m[5];
  469. };
  470. Matrix2D.prototype.transformPoint = function (p) {
  471. var res = BABYLON.Vector2.Zero();
  472. this.transformFloatsToRef(p.x, p.y, res);
  473. return res;
  474. };
  475. Matrix2D.prototype.transformPointToRef = function (p, r) {
  476. this.transformFloatsToRef(p.x, p.y, r);
  477. };
  478. return Matrix2D;
  479. }());
  480. BABYLON.Matrix2D = Matrix2D;
  481. /**
  482. * Stores information about a 2D Triangle.
  483. * This class stores the 3 vertices but also the center and radius of the triangle
  484. */
  485. var Tri2DInfo = (function () {
  486. /**
  487. * Construct an instance of Tri2DInfo, you can either pass null to a, b and c and the instance will be allocated "clear", or give actual triangle info and the center/radius will be computed
  488. */
  489. function Tri2DInfo(a, b, c) {
  490. if (a === null && b === null && c === null) {
  491. this.a = BABYLON.Vector2.Zero();
  492. this.b = BABYLON.Vector2.Zero();
  493. this.c = BABYLON.Vector2.Zero();
  494. this.center = BABYLON.Vector2.Zero();
  495. this.radius = 0;
  496. return;
  497. }
  498. this.a = a.clone();
  499. this.b = b.clone();
  500. this.c = c.clone();
  501. this._updateCenterRadius();
  502. }
  503. Tri2DInfo.Zero = function () {
  504. return new Tri2DInfo(null, null, null);
  505. };
  506. Tri2DInfo.prototype.set = function (a, b, c) {
  507. this.a.copyFrom(a);
  508. this.b.copyFrom(b);
  509. this.c.copyFrom(c);
  510. this._updateCenterRadius();
  511. };
  512. Tri2DInfo.prototype.transformInPlace = function (transform) {
  513. BABYLON.Vector2.TransformToRef(this.a, transform, this.a);
  514. BABYLON.Vector2.TransformToRef(this.b, transform, this.b);
  515. BABYLON.Vector2.TransformToRef(this.c, transform, this.c);
  516. this._updateCenterRadius();
  517. };
  518. Tri2DInfo.prototype.doesContain = function (p) {
  519. return BABYLON.Vector2.PointInTriangle(p, this.a, this.b, this.c);
  520. };
  521. Tri2DInfo.prototype._updateCenterRadius = function () {
  522. this.center.x = (this.a.x + this.b.x + this.c.x) / 3;
  523. this.center.y = (this.a.y + this.b.y + this.c.y) / 3;
  524. var la = BABYLON.Vector2.DistanceSquared(this.a, this.center);
  525. var lb = BABYLON.Vector2.DistanceSquared(this.b, this.center);
  526. var lc = BABYLON.Vector2.DistanceSquared(this.c, this.center);
  527. var rs = Math.max(Math.max(la, lb), lc);
  528. this.radius = Math.sqrt(rs);
  529. };
  530. return Tri2DInfo;
  531. }());
  532. BABYLON.Tri2DInfo = Tri2DInfo;
  533. /**
  534. * Stores an array of 2D Triangles.
  535. * Internally the data is stored as a Float32Array to minimize the memory footprint.
  536. * This can use the Tri2DInfo class as proxy for storing/retrieving data.
  537. * The array can't grow, it's fixed size.
  538. */
  539. var Tri2DArray = (function () {
  540. function Tri2DArray(count) {
  541. this._count = count;
  542. this._array = new Float32Array(9 * count);
  543. }
  544. /**
  545. * Clear the content and allocate a new array to store the given count of triangles
  546. * @param count The new count of triangles to store
  547. */
  548. Tri2DArray.prototype.clear = function (count) {
  549. if (this._count === count) {
  550. return;
  551. }
  552. this._count = count;
  553. this._array = new Float32Array(9 * count);
  554. };
  555. /**
  556. * Store a given triangle at the given index
  557. * @param index the 0 based index to store the triangle in the array
  558. * @param a the A vertex of the triangle
  559. * @param b the B vertex of the triangle
  560. * @param c the C vertex of the triangle
  561. */
  562. Tri2DArray.prototype.storeTriangle = function (index, a, b, c) {
  563. var center = new BABYLON.Vector2((a.x + b.x + c.x) / 3, (a.y + b.y + c.y) / 3);
  564. var la = BABYLON.Vector2.DistanceSquared(a, center);
  565. var lb = BABYLON.Vector2.DistanceSquared(b, center);
  566. var lc = BABYLON.Vector2.DistanceSquared(c, center);
  567. var rs = Math.max(Math.max(la, lb), lc);
  568. var radius = Math.sqrt(rs);
  569. var offset = index * 9;
  570. this._array[offset + 0] = a.x;
  571. this._array[offset + 1] = a.y;
  572. this._array[offset + 2] = b.x;
  573. this._array[offset + 3] = b.y;
  574. this._array[offset + 4] = c.x;
  575. this._array[offset + 5] = c.y;
  576. this._array[offset + 6] = center.x;
  577. this._array[offset + 7] = center.y;
  578. this._array[offset + 8] = radius;
  579. };
  580. /**
  581. * Store a triangle in a Tri2DInfo object
  582. * @param index the index of the triangle to store
  583. * @param tri2dInfo the instance that will contain the data, it must be already allocated with its inner object also allocated
  584. */
  585. Tri2DArray.prototype.storeToTri2DInfo = function (index, tri2dInfo) {
  586. if (index >= this._count) {
  587. throw new Error("Can't fetch the triangle at index " + index + ", max index is " + (this._count - 1));
  588. }
  589. var offset = index * 9;
  590. tri2dInfo.a.x = this._array[offset + 0];
  591. tri2dInfo.a.y = this._array[offset + 1];
  592. tri2dInfo.b.x = this._array[offset + 2];
  593. tri2dInfo.b.y = this._array[offset + 3];
  594. tri2dInfo.c.x = this._array[offset + 4];
  595. tri2dInfo.c.y = this._array[offset + 5];
  596. tri2dInfo.center.x = this._array[offset + 6];
  597. tri2dInfo.center.y = this._array[offset + 7];
  598. tri2dInfo.radius = this._array[offset + 8];
  599. };
  600. /**
  601. * Transform the given triangle and store its result in the array
  602. * @param index The index to store the result to
  603. * @param tri2dInfo The triangle to transform
  604. * @param transform The transformation matrix
  605. */
  606. Tri2DArray.prototype.transformAndStoreToTri2DInfo = function (index, tri2dInfo, transform) {
  607. if (index >= this._count) {
  608. throw new Error("Can't fetch the triangle at index " + index + ", max index is " + (this._count - 1));
  609. }
  610. var offset = index * 9;
  611. tri2dInfo.a.x = this._array[offset + 0];
  612. tri2dInfo.a.y = this._array[offset + 1];
  613. tri2dInfo.b.x = this._array[offset + 2];
  614. tri2dInfo.b.y = this._array[offset + 3];
  615. tri2dInfo.c.x = this._array[offset + 4];
  616. tri2dInfo.c.y = this._array[offset + 5];
  617. tri2dInfo.transformInPlace(transform);
  618. };
  619. Object.defineProperty(Tri2DArray.prototype, "count", {
  620. /**
  621. * Get the element count that can be stored in this array
  622. * @returns {}
  623. */
  624. get: function () {
  625. return this._count;
  626. },
  627. enumerable: true,
  628. configurable: true
  629. });
  630. /**
  631. * Check if a given point intersects with at least one of the triangles stored in the array.
  632. * If true is returned the point is intersecting with at least one triangle, false if it doesn't intersect with any of them
  633. * @param p The point to check
  634. */
  635. Tri2DArray.prototype.doesContain = function (p) {
  636. Tri2DArray._checkInitStatics();
  637. var a = Tri2DArray.tempT[0];
  638. for (var i = 0; i < this.count; i++) {
  639. this.storeToTri2DInfo(i, a);
  640. if (a.doesContain(p)) {
  641. return true;
  642. }
  643. }
  644. return false;
  645. };
  646. /**
  647. * Make a intersection test between two sets of triangles. The triangles of setB will be transformed to the frame of reference of the setA using the given bToATransform matrix.
  648. * If true is returned at least one triangle intersects with another of the other set, otherwise false is returned.
  649. * @param setA The first set of triangles
  650. * @param setB The second set of triangles
  651. * @param bToATransform The transformation matrix to transform the setB triangles into the frame of reference of the setA
  652. */
  653. Tri2DArray.doesIntersect = function (setA, setB, bToATransform) {
  654. Tri2DArray._checkInitStatics();
  655. var a = Tri2DArray.tempT[0];
  656. var b = Tri2DArray.tempT[1];
  657. var v0 = Tri2DArray.tempV[0];
  658. for (var curB = 0; curB < setB.count; curB++) {
  659. setB.transformAndStoreToTri2DInfo(curB, b, bToATransform);
  660. for (var curA = 0; curA < setA.count; curA++) {
  661. setA.storeToTri2DInfo(curA, a);
  662. // Fast rejection first
  663. v0.x = a.center.x - b.center.x;
  664. v0.y = a.center.y - b.center.y;
  665. if (v0.lengthSquared() > ((a.radius * a.radius) + (b.radius * b.radius))) {
  666. continue;
  667. }
  668. // Actual intersection test
  669. if (Math2D.TriangleTriangleDosIntersect(a.a, a.b, a.c, b.a, b.b, b.c)) {
  670. return true;
  671. }
  672. }
  673. }
  674. return false;
  675. };
  676. Tri2DArray._checkInitStatics = function () {
  677. if (Tri2DArray.tempT !== null) {
  678. return;
  679. }
  680. Tri2DArray.tempT = new Array(2);
  681. Tri2DArray.tempT[0] = new Tri2DInfo(null, null, null);
  682. Tri2DArray.tempT[1] = new Tri2DInfo(null, null, null);
  683. Tri2DArray.tempV = new Array(6);
  684. for (var i = 0; i < 6; i++) {
  685. Tri2DArray.tempV[i] = BABYLON.Vector2.Zero();
  686. }
  687. };
  688. return Tri2DArray;
  689. }());
  690. Tri2DArray.tempV = null;
  691. Tri2DArray.tempT = null;
  692. BABYLON.Tri2DArray = Tri2DArray;
  693. /**
  694. * Some 2D Math helpers functions
  695. */
  696. var Math2D = (function () {
  697. function Math2D() {
  698. }
  699. Math2D.Dot = function (a, b) {
  700. return a.x * b.x + a.y * b.y;
  701. };
  702. // From http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
  703. // Note: this one might also be considered with the above one proves to not be good enough: http://jsfiddle.net/justin_c_rounds/Gd2S2/light/
  704. Math2D.LineLineDoesIntersect = function (segA1, segA2, segB1, segB2) {
  705. var s1_x = segA2.x - segA1.x;
  706. var s1_y = segA2.y - segA1.y;
  707. var s2_x = segB2.x - segB1.x;
  708. var s2_y = segB2.y - segB1.y;
  709. var s = (-s1_y * (segA1.x - segB1.x) + s1_x * (segA1.y - segB1.y)) / (-s2_x * s1_y + s1_x * s2_y);
  710. var t = (s2_x * (segA1.y - segB1.y) - s2_y * (segA1.x - segB1.x)) / (-s2_x * s1_y + s1_x * s2_y);
  711. if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
  712. return true;
  713. }
  714. return false;
  715. };
  716. // From http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
  717. Math2D.LineLineIntersection = function (p0, p1, p2, p3) {
  718. var s1_x = p1.x - p0.x;
  719. var s1_y = p1.y - p0.y;
  720. var s2_x = p3.x - p2.x;
  721. var s2_y = p3.y - p2.y;
  722. var s = (-s1_y * (p0.x - p2.x) + s1_x * (p0.y - p2.y)) / (-s2_x * s1_y + s1_x * s2_y);
  723. var t = (s2_x * (p0.y - p2.y) - s2_y * (p0.x - p2.x)) / (-s2_x * s1_y + s1_x * s2_y);
  724. if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
  725. return { res: true, xr: p0.x + (t * s1_x), yr: p0.y + (t * s1_y) };
  726. }
  727. return { res: false, xr: 0, yr: 0 };
  728. };
  729. // Tell me that it's slow and I'll answer: yes it is!
  730. // If you fancy to implement the SAT (Separating Axis Theorem) version: BE MY VERY WELCOMED GUEST!
  731. Math2D.TriangleTriangleDosIntersect = function (tri1A, tri1B, tri1C, tri2A, tri2B, tri2C) {
  732. if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2A, tri2B))
  733. return true;
  734. if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2A, tri2C))
  735. return true;
  736. if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2B, tri2C))
  737. return true;
  738. if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2A, tri2B))
  739. return true;
  740. if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2A, tri2C))
  741. return true;
  742. if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2B, tri2C))
  743. return true;
  744. if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2A, tri2B))
  745. return true;
  746. if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2A, tri2C))
  747. return true;
  748. if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2B, tri2C))
  749. return true;
  750. if (BABYLON.Vector2.PointInTriangle(tri2A, tri1A, tri1B, tri1C) &&
  751. BABYLON.Vector2.PointInTriangle(tri2B, tri1A, tri1B, tri1C) &&
  752. BABYLON.Vector2.PointInTriangle(tri2C, tri1A, tri1B, tri1C))
  753. return true;
  754. if (BABYLON.Vector2.PointInTriangle(tri1A, tri2A, tri2B, tri2C) &&
  755. BABYLON.Vector2.PointInTriangle(tri1B, tri2A, tri2B, tri2C) &&
  756. BABYLON.Vector2.PointInTriangle(tri1C, tri2A, tri2B, tri2C))
  757. return true;
  758. return false;
  759. };
  760. return Math2D;
  761. }());
  762. Math2D.v0 = BABYLON.Vector2.Zero();
  763. Math2D.v1 = BABYLON.Vector2.Zero();
  764. Math2D.v2 = BABYLON.Vector2.Zero();
  765. })(BABYLON || (BABYLON = {}));
  766. //# sourceMappingURL=babylon.math2D.js.map
  767. var BABYLON;
  768. (function (BABYLON) {
  769. var PropertyChangedInfo = (function () {
  770. function PropertyChangedInfo() {
  771. }
  772. return PropertyChangedInfo;
  773. }());
  774. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  775. /**
  776. * The purpose of this class is to provide a base implementation of the IPropertyChanged interface for the user to avoid rewriting a code needlessly.
  777. * Typical use of this class is to check for equality in a property set(), then call the onPropertyChanged method if values are different after the new value is set. The protected method will notify observers of the change.
  778. * Remark: onPropertyChanged detects reentrant code and acts in a way to make sure everything is fine, fast and allocation friendly (when there no reentrant code which should be 99% of the time)
  779. */
  780. var PropertyChangedBase = (function () {
  781. function PropertyChangedBase() {
  782. this._propertyChanged = null;
  783. }
  784. /**
  785. * Protected method to call when there's a change of value in a property set
  786. * @param propName the name of the concerned property
  787. * @param oldValue its old value
  788. * @param newValue its new value
  789. * @param mask an optional observable mask
  790. */
  791. PropertyChangedBase.prototype.onPropertyChanged = function (propName, oldValue, newValue, mask) {
  792. if (this.propertyChanged.hasObservers()) {
  793. var pci = PropertyChangedBase.calling ? new PropertyChangedInfo() : PropertyChangedBase.pci;
  794. pci.oldValue = oldValue;
  795. pci.newValue = newValue;
  796. pci.propertyName = propName;
  797. try {
  798. PropertyChangedBase.calling = true;
  799. this.propertyChanged.notifyObservers(pci, mask);
  800. }
  801. finally {
  802. PropertyChangedBase.calling = false;
  803. }
  804. }
  805. };
  806. Object.defineProperty(PropertyChangedBase.prototype, "propertyChanged", {
  807. /**
  808. * An observable that is triggered when a property (using of the XXXXLevelProperty decorator) has its value changing.
  809. * You can add an observer that will be triggered only for a given set of Properties using the Mask feature of the Observable and the corresponding Prim2DPropInfo.flagid value (e.g. Prim2DBase.positionProperty.flagid|Prim2DBase.rotationProperty.flagid to be notified only about position or rotation change)
  810. */
  811. get: function () {
  812. if (!this._propertyChanged) {
  813. this._propertyChanged = new BABYLON.Observable();
  814. }
  815. return this._propertyChanged;
  816. },
  817. enumerable: true,
  818. configurable: true
  819. });
  820. return PropertyChangedBase;
  821. }());
  822. PropertyChangedBase.pci = new PropertyChangedInfo();
  823. PropertyChangedBase.calling = false;
  824. BABYLON.PropertyChangedBase = PropertyChangedBase;
  825. })(BABYLON || (BABYLON = {}));
  826. //# sourceMappingURL=babylon.iPropertyChanged.js.map
  827. var BABYLON;
  828. (function (BABYLON) {
  829. // logging stuffs
  830. var C2DLogging = (function () {
  831. function C2DLogging() {
  832. }
  833. C2DLogging.logFrameRender = function (frameCount) {
  834. C2DLogging.snooze = true;
  835. C2DLogging._logFramesCount = frameCount;
  836. };
  837. C2DLogging.setPostMessage = function (message) {
  838. if (C2DLoggingInternals.enableLog) {
  839. C2DLoggingInternals.postMessages[C2DLoggingInternals.callDepth - 1] = message();
  840. }
  841. };
  842. C2DLogging._startFrameRender = function () {
  843. if (C2DLogging._logFramesCount === 0) {
  844. return;
  845. }
  846. C2DLogging.snooze = false;
  847. };
  848. C2DLogging._endFrameRender = function () {
  849. if (C2DLogging._logFramesCount === 0) {
  850. return;
  851. }
  852. C2DLogging.snooze = true;
  853. --C2DLogging._logFramesCount;
  854. };
  855. return C2DLogging;
  856. }());
  857. // Set to true to temporary disable logging.
  858. C2DLogging.snooze = true;
  859. C2DLogging._logFramesCount = 0;
  860. BABYLON.C2DLogging = C2DLogging;
  861. var C2DLoggingInternals = (function () {
  862. function C2DLoggingInternals() {
  863. }
  864. C2DLoggingInternals.computeIndent = function () {
  865. // Compute the indent
  866. var indent = null;
  867. if (C2DLoggingInternals.callDepth < 20) {
  868. indent = C2DLoggingInternals.depths[C2DLoggingInternals.callDepth];
  869. }
  870. else {
  871. indent = "|";
  872. for (var i = 0; i <= C2DLoggingInternals.callDepth; i++) {
  873. indent = indent + "-";
  874. }
  875. }
  876. return indent;
  877. };
  878. C2DLoggingInternals.getFormattedValue = function (a) {
  879. if (a instanceof BABYLON.Prim2DBase) {
  880. return a.id;
  881. }
  882. if (a == null) {
  883. return "[null]";
  884. }
  885. return a.toString();
  886. };
  887. return C2DLoggingInternals;
  888. }());
  889. //-------------FLAG TO CHANGE TO ENABLE/DISABLE LOGGING ACTIVATION--------------
  890. // This flag can't be changed at runtime you must manually change it in the code
  891. C2DLoggingInternals.enableLog = false;
  892. C2DLoggingInternals.callDepth = 0;
  893. C2DLoggingInternals.depths = [
  894. "|-", "|--", "|---", "|----", "|-----", "|------", "|-------", "|--------", "|---------", "|----------",
  895. "|-----------", "|------------", "|-------------", "|--------------", "|---------------", "|----------------", "|-----------------", "|------------------", "|-------------------", "|--------------------"
  896. ];
  897. C2DLoggingInternals.postMessages = [];
  898. function logProp(message, alsoGet, setNoProlog, getNoProlog) {
  899. if (message === void 0) { message = ""; }
  900. if (alsoGet === void 0) { alsoGet = false; }
  901. if (setNoProlog === void 0) { setNoProlog = false; }
  902. if (getNoProlog === void 0) { getNoProlog = false; }
  903. return function (target, propName, descriptor) {
  904. if (!C2DLoggingInternals.enableLog) {
  905. return descriptor;
  906. }
  907. var getter = descriptor.get, setter = descriptor.set;
  908. if (getter && alsoGet) {
  909. descriptor.get = function () {
  910. if (C2DLogging.snooze) {
  911. return getter.call(this);
  912. }
  913. else {
  914. var indent = C2DLoggingInternals.computeIndent();
  915. var id = this.id || "";
  916. if (message !== null && message !== "") {
  917. console.log(message);
  918. }
  919. var isSPP = this instanceof BABYLON.SmartPropertyPrim;
  920. var flags = isSPP ? this._flags : 0;
  921. var depth = C2DLoggingInternals.callDepth;
  922. if (!getNoProlog) {
  923. console.log(indent + " [" + id + "] (" + depth + ") ==> get " + propName + " property");
  924. }
  925. ++C2DLoggingInternals.callDepth;
  926. C2DLogging.setPostMessage(function () { return "[no msg]"; });
  927. // Call the initial getter
  928. var r = getter.call(this);
  929. --C2DLoggingInternals.callDepth;
  930. var flagsStr = "";
  931. if (isSPP) {
  932. var nflags = this._flags;
  933. var newFlags = this._getFlagsDebug((nflags & flags) ^ nflags);
  934. var removedFlags = this._getFlagsDebug((nflags & flags) ^ flags);
  935. flagsStr = "";
  936. if (newFlags !== "") {
  937. flagsStr = " +++[" + newFlags + "]";
  938. }
  939. if (removedFlags !== "") {
  940. if (flagsStr !== "") {
  941. flagsStr += ",";
  942. }
  943. flagsStr += " ---[" + removedFlags + "]";
  944. }
  945. }
  946. console.log(indent + " [" + id + "] (" + depth + ")" + (getNoProlog ? "" : " <==") + " get " + propName + " property => " + C2DLoggingInternals.getFormattedValue(r) + flagsStr + ", " + C2DLoggingInternals.postMessages[C2DLoggingInternals.callDepth]);
  947. return r;
  948. }
  949. };
  950. }
  951. // Overload the property setter implementation to add our own logic
  952. if (setter) {
  953. descriptor.set = function (val) {
  954. if (C2DLogging.snooze) {
  955. setter.call(this, val);
  956. }
  957. else {
  958. var indent = C2DLoggingInternals.computeIndent();
  959. var id = this.id || "";
  960. if (message !== null && message !== "") {
  961. console.log(message);
  962. }
  963. var isSPP = this instanceof BABYLON.SmartPropertyPrim;
  964. var flags = isSPP ? this._flags : 0;
  965. var depth = C2DLoggingInternals.callDepth;
  966. if (!setNoProlog) {
  967. console.log(indent + " [" + id + "] (" + depth + ") ==> set " + propName + " property with " + C2DLoggingInternals.getFormattedValue(val));
  968. }
  969. ++C2DLoggingInternals.callDepth;
  970. C2DLogging.setPostMessage(function () { return "[no msg]"; });
  971. // Change the value
  972. setter.call(this, val);
  973. --C2DLoggingInternals.callDepth;
  974. var flagsStr = "";
  975. if (isSPP) {
  976. var nflags = this._flags;
  977. var newFlags = this._getFlagsDebug((nflags & flags) ^ nflags);
  978. var removedFlags = this._getFlagsDebug((nflags & flags) ^ flags);
  979. flagsStr = "";
  980. if (newFlags !== "") {
  981. flagsStr = " +++[" + newFlags + "]";
  982. }
  983. if (removedFlags !== "") {
  984. if (flagsStr !== "") {
  985. flagsStr += ",";
  986. }
  987. flagsStr += " ---[" + removedFlags + "]";
  988. }
  989. }
  990. console.log(indent + " [" + id + "] (" + depth + ")" + (setNoProlog ? "" : " <==") + " set " + propName + " property, " + C2DLoggingInternals.postMessages[C2DLoggingInternals.callDepth] + flagsStr);
  991. }
  992. };
  993. }
  994. return descriptor;
  995. };
  996. }
  997. BABYLON.logProp = logProp;
  998. function logMethod(message, noProlog) {
  999. if (message === void 0) { message = ""; }
  1000. if (noProlog === void 0) { noProlog = false; }
  1001. return function (target, key, descriptor) {
  1002. if (!C2DLoggingInternals.enableLog) {
  1003. return descriptor;
  1004. }
  1005. if (descriptor === undefined) {
  1006. descriptor = Object.getOwnPropertyDescriptor(target, key);
  1007. }
  1008. var originalMethod = descriptor.value;
  1009. //editing the descriptor/value parameter
  1010. descriptor.value = function () {
  1011. var args = [];
  1012. for (var _i = 0; _i < arguments.length; _i++) {
  1013. args[_i - 0] = arguments[_i];
  1014. }
  1015. if (C2DLogging.snooze) {
  1016. return originalMethod.apply(this, args);
  1017. }
  1018. else {
  1019. var a = args.map(function (a) { return C2DLoggingInternals.getFormattedValue(a) + ", "; }).join();
  1020. a = a.slice(0, a.length - 2);
  1021. var indent = C2DLoggingInternals.computeIndent();
  1022. var id = this.id || "";
  1023. if (message !== null && message !== "") {
  1024. console.log(message);
  1025. }
  1026. var isSPP = this instanceof BABYLON.SmartPropertyPrim;
  1027. var flags = isSPP ? this._flags : 0;
  1028. var depth = C2DLoggingInternals.callDepth;
  1029. if (!noProlog) {
  1030. console.log(indent + " [" + id + "] (" + depth + ") ==> call: " + key + " (" + a + ")");
  1031. }
  1032. ++C2DLoggingInternals.callDepth;
  1033. C2DLogging.setPostMessage(function () { return "[no msg]"; });
  1034. // Call the method!
  1035. var result = originalMethod.apply(this, args);
  1036. --C2DLoggingInternals.callDepth;
  1037. var flagsStr = "";
  1038. if (isSPP) {
  1039. var nflags = this._flags;
  1040. var newFlags = this._getFlagsDebug((nflags & flags) ^ nflags);
  1041. var removedFlags = this._getFlagsDebug((nflags & flags) ^ flags);
  1042. flagsStr = "";
  1043. if (newFlags !== "") {
  1044. flagsStr = " +++[" + newFlags + "]";
  1045. }
  1046. if (removedFlags !== "") {
  1047. if (flagsStr !== "") {
  1048. flagsStr += ",";
  1049. }
  1050. flagsStr += " ---[" + removedFlags + "]";
  1051. }
  1052. }
  1053. console.log(indent + " [" + id + "] (" + depth + ")" + (noProlog ? "" : " <==") + " call: " + key + " (" + a + ") Res: " + C2DLoggingInternals.getFormattedValue(result) + ", " + C2DLoggingInternals.postMessages[C2DLoggingInternals.callDepth] + flagsStr);
  1054. return result;
  1055. }
  1056. };
  1057. // return edited descriptor as opposed to overwriting the descriptor
  1058. return descriptor;
  1059. };
  1060. }
  1061. BABYLON.logMethod = logMethod;
  1062. })(BABYLON || (BABYLON = {}));
  1063. //# sourceMappingURL=babylon.c2dlogging.js.map
  1064. var __extends = (this && this.__extends) || function (d, b) {
  1065. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1066. function __() { this.constructor = d; }
  1067. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1068. };
  1069. var BABYLON;
  1070. (function (BABYLON) {
  1071. /**
  1072. * Class for the ObservableArray.onArrayChanged observable
  1073. */
  1074. var ArrayChanged = (function () {
  1075. function ArrayChanged() {
  1076. this.action = 0;
  1077. this.newItems = new Array();
  1078. this.removedItems = new Array();
  1079. this.changedItems = new Array();
  1080. this.newStartingIndex = -1;
  1081. this.removedStartingIndex = -1;
  1082. }
  1083. Object.defineProperty(ArrayChanged, "clearAction", {
  1084. /**
  1085. * The content of the array was totally cleared
  1086. */
  1087. get: function () {
  1088. return ArrayChanged._clearAction;
  1089. },
  1090. enumerable: true,
  1091. configurable: true
  1092. });
  1093. Object.defineProperty(ArrayChanged, "newItemsAction", {
  1094. /**
  1095. * A new item was added, the newItems field contains the key/value pairs
  1096. */
  1097. get: function () {
  1098. return ArrayChanged._newItemsAction;
  1099. },
  1100. enumerable: true,
  1101. configurable: true
  1102. });
  1103. Object.defineProperty(ArrayChanged, "removedItemsAction", {
  1104. /**
  1105. * An existing item was removed, the removedKey field contains its key
  1106. */
  1107. get: function () {
  1108. return ArrayChanged._removedItemsAction;
  1109. },
  1110. enumerable: true,
  1111. configurable: true
  1112. });
  1113. Object.defineProperty(ArrayChanged, "changedItemAction", {
  1114. /**
  1115. * One or many items in the array were changed, the
  1116. */
  1117. get: function () {
  1118. return ArrayChanged._changedItemAction;
  1119. },
  1120. enumerable: true,
  1121. configurable: true
  1122. });
  1123. Object.defineProperty(ArrayChanged, "replacedArrayAction", {
  1124. /**
  1125. * The array's content was totally changed
  1126. * Depending on the method that used this mode the ChangedArray object may contains more information
  1127. */
  1128. get: function () {
  1129. return ArrayChanged._replacedArrayAction;
  1130. },
  1131. enumerable: true,
  1132. configurable: true
  1133. });
  1134. Object.defineProperty(ArrayChanged, "lengthChangedAction", {
  1135. /**
  1136. * The length of the array changed
  1137. */
  1138. get: function () {
  1139. return ArrayChanged._lengthChangedAction;
  1140. },
  1141. enumerable: true,
  1142. configurable: true
  1143. });
  1144. ArrayChanged.prototype.clear = function () {
  1145. this.action = 0;
  1146. this.newItems.splice(0);
  1147. this.removedItems.splice(0);
  1148. this.changedItems.splice(0);
  1149. this.removedStartingIndex = this.removedStartingIndex = this.changedStartingIndex = 0;
  1150. };
  1151. return ArrayChanged;
  1152. }());
  1153. ArrayChanged._clearAction = 0x1;
  1154. ArrayChanged._newItemsAction = 0x2;
  1155. ArrayChanged._removedItemsAction = 0x4;
  1156. ArrayChanged._replacedArrayAction = 0x8;
  1157. ArrayChanged._lengthChangedAction = 0x10;
  1158. ArrayChanged._changedItemAction = 0x20;
  1159. BABYLON.ArrayChanged = ArrayChanged;
  1160. var OAWatchedObjectChangedInfo = (function () {
  1161. function OAWatchedObjectChangedInfo() {
  1162. }
  1163. return OAWatchedObjectChangedInfo;
  1164. }());
  1165. BABYLON.OAWatchedObjectChangedInfo = OAWatchedObjectChangedInfo;
  1166. /**
  1167. * This class mimics the Javascript Array and TypeScript Array<T> classes, adding new features concerning the Observable pattern.
  1168. *
  1169. */
  1170. var ObservableArray = (function (_super) {
  1171. __extends(ObservableArray, _super);
  1172. /**
  1173. * Create an Observable Array.
  1174. * @param watchObjectsPropertyChange
  1175. * @param array and optional array that will be encapsulated by this ObservableArray instance. That's right, it's NOT a copy!
  1176. */
  1177. function ObservableArray(watchObjectsPropertyChange, array) {
  1178. var _this = _super.call(this) || this;
  1179. _this.dci = new ArrayChanged();
  1180. _this._callingArrayChanged = false;
  1181. _this._array = (array != null) ? array : new Array();
  1182. _this.dci = new ArrayChanged();
  1183. _this._callingArrayChanged = false;
  1184. _this._arrayChanged = null;
  1185. _this._callingWatchedObjectChanged = false;
  1186. _this._watchObjectsPropertyChange = watchObjectsPropertyChange;
  1187. _this._watchedObjectList = _this._watchObjectsPropertyChange ? new BABYLON.StringDictionary() : null;
  1188. _this._woci = new OAWatchedObjectChangedInfo();
  1189. return _this;
  1190. }
  1191. Object.defineProperty(ObservableArray.prototype, "length", {
  1192. /**
  1193. * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.
  1194. */
  1195. get: function () {
  1196. return this._array.length;
  1197. },
  1198. set: function (value) {
  1199. if (value === this._array.length) {
  1200. return;
  1201. }
  1202. var oldLength = this._array.length;
  1203. this._array.length = value;
  1204. this.onPropertyChanged("length", oldLength, this._array.length);
  1205. },
  1206. enumerable: true,
  1207. configurable: true
  1208. });
  1209. ObservableArray.prototype.getAt = function (index) {
  1210. return this._array[index];
  1211. };
  1212. ObservableArray.prototype.setAt = function (index, value) {
  1213. if (index < 0) {
  1214. return false;
  1215. }
  1216. var insertion = (index >= this._array.length) || this._array[index] === undefined;
  1217. var oldLength = 0;
  1218. if (insertion) {
  1219. oldLength = this._array.length;
  1220. }
  1221. else if (this._watchObjectsPropertyChange) {
  1222. this._removeWatchedElement(this._array[index]);
  1223. }
  1224. this._array[index] = value;
  1225. if (this._watchObjectsPropertyChange) {
  1226. this._addWatchedElement(value);
  1227. }
  1228. if (insertion) {
  1229. this.onPropertyChanged("length", oldLength, this._array.length);
  1230. }
  1231. var ac = this.getArrayChangedObject();
  1232. if (ac) {
  1233. ac.action = insertion ? ArrayChanged.newItemsAction : ArrayChanged.changedItemAction;
  1234. if (insertion) {
  1235. ac.newItems.splice(0, ac.newItems.length, { index: index, value: value });
  1236. ac.newStartingIndex = index;
  1237. ac.changedItems.splice(0);
  1238. }
  1239. else {
  1240. ac.newItems.splice(0);
  1241. ac.changedStartingIndex = index;
  1242. ac.changedItems.splice(0, ac.changedItems.length, { index: index, value: value });
  1243. }
  1244. ac.removedItems.splice(0);
  1245. ac.removedStartingIndex = -1;
  1246. this.callArrayChanged(ac);
  1247. }
  1248. };
  1249. /**
  1250. * Returns a string representation of an array.
  1251. */
  1252. ObservableArray.prototype.toString = function () {
  1253. return this._array.toString();
  1254. };
  1255. ObservableArray.prototype.toLocaleString = function () {
  1256. return this._array.toLocaleString();
  1257. };
  1258. /**
  1259. * Appends new elements to an array, and returns the new length of the array.
  1260. * @param items New elements of the Array.
  1261. */
  1262. ObservableArray.prototype.push = function () {
  1263. var items = [];
  1264. for (var _i = 0; _i < arguments.length; _i++) {
  1265. items[_i] = arguments[_i];
  1266. }
  1267. var oldLength = this._array.length;
  1268. var n = (_a = this._array).push.apply(_a, items);
  1269. if (this._watchObjectsPropertyChange) {
  1270. this._addWatchedElement.apply(this, items);
  1271. }
  1272. this.onPropertyChanged("length", oldLength, this._array.length);
  1273. var ac = this.getArrayChangedObject();
  1274. if (ac) {
  1275. ac.action = ArrayChanged.newItemsAction;
  1276. ac.newStartingIndex = oldLength;
  1277. this.feedNotifArray.apply(this, [ac.newItems, oldLength].concat(items));
  1278. this.callArrayChanged(ac);
  1279. }
  1280. return n;
  1281. var _a;
  1282. };
  1283. /**
  1284. * Removes the last element from an array and returns it.
  1285. */
  1286. ObservableArray.prototype.pop = function () {
  1287. var firstRemove = this._array.length - 1;
  1288. var res = this._array.pop();
  1289. if (res && this._watchObjectsPropertyChange) {
  1290. this._removeWatchedElement(res);
  1291. }
  1292. if (firstRemove !== -1) {
  1293. this.onPropertyChanged("length", this._array.length + 1, this._array.length);
  1294. var ac = this.getArrayChangedObject();
  1295. if (ac) {
  1296. ac.action = ArrayChanged.removedItemsAction;
  1297. ac.removedStartingIndex = firstRemove;
  1298. this.feedNotifArray(ac.removedItems, firstRemove, res);
  1299. }
  1300. }
  1301. return res;
  1302. };
  1303. /**
  1304. * Combines two or more arrays.
  1305. * @param items Additional items to add to the end of array1.
  1306. */
  1307. ObservableArray.prototype.concat = function () {
  1308. var items = [];
  1309. for (var _i = 0; _i < arguments.length; _i++) {
  1310. items[_i] = arguments[_i];
  1311. }
  1312. return new ObservableArray(this._watchObjectsPropertyChange, (_a = this._array).concat.apply(_a, items));
  1313. var _a;
  1314. };
  1315. /**
  1316. * Adds all the elements of an array separated by the specified separator string.
  1317. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.
  1318. */
  1319. ObservableArray.prototype.join = function (separator) {
  1320. return this._array.join(separator);
  1321. };
  1322. /**
  1323. * Reverses the elements in an Array.
  1324. * The arrayChanged action is
  1325. */
  1326. ObservableArray.prototype.reverse = function () {
  1327. var res = this._array.reverse();
  1328. var ac = this.getArrayChangedObject();
  1329. ac.action = ArrayChanged.replacedArrayAction;
  1330. return res;
  1331. };
  1332. /**
  1333. * Removes the first element from an array and returns it, shift all subsequents element one element before.
  1334. * The ArrayChange action is replacedArrayAction, the whole array changes and must be reevaluate as such, the removed element is in removedItems.
  1335. *
  1336. */
  1337. ObservableArray.prototype.shift = function () {
  1338. var oldLength = this._array.length;
  1339. var res = this._array.shift();
  1340. if (this._watchedObjectChanged && res != null) {
  1341. this._removeWatchedElement(res);
  1342. }
  1343. if (oldLength !== 0) {
  1344. this.onPropertyChanged("length", oldLength, this._array.length);
  1345. var ac = this.getArrayChangedObject();
  1346. if (ac) {
  1347. ac.action = ArrayChanged.replacedArrayAction;
  1348. ac.removedItems.splice(0, ac.removedItems.length, { index: 0, value: res });
  1349. ac.newItems.splice(0);
  1350. ac.changedItems.splice(0);
  1351. ac.removedStartingIndex = 0;
  1352. this.callArrayChanged(ac);
  1353. }
  1354. }
  1355. return res;
  1356. };
  1357. /**
  1358. * Returns a section of an array.
  1359. * @param start The beginning of the specified portion of the array.
  1360. * @param end The end of the specified portion of the array.
  1361. */
  1362. ObservableArray.prototype.slice = function (start, end) {
  1363. return new ObservableArray(this._watchObjectsPropertyChange, this._array.slice(start, end));
  1364. };
  1365. /**
  1366. * Sorts an array.
  1367. * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order.
  1368. * On the contrary of the Javascript Array's implementation, this method returns nothing
  1369. */
  1370. ObservableArray.prototype.sort = function (compareFn) {
  1371. var oldLength = this._array.length;
  1372. this._array.sort(compareFn);
  1373. if (oldLength !== 0) {
  1374. var ac = this.getArrayChangedObject();
  1375. if (ac) {
  1376. ac.clear();
  1377. ac.action = ArrayChanged.replacedArrayAction;
  1378. this.callArrayChanged(ac);
  1379. }
  1380. }
  1381. };
  1382. /**
  1383. * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
  1384. * @param start The zero-based location in the array from which to start removing elements.
  1385. * @param deleteCount The number of elements to remove.
  1386. * @param items Elements to insert into the array in place of the deleted elements.
  1387. */
  1388. ObservableArray.prototype.splice = function (start, deleteCount) {
  1389. var items = [];
  1390. for (var _i = 2; _i < arguments.length; _i++) {
  1391. items[_i - 2] = arguments[_i];
  1392. }
  1393. var oldLength = this._array.length;
  1394. if (this._watchObjectsPropertyChange) {
  1395. for (var i = start; i < start + deleteCount; i++) {
  1396. var val = this._array[i];
  1397. if (this._watchObjectsPropertyChange && val != null) {
  1398. this._removeWatchedElement(val);
  1399. }
  1400. }
  1401. }
  1402. var res = (_a = this._array).splice.apply(_a, [start, deleteCount].concat(items));
  1403. if (this._watchObjectsPropertyChange) {
  1404. this._addWatchedElement.apply(this, items);
  1405. }
  1406. if (oldLength !== this._array.length) {
  1407. this.onPropertyChanged("length", oldLength, this._array.length);
  1408. }
  1409. var ac = this.getArrayChangedObject();
  1410. if (ac) {
  1411. ac.clear();
  1412. ac.action = ArrayChanged.replacedArrayAction;
  1413. this.callArrayChanged(ac);
  1414. }
  1415. return res;
  1416. var _a;
  1417. };
  1418. /**
  1419. * Inserts new elements at the start of an array.
  1420. * @param items Elements to insert at the start of the Array.
  1421. * The ChangedArray action is replacedArrayAction, newItems contains the list of the added items
  1422. */
  1423. ObservableArray.prototype.unshift = function () {
  1424. var items = [];
  1425. for (var _i = 0; _i < arguments.length; _i++) {
  1426. items[_i] = arguments[_i];
  1427. }
  1428. var oldLength = this._array.length;
  1429. var res = (_a = this._array).unshift.apply(_a, items);
  1430. if (this._watchObjectsPropertyChange) {
  1431. this._addWatchedElement.apply(this, items);
  1432. }
  1433. this.onPropertyChanged("length", oldLength, this._array.length);
  1434. var ac = this.getArrayChangedObject();
  1435. if (ac) {
  1436. ac.clear();
  1437. ac.action = ArrayChanged.replacedArrayAction;
  1438. ac.newStartingIndex = 0, this.feedNotifArray.apply(this, [ac.newItems, 0].concat(items));
  1439. this.callArrayChanged(ac);
  1440. }
  1441. return res;
  1442. var _a;
  1443. };
  1444. /**
  1445. * Returns the index of the first occurrence of a value in an array.
  1446. * @param searchElement The value to locate in the array.
  1447. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
  1448. */
  1449. ObservableArray.prototype.indexOf = function (searchElement, fromIndex) {
  1450. return this._array.indexOf(searchElement, fromIndex);
  1451. };
  1452. /**
  1453. * Returns the index of the last occurrence of a specified value in an array.
  1454. * @param searchElement The value to locate in the array.
  1455. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.
  1456. */
  1457. ObservableArray.prototype.lastIndexOf = function (searchElement, fromIndex) {
  1458. return this._array.lastIndexOf(searchElement, fromIndex);
  1459. };
  1460. /**
  1461. * Determines whether all the members of an array satisfy the specified test.
  1462. * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array.
  1463. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
  1464. */
  1465. ObservableArray.prototype.every = function (callbackfn, thisArg) {
  1466. return this._array.every(callbackfn, thisArg);
  1467. };
  1468. /**
  1469. * Determines whether the specified callback function returns true for any element of an array.
  1470. * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array.
  1471. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
  1472. */
  1473. ObservableArray.prototype.some = function (callbackfn, thisArg) {
  1474. return this._array.some(callbackfn, thisArg);
  1475. };
  1476. /**
  1477. * Performs the specified action for each element in an array.
  1478. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
  1479. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
  1480. */
  1481. ObservableArray.prototype.forEach = function (callbackfn, thisArg) {
  1482. return this._array.forEach(callbackfn, thisArg);
  1483. };
  1484. /**
  1485. * Calls a defined callback function on each element of an array, and returns an array that contains the results.
  1486. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
  1487. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
  1488. */
  1489. ObservableArray.prototype.map = function (callbackfn, thisArg) {
  1490. return this._array.map(callbackfn, thisArg);
  1491. };
  1492. /**
  1493. * Returns the elements of an array that meet the condition specified in a callback function.
  1494. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
  1495. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
  1496. */
  1497. ObservableArray.prototype.filter = function (callbackfn, thisArg) {
  1498. return this._array.filter(callbackfn, thisArg);
  1499. };
  1500. /**
  1501. * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
  1502. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
  1503. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
  1504. */
  1505. ObservableArray.prototype.reduce = function (callbackfn, initialValue) {
  1506. return this._array.reduce(callbackfn);
  1507. };
  1508. /**
  1509. * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
  1510. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
  1511. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
  1512. */
  1513. ObservableArray.prototype.reduceRight = function (callbackfn, initialValue) {
  1514. return this._array.reduceRight(callbackfn);
  1515. };
  1516. Object.defineProperty(ObservableArray.prototype, "arrayChanged", {
  1517. get: function () {
  1518. if (!this._arrayChanged) {
  1519. this._arrayChanged = new BABYLON.Observable();
  1520. }
  1521. return this._arrayChanged;
  1522. },
  1523. enumerable: true,
  1524. configurable: true
  1525. });
  1526. ObservableArray.prototype.getArrayChangedObject = function () {
  1527. if (this._arrayChanged && this._arrayChanged.hasObservers()) {
  1528. var ac = this._callingArrayChanged ? new ArrayChanged() : this.dci;
  1529. return ac;
  1530. }
  1531. return null;
  1532. };
  1533. ObservableArray.prototype.feedNotifArray = function (array, startindIndex) {
  1534. var items = [];
  1535. for (var _i = 2; _i < arguments.length; _i++) {
  1536. items[_i - 2] = arguments[_i];
  1537. }
  1538. array.splice(0);
  1539. for (var i = 0; i < items.length; i++) {
  1540. var value = this._array[i + startindIndex];
  1541. if (value !== undefined) {
  1542. array.push({ index: i + startindIndex, value: value });
  1543. }
  1544. }
  1545. };
  1546. ObservableArray.prototype.callArrayChanged = function (ac) {
  1547. try {
  1548. this._callingArrayChanged = true;
  1549. this.arrayChanged.notifyObservers(ac, ac.action);
  1550. }
  1551. finally {
  1552. this._callingArrayChanged = false;
  1553. }
  1554. };
  1555. Object.defineProperty(ObservableArray.prototype, "watchedObjectChanged", {
  1556. get: function () {
  1557. if (!this._watchedObjectChanged) {
  1558. this._watchedObjectChanged = new BABYLON.Observable();
  1559. }
  1560. return this._watchedObjectChanged;
  1561. },
  1562. enumerable: true,
  1563. configurable: true
  1564. });
  1565. ObservableArray.prototype._addWatchedElement = function () {
  1566. var _this = this;
  1567. var items = [];
  1568. for (var _i = 0; _i < arguments.length; _i++) {
  1569. items[_i] = arguments[_i];
  1570. }
  1571. var _loop_1 = function (curItem) {
  1572. if (curItem["propertyChanged"]) {
  1573. var key_1 = curItem["__ObsArrayObjID__"];
  1574. // The object may already be part of another ObsArray, so there already be a valid ID
  1575. if (!key_1) {
  1576. key_1 = BABYLON.Tools.RandomId();
  1577. curItem["__ObsArrayObjID__"] = key_1;
  1578. }
  1579. this_1._watchedObjectList.add(key_1, curItem.propertyChanged.add(function (e, d) {
  1580. _this.onWatchedObjectChanged(key_1, curItem, e);
  1581. }));
  1582. }
  1583. };
  1584. var this_1 = this;
  1585. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  1586. var curItem = items_1[_a];
  1587. _loop_1(curItem);
  1588. }
  1589. };
  1590. ObservableArray.prototype._removeWatchedElement = function () {
  1591. var items = [];
  1592. for (var _i = 0; _i < arguments.length; _i++) {
  1593. items[_i] = arguments[_i];
  1594. }
  1595. for (var _a = 0, items_2 = items; _a < items_2.length; _a++) {
  1596. var curItem = items_2[_a];
  1597. var key = curItem["__ObsArrayObjID__"];
  1598. if (key != null) {
  1599. var observer = this._watchedObjectList.getAndRemove(key);
  1600. curItem.propertyChanged.remove(observer);
  1601. }
  1602. }
  1603. };
  1604. ObservableArray.prototype.onWatchedObjectChanged = function (key, object, propChanged) {
  1605. if (this._watchedObjectChanged && this._watchedObjectChanged.hasObservers()) {
  1606. var woci = this._callingWatchedObjectChanged ? new OAWatchedObjectChangedInfo() : this._woci;
  1607. woci.object = object;
  1608. woci.propertyChanged = propChanged;
  1609. try {
  1610. this._callingWatchedObjectChanged = true;
  1611. this.watchedObjectChanged.notifyObservers(woci);
  1612. }
  1613. finally {
  1614. this._callingWatchedObjectChanged = false;
  1615. }
  1616. }
  1617. };
  1618. return ObservableArray;
  1619. }(BABYLON.PropertyChangedBase));
  1620. BABYLON.ObservableArray = ObservableArray;
  1621. })(BABYLON || (BABYLON = {}));
  1622. //# sourceMappingURL=babylon.observableArray.js.map
  1623. var __extends = (this && this.__extends) || function (d, b) {
  1624. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1625. function __() { this.constructor = d; }
  1626. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1627. };
  1628. var BABYLON;
  1629. (function (BABYLON) {
  1630. /**
  1631. * Class for the ObservableStringDictionary.onDictionaryChanged observable
  1632. */
  1633. var DictionaryChanged = (function () {
  1634. function DictionaryChanged() {
  1635. }
  1636. Object.defineProperty(DictionaryChanged, "clearAction", {
  1637. /**
  1638. * The content of the dictionary was totally cleared
  1639. */
  1640. get: function () {
  1641. return DictionaryChanged._clearAction;
  1642. },
  1643. enumerable: true,
  1644. configurable: true
  1645. });
  1646. Object.defineProperty(DictionaryChanged, "newItemAction", {
  1647. /**
  1648. * A new item was added, the newItem field contains the key/value pair
  1649. */
  1650. get: function () {
  1651. return DictionaryChanged._newItemAction;
  1652. },
  1653. enumerable: true,
  1654. configurable: true
  1655. });
  1656. Object.defineProperty(DictionaryChanged, "removedItemAction", {
  1657. /**
  1658. * An existing item was removed, the removedKey field contains its key
  1659. */
  1660. get: function () {
  1661. return DictionaryChanged._removedItemAction;
  1662. },
  1663. enumerable: true,
  1664. configurable: true
  1665. });
  1666. Object.defineProperty(DictionaryChanged, "itemValueChangedAction", {
  1667. /**
  1668. * An existing item had a value change, the changedItem field contains the key/value
  1669. */
  1670. get: function () {
  1671. return DictionaryChanged._itemValueChangedAction;
  1672. },
  1673. enumerable: true,
  1674. configurable: true
  1675. });
  1676. Object.defineProperty(DictionaryChanged, "replacedAction", {
  1677. /**
  1678. * The dictionary's content was reset and replaced by the content of another dictionary.
  1679. * DictionaryChanged<T> contains no further information about this action
  1680. */
  1681. get: function () {
  1682. return DictionaryChanged._replacedAction;
  1683. },
  1684. enumerable: true,
  1685. configurable: true
  1686. });
  1687. return DictionaryChanged;
  1688. }());
  1689. DictionaryChanged._clearAction = 0x1;
  1690. DictionaryChanged._newItemAction = 0x2;
  1691. DictionaryChanged._removedItemAction = 0x4;
  1692. DictionaryChanged._itemValueChangedAction = 0x8;
  1693. DictionaryChanged._replacedAction = 0x10;
  1694. BABYLON.DictionaryChanged = DictionaryChanged;
  1695. var OSDWatchedObjectChangedInfo = (function () {
  1696. function OSDWatchedObjectChangedInfo() {
  1697. }
  1698. return OSDWatchedObjectChangedInfo;
  1699. }());
  1700. BABYLON.OSDWatchedObjectChangedInfo = OSDWatchedObjectChangedInfo;
  1701. var ObservableStringDictionary = (function (_super) {
  1702. __extends(ObservableStringDictionary, _super);
  1703. function ObservableStringDictionary(watchObjectsPropertyChange) {
  1704. var _this = _super.call(this) || this;
  1705. _this._propertyChanged = null;
  1706. _this._dictionaryChanged = null;
  1707. _this.dci = new DictionaryChanged();
  1708. _this._callingDicChanged = false;
  1709. _this._watchedObjectChanged = null;
  1710. _this._callingWatchedObjectChanged = false;
  1711. _this._woci = new OSDWatchedObjectChangedInfo();
  1712. _this._watchObjectsPropertyChange = watchObjectsPropertyChange;
  1713. _this._watchedObjectList = _this._watchObjectsPropertyChange ? new BABYLON.StringDictionary() : null;
  1714. return _this;
  1715. }
  1716. /**
  1717. * This will clear this dictionary and copy the content from the 'source' one.
  1718. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  1719. * @param source the dictionary to take the content from and copy to this dictionary
  1720. */
  1721. ObservableStringDictionary.prototype.copyFrom = function (source) {
  1722. var _this = this;
  1723. var oldCount = this.count;
  1724. // Don't rely on this class' implementation for clear/add otherwise tons of notification will be thrown
  1725. _super.prototype.clear.call(this);
  1726. source.forEach(function (t, v) { return _this._add(t, v, false, _this._watchObjectsPropertyChange); });
  1727. this.onDictionaryChanged(DictionaryChanged.replacedAction, null, null, null);
  1728. this.onPropertyChanged("count", oldCount, this.count);
  1729. };
  1730. /**
  1731. * Get a value from its key or add it if it doesn't exist.
  1732. * This method will ensure you that a given key/data will be present in the dictionary.
  1733. * @param key the given key to get the matching value from
  1734. * @param factory the factory that will create the value if the key is not present in the dictionary.
  1735. * The factory will only be invoked if there's no data for the given key.
  1736. * @return the value corresponding to the key.
  1737. */
  1738. ObservableStringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  1739. var _this = this;
  1740. var val = _super.prototype.getOrAddWithFactory.call(this, key, function (k) {
  1741. var v = factory(key);
  1742. _this._add(key, v, true, _this._watchObjectsPropertyChange);
  1743. return v;
  1744. });
  1745. return val;
  1746. };
  1747. /**
  1748. * Add a new key and its corresponding value
  1749. * @param key the key to add
  1750. * @param value the value corresponding to the key
  1751. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  1752. */
  1753. ObservableStringDictionary.prototype.add = function (key, value) {
  1754. return this._add(key, value, true, this._watchObjectsPropertyChange);
  1755. };
  1756. ObservableStringDictionary.prototype.getAndRemove = function (key) {
  1757. var val = _super.prototype.get.call(this, key);
  1758. this._remove(key, true, val);
  1759. return val;
  1760. };
  1761. ObservableStringDictionary.prototype._add = function (key, value, fireNotif, registerWatcher) {
  1762. if (_super.prototype.add.call(this, key, value)) {
  1763. if (fireNotif) {
  1764. this.onDictionaryChanged(DictionaryChanged.newItemAction, { key: key, value: value }, null, null);
  1765. this.onPropertyChanged("count", this.count - 1, this.count);
  1766. }
  1767. if (registerWatcher) {
  1768. this._addWatchedElement(key, value);
  1769. }
  1770. return true;
  1771. }
  1772. return false;
  1773. };
  1774. ObservableStringDictionary.prototype._addWatchedElement = function (key, el) {
  1775. var _this = this;
  1776. if (el["propertyChanged"]) {
  1777. this._watchedObjectList.add(key, el.propertyChanged.add(function (e, d) {
  1778. _this.onWatchedObjectChanged(key, el, e);
  1779. }));
  1780. }
  1781. };
  1782. ObservableStringDictionary.prototype._removeWatchedElement = function (key, el) {
  1783. var observer = this._watchedObjectList.getAndRemove(key);
  1784. if (el["propertyChanged"]) {
  1785. el.propertyChanged.remove(observer);
  1786. }
  1787. };
  1788. ObservableStringDictionary.prototype.set = function (key, value) {
  1789. var oldValue = this.get(key);
  1790. if (this._watchObjectsPropertyChange) {
  1791. this._removeWatchedElement(key, oldValue);
  1792. }
  1793. if (_super.prototype.set.call(this, key, value)) {
  1794. this.onDictionaryChanged(DictionaryChanged.itemValueChangedAction, null, null, { key: key, oldValue: oldValue, newValue: value });
  1795. this._addWatchedElement(key, value);
  1796. return true;
  1797. }
  1798. return false;
  1799. };
  1800. /**
  1801. * Remove a key/value from the dictionary.
  1802. * @param key the key to remove
  1803. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  1804. */
  1805. ObservableStringDictionary.prototype.remove = function (key) {
  1806. return this._remove(key, true);
  1807. };
  1808. ObservableStringDictionary.prototype._remove = function (key, fireNotif, element) {
  1809. if (!element) {
  1810. element = this.get(key);
  1811. }
  1812. if (!element) {
  1813. return false;
  1814. }
  1815. if (_super.prototype.remove.call(this, key) === undefined) {
  1816. return false;
  1817. }
  1818. this.onDictionaryChanged(DictionaryChanged.removedItemAction, null, key, null);
  1819. this.onPropertyChanged("count", this.count + 1, this.count);
  1820. if (this._watchObjectsPropertyChange) {
  1821. this._removeWatchedElement(key, element);
  1822. }
  1823. return true;
  1824. };
  1825. /**
  1826. * Clear the whole content of the dictionary
  1827. */
  1828. ObservableStringDictionary.prototype.clear = function () {
  1829. var _this = this;
  1830. if (this._watchedObjectList) {
  1831. this._watchedObjectList.forEach(function (k, v) {
  1832. var el = _this.get(k);
  1833. _this._removeWatchedElement(k, el);
  1834. });
  1835. this._watchedObjectList.clear();
  1836. }
  1837. var oldCount = this.count;
  1838. _super.prototype.clear.call(this);
  1839. this.onDictionaryChanged(DictionaryChanged.clearAction, null, null, null);
  1840. this.onPropertyChanged("count", oldCount, 0);
  1841. };
  1842. Object.defineProperty(ObservableStringDictionary.prototype, "propertyChanged", {
  1843. get: function () {
  1844. if (!this._propertyChanged) {
  1845. this._propertyChanged = new BABYLON.Observable();
  1846. }
  1847. return this._propertyChanged;
  1848. },
  1849. enumerable: true,
  1850. configurable: true
  1851. });
  1852. ObservableStringDictionary.prototype.onPropertyChanged = function (propName, oldValue, newValue, mask) {
  1853. if (this._propertyChanged && this._propertyChanged.hasObservers()) {
  1854. var pci = ObservableStringDictionary.callingPropChanged ? new BABYLON.PropertyChangedInfo() : ObservableStringDictionary.pci;
  1855. pci.oldValue = oldValue;
  1856. pci.newValue = newValue;
  1857. pci.propertyName = propName;
  1858. try {
  1859. ObservableStringDictionary.callingPropChanged = true;
  1860. this.propertyChanged.notifyObservers(pci, mask);
  1861. }
  1862. finally {
  1863. ObservableStringDictionary.callingPropChanged = false;
  1864. }
  1865. }
  1866. };
  1867. Object.defineProperty(ObservableStringDictionary.prototype, "dictionaryChanged", {
  1868. get: function () {
  1869. if (!this._dictionaryChanged) {
  1870. this._dictionaryChanged = new BABYLON.Observable();
  1871. }
  1872. return this._dictionaryChanged;
  1873. },
  1874. enumerable: true,
  1875. configurable: true
  1876. });
  1877. ObservableStringDictionary.prototype.onDictionaryChanged = function (action, newItem, removedKey, changedItem) {
  1878. if (this._dictionaryChanged && this._dictionaryChanged.hasObservers()) {
  1879. var dci = this._callingDicChanged ? new DictionaryChanged() : this.dci;
  1880. dci.action = action;
  1881. dci.newItem = newItem;
  1882. dci.removedKey = removedKey;
  1883. dci.changedItem = changedItem;
  1884. try {
  1885. this._callingDicChanged = true;
  1886. this.dictionaryChanged.notifyObservers(dci, action);
  1887. }
  1888. finally {
  1889. this._callingDicChanged = false;
  1890. }
  1891. }
  1892. };
  1893. Object.defineProperty(ObservableStringDictionary.prototype, "watchedObjectChanged", {
  1894. get: function () {
  1895. if (!this._watchedObjectChanged) {
  1896. this._watchedObjectChanged = new BABYLON.Observable();
  1897. }
  1898. return this._watchedObjectChanged;
  1899. },
  1900. enumerable: true,
  1901. configurable: true
  1902. });
  1903. ObservableStringDictionary.prototype.onWatchedObjectChanged = function (key, object, propChanged) {
  1904. if (this._watchedObjectChanged && this._watchedObjectChanged.hasObservers()) {
  1905. var woci = this._callingWatchedObjectChanged ? new OSDWatchedObjectChangedInfo() : this._woci;
  1906. woci.key = key;
  1907. woci.object = object;
  1908. woci.propertyChanged = propChanged;
  1909. try {
  1910. this._callingWatchedObjectChanged = true;
  1911. this.watchedObjectChanged.notifyObservers(woci);
  1912. }
  1913. finally {
  1914. this._callingWatchedObjectChanged = false;
  1915. }
  1916. }
  1917. };
  1918. return ObservableStringDictionary;
  1919. }(BABYLON.StringDictionary));
  1920. ObservableStringDictionary.pci = new BABYLON.PropertyChangedInfo();
  1921. ObservableStringDictionary.callingPropChanged = false;
  1922. BABYLON.ObservableStringDictionary = ObservableStringDictionary;
  1923. })(BABYLON || (BABYLON = {}));
  1924. //# sourceMappingURL=babylon.observableStringDictionary.js.map
  1925. var __extends = (this && this.__extends) || function (d, b) {
  1926. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1927. function __() { this.constructor = d; }
  1928. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1929. };
  1930. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  1931. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  1932. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  1933. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  1934. return c > 3 && r && Object.defineProperty(target, key, r), r;
  1935. };
  1936. var BABYLON;
  1937. (function (BABYLON) {
  1938. /**
  1939. * This class given information about a given character.
  1940. */
  1941. var CharInfo = (function () {
  1942. function CharInfo() {
  1943. }
  1944. return CharInfo;
  1945. }());
  1946. BABYLON.CharInfo = CharInfo;
  1947. /**
  1948. * This is an abstract base class to hold a Texture that will contain a FontMap
  1949. */
  1950. var BaseFontTexture = (function (_super) {
  1951. __extends(BaseFontTexture, _super);
  1952. function BaseFontTexture(url, scene, noMipmap, invertY, samplingMode, premultipliedAlpha) {
  1953. if (noMipmap === void 0) { noMipmap = false; }
  1954. if (invertY === void 0) { invertY = true; }
  1955. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  1956. if (premultipliedAlpha === void 0) { premultipliedAlpha = false; }
  1957. var _this = _super.call(this, url, scene, noMipmap, invertY, samplingMode) || this;
  1958. _this._cachedFontId = null;
  1959. _this._charInfos = new BABYLON.StringDictionary();
  1960. _this._isPremultipliedAlpha = premultipliedAlpha;
  1961. return _this;
  1962. }
  1963. Object.defineProperty(BaseFontTexture.prototype, "isSuperSampled", {
  1964. /**
  1965. * Is the Font is using Super Sampling (each font texel is doubled).
  1966. */
  1967. get: function () {
  1968. return this._superSample;
  1969. },
  1970. enumerable: true,
  1971. configurable: true
  1972. });
  1973. Object.defineProperty(BaseFontTexture.prototype, "isSignedDistanceField", {
  1974. /**
  1975. * Is the Font was rendered using the Signed Distance Field algorithm
  1976. * @returns {}
  1977. */
  1978. get: function () {
  1979. return this._signedDistanceField;
  1980. },
  1981. enumerable: true,
  1982. configurable: true
  1983. });
  1984. Object.defineProperty(BaseFontTexture.prototype, "isPremultipliedAlpha", {
  1985. /**
  1986. * True if the font was drawn using multiplied alpha
  1987. */
  1988. get: function () {
  1989. return this._isPremultipliedAlpha;
  1990. },
  1991. enumerable: true,
  1992. configurable: true
  1993. });
  1994. Object.defineProperty(BaseFontTexture.prototype, "spaceWidth", {
  1995. /**
  1996. * Get the Width (in pixel) of the Space character
  1997. */
  1998. get: function () {
  1999. return this._spaceWidth;
  2000. },
  2001. enumerable: true,
  2002. configurable: true
  2003. });
  2004. Object.defineProperty(BaseFontTexture.prototype, "lineHeight", {
  2005. /**
  2006. * Get the Line height (in pixel)
  2007. */
  2008. get: function () {
  2009. return this._lineHeight;
  2010. },
  2011. enumerable: true,
  2012. configurable: true
  2013. });
  2014. /**
  2015. * Measure the width/height that will take a given text
  2016. * @param text the text to measure
  2017. * @param tabulationSize the size (in space character) of the tabulation character, default value must be 4
  2018. */
  2019. BaseFontTexture.prototype.measureText = function (text, tabulationSize) {
  2020. var maxWidth = 0;
  2021. var curWidth = 0;
  2022. var lineCount = 1;
  2023. var charxpos = 0;
  2024. // Parse each char of the string
  2025. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  2026. var char = text_1[_i];
  2027. // Next line feed?
  2028. if (char === "\n") {
  2029. maxWidth = Math.max(maxWidth, curWidth);
  2030. charxpos = 0;
  2031. curWidth = 0;
  2032. ++lineCount;
  2033. continue;
  2034. }
  2035. // Tabulation ?
  2036. if (char === "\t") {
  2037. var nextPos = charxpos + tabulationSize;
  2038. nextPos = nextPos - (nextPos % tabulationSize);
  2039. curWidth += (nextPos - charxpos) * this.spaceWidth;
  2040. charxpos = nextPos;
  2041. continue;
  2042. }
  2043. if (char < " ") {
  2044. continue;
  2045. }
  2046. var ci = this.getChar(char);
  2047. if (!ci) {
  2048. throw new Error("Character " + char + " is not supported by FontTexture " + this.name);
  2049. }
  2050. curWidth += ci.charWidth;
  2051. ++charxpos;
  2052. }
  2053. maxWidth = Math.max(maxWidth, curWidth);
  2054. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  2055. };
  2056. return BaseFontTexture;
  2057. }(BABYLON.Texture));
  2058. BABYLON.BaseFontTexture = BaseFontTexture;
  2059. var BitmapFontInfo = (function () {
  2060. function BitmapFontInfo() {
  2061. this.kerningDic = new BABYLON.StringDictionary();
  2062. this.charDic = new BABYLON.StringDictionary();
  2063. }
  2064. return BitmapFontInfo;
  2065. }());
  2066. BABYLON.BitmapFontInfo = BitmapFontInfo;
  2067. var BitmapFontTexture = (function (_super) {
  2068. __extends(BitmapFontTexture, _super);
  2069. function BitmapFontTexture(scene, bmFontUrl, textureUrl, noMipmap, invertY, samplingMode, premultipliedAlpha, onLoad, onError) {
  2070. if (textureUrl === void 0) { textureUrl = null; }
  2071. if (noMipmap === void 0) { noMipmap = false; }
  2072. if (invertY === void 0) { invertY = true; }
  2073. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2074. if (premultipliedAlpha === void 0) { premultipliedAlpha = false; }
  2075. if (onLoad === void 0) { onLoad = null; }
  2076. if (onError === void 0) { onError = null; }
  2077. var _this = _super.call(this, null, scene, noMipmap, invertY, samplingMode, premultipliedAlpha) || this;
  2078. _this._usedCounter = 1;
  2079. var xhr = new XMLHttpRequest();
  2080. xhr.onreadystatechange = function () {
  2081. if (xhr.readyState === XMLHttpRequest.DONE) {
  2082. if (xhr.status === 200) {
  2083. var ext = bmFontUrl.split('.').pop().split(/\#|\?/)[0];
  2084. var plugins = BitmapFontTexture.plugins.get(ext.toLocaleLowerCase());
  2085. if (!plugins) {
  2086. if (onError) {
  2087. onError("couldn't find a plugin for this file extension", -1);
  2088. }
  2089. return;
  2090. }
  2091. var _loop_1 = function (p) {
  2092. var ret = p.loadFont(xhr.response, scene, invertY);
  2093. if (ret) {
  2094. var bfi = ret.bfi;
  2095. if (textureUrl != null) {
  2096. bfi.textureUrl = textureUrl;
  2097. }
  2098. else {
  2099. var baseUrl = bmFontUrl.substr(0, bmFontUrl.lastIndexOf("/") + 1);
  2100. bfi.textureUrl = baseUrl + bfi.textureFile;
  2101. }
  2102. _this._texture = scene.getEngine().createTexture(bfi.textureUrl, noMipmap, invertY, scene, samplingMode, function () {
  2103. if (ret.bfi && onLoad) {
  2104. onLoad();
  2105. }
  2106. });
  2107. _this._lineHeight = bfi.lineHeight;
  2108. _this._charInfos.copyFrom(bfi.charDic);
  2109. var ci = _this.getChar(" ");
  2110. if (ci) {
  2111. _this._spaceWidth = ci.charWidth;
  2112. }
  2113. else {
  2114. _this._charInfos.first(function (k, v) { return _this._spaceWidth = v.charWidth; });
  2115. }
  2116. if (!ret.bfi && onError) {
  2117. onError(ret.errorMsg, ret.errorCode);
  2118. }
  2119. return { value: void 0 };
  2120. }
  2121. };
  2122. for (var _i = 0, plugins_1 = plugins; _i < plugins_1.length; _i++) {
  2123. var p = plugins_1[_i];
  2124. var state_1 = _loop_1(p);
  2125. if (typeof state_1 === "object")
  2126. return state_1.value;
  2127. }
  2128. if (onError) {
  2129. onError("No plugin to load this BMFont file format", -1);
  2130. }
  2131. }
  2132. else {
  2133. if (onError) {
  2134. onError("Couldn't load file through HTTP Request, HTTP Status " + xhr.status, xhr.status);
  2135. }
  2136. }
  2137. }
  2138. };
  2139. xhr.open("GET", bmFontUrl, true);
  2140. xhr.send();
  2141. return _this;
  2142. }
  2143. BitmapFontTexture.GetCachedFontTexture = function (scene, fontTexture) {
  2144. var dic = scene.getOrAddExternalDataWithFactory("BitmapFontTextureCache", function () { return new BABYLON.StringDictionary(); });
  2145. var ft = dic.get(fontTexture.uid);
  2146. if (ft) {
  2147. ++ft._usedCounter;
  2148. return ft;
  2149. }
  2150. dic.add(fontTexture.uid, fontTexture);
  2151. return ft;
  2152. };
  2153. BitmapFontTexture.ReleaseCachedFontTexture = function (scene, fontTexture) {
  2154. var dic = scene.getExternalData("BitmapFontTextureCache");
  2155. if (!dic) {
  2156. return;
  2157. }
  2158. var font = dic.get(fontTexture.uid);
  2159. if (--font._usedCounter === 0) {
  2160. dic.remove(fontTexture.uid);
  2161. font.dispose();
  2162. }
  2163. };
  2164. Object.defineProperty(BitmapFontTexture.prototype, "isDynamicFontTexture", {
  2165. /**
  2166. * Is the font dynamically updated, if true is returned then you have to call the update() before using the font in rendering if new character were adding using getChar()
  2167. */
  2168. get: function () {
  2169. return false;
  2170. },
  2171. enumerable: true,
  2172. configurable: true
  2173. });
  2174. /**
  2175. * This method does nothing for a BitmapFontTexture object as it's a static texture
  2176. */
  2177. BitmapFontTexture.prototype.update = function () {
  2178. };
  2179. /**
  2180. * Retrieve the CharInfo object for a given character
  2181. * @param char the character to retrieve the CharInfo object from (e.g.: "A", "a", etc.)
  2182. */
  2183. BitmapFontTexture.prototype.getChar = function (char) {
  2184. return this._charInfos.get(char);
  2185. };
  2186. /**
  2187. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  2188. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  2189. */
  2190. BitmapFontTexture.prototype.incCachedFontTextureCounter = function () {
  2191. ++this._usedCounter;
  2192. };
  2193. /**
  2194. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  2195. */
  2196. BitmapFontTexture.prototype.decCachedFontTextureCounter = function () {
  2197. var dic = this.getScene().getExternalData("BitmapFontTextureCache");
  2198. if (!dic) {
  2199. return;
  2200. }
  2201. if (--this._usedCounter === 0) {
  2202. dic.remove(this._cachedFontId);
  2203. this.dispose();
  2204. }
  2205. };
  2206. BitmapFontTexture.addLoader = function (fileExtension, plugin) {
  2207. var a = BitmapFontTexture.plugins.getOrAddWithFactory(fileExtension.toLocaleLowerCase(), function () { return new Array(); });
  2208. a.push(plugin);
  2209. };
  2210. return BitmapFontTexture;
  2211. }(BaseFontTexture));
  2212. BitmapFontTexture.plugins = new BABYLON.StringDictionary();
  2213. BABYLON.BitmapFontTexture = BitmapFontTexture;
  2214. /**
  2215. * This class is a special kind of texture which generates on the fly characters of a given css style "fontName".
  2216. * The generated texture will be updated when new characters will be retrieved using the getChar() method, but you have
  2217. * to call the update() method for the texture to fetch these changes, you can harmlessly call update any time you want, if no
  2218. * change were made, nothing will happen.
  2219. * The Font Texture can be rendered in three modes: normal size, super sampled size (x2) or using Signed Distance Field rendering.
  2220. * Signed Distance Field should be prefered because the texture can be rendered using AlphaTest instead of Transparency, which is way more faster. More about SDF here (http://www.valvesoftware.com/publications/2007/SIGGRAPH2007_AlphaTestedMagnification.pdf).
  2221. * The only flaw of SDF is that the rendering quality may not be the best or the edges too sharp is the font thickness is too thin.
  2222. */
  2223. var FontTexture = (function (_super) {
  2224. __extends(FontTexture, _super);
  2225. /**
  2226. * Create a new instance of the FontTexture class
  2227. * @param name the name of the texture
  2228. * @param font the font to use, use the W3C CSS notation
  2229. * @param scene the scene that owns the texture
  2230. * @param maxCharCount the approximative maximum count of characters that could fit in the texture. This is an approximation because most of the fonts are proportional (each char has its own Width). The 'W' character's width is used to compute the size of the texture based on the given maxCharCount
  2231. * @param samplingMode the texture sampling mode
  2232. * @param superSample if true the FontTexture will be created with a font of a size twice bigger than the given one but all properties (lineHeight, charWidth, etc.) will be according to the original size. This is made to improve the text quality.
  2233. */
  2234. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
  2235. if (maxCharCount === void 0) { maxCharCount = 200; }
  2236. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2237. if (superSample === void 0) { superSample = false; }
  2238. if (signedDistanceField === void 0) { signedDistanceField = false; }
  2239. var _this = _super.call(this, null, scene, true, false, samplingMode) || this;
  2240. _this._curCharCount = 0;
  2241. _this._lastUpdateCharCount = -1;
  2242. _this._usedCounter = 1;
  2243. _this.name = name;
  2244. _this.debugMode = false;
  2245. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  2246. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  2247. _this._sdfScale = 8;
  2248. _this._signedDistanceField = signedDistanceField;
  2249. _this._superSample = false;
  2250. _this._isPremultipliedAlpha = !signedDistanceField;
  2251. // SDF will use super sample no matter what, the resolution is otherwise too poor to produce correct result
  2252. if (superSample || signedDistanceField) {
  2253. var sfont = _this.getSuperSampleFont(font);
  2254. if (sfont) {
  2255. _this._superSample = true;
  2256. font = sfont;
  2257. }
  2258. }
  2259. // First canvas creation to determine the size of the texture to create
  2260. _this._canvas = document.createElement("canvas");
  2261. _this._context = _this._canvas.getContext("2d");
  2262. _this._context.font = font;
  2263. _this._context.fillStyle = "white";
  2264. _this._context.textBaseline = "top";
  2265. var res = _this.getFontHeight(font, "j$|");
  2266. _this._lineHeightSuper = res.height; //+4;
  2267. _this._lineHeight = _this._superSample ? (Math.ceil(_this._lineHeightSuper / 2)) : _this._lineHeightSuper;
  2268. _this._offset = res.offset;
  2269. res = _this.getFontHeight(font, "f");
  2270. _this._baseLine = res.height + res.offset - _this._offset;
  2271. var maxCharWidth = Math.max(_this._context.measureText("W").width, _this._context.measureText("_").width);
  2272. _this._spaceWidthSuper = _this._context.measureText(" ").width;
  2273. _this._spaceWidth = _this._superSample ? (_this._spaceWidthSuper / 2) : _this._spaceWidthSuper;
  2274. _this._xMargin = Math.ceil(maxCharWidth / 32);
  2275. _this._yMargin = _this._xMargin;
  2276. // This is an approximate size, but should always be able to fit at least the maxCharCount
  2277. var totalEstSurface = (Math.ceil(_this._lineHeightSuper) + (_this._yMargin * 2)) * (Math.ceil(maxCharWidth) + (_this._xMargin * 2)) * maxCharCount;
  2278. var edge = Math.sqrt(totalEstSurface);
  2279. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  2280. // Create the texture that will store the font characters
  2281. _this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  2282. var textureSize = _this.getSize();
  2283. _this.hasAlpha = _this._signedDistanceField === false;
  2284. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  2285. _this._canvas = document.createElement("canvas");
  2286. _this._canvas.width = textureSize.width;
  2287. _this._canvas.height = textureSize.height;
  2288. _this._context = _this._canvas.getContext("2d");
  2289. _this._context.textBaseline = "top";
  2290. _this._context.font = font;
  2291. _this._context.fillStyle = "white";
  2292. _this._context.imageSmoothingEnabled = false;
  2293. _this._context.clearRect(0, 0, textureSize.width, textureSize.height);
  2294. // Create a canvas for the signed distance field mode, we only have to store one char, the purpose is to render a char scaled _sdfScale times
  2295. // into this 2D context, then get the bitmap data, create the SDF char and push the result in the _context (which hold the whole Font Texture content)
  2296. // So you can see this context as an intermediate one, because it is.
  2297. if (_this._signedDistanceField) {
  2298. var sdfC = document.createElement("canvas");
  2299. var s = _this._sdfScale;
  2300. sdfC.width = (Math.ceil(maxCharWidth) + _this._xMargin * 2) * s;
  2301. sdfC.height = (Math.ceil(_this._lineHeightSuper) + _this._yMargin * 2) * s;
  2302. var sdfCtx = sdfC.getContext("2d");
  2303. sdfCtx.scale(s, s);
  2304. sdfCtx.textBaseline = "top";
  2305. sdfCtx.font = font;
  2306. sdfCtx.fillStyle = "white";
  2307. sdfCtx.imageSmoothingEnabled = false;
  2308. _this._sdfCanvas = sdfC;
  2309. _this._sdfContext = sdfCtx;
  2310. }
  2311. _this._currentFreePosition = BABYLON.Vector2.Zero();
  2312. // Add the basic ASCII based characters
  2313. for (var i = 0x20; i < 0x7F; i++) {
  2314. var c = String.fromCharCode(i);
  2315. _this.getChar(c);
  2316. }
  2317. _this.update();
  2318. return _this;
  2319. //this._saveToImage("");
  2320. }
  2321. Object.defineProperty(FontTexture.prototype, "isDynamicFontTexture", {
  2322. get: function () {
  2323. return true;
  2324. },
  2325. enumerable: true,
  2326. configurable: true
  2327. });
  2328. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField, bilinearFiltering) {
  2329. if (supersample === void 0) { supersample = false; }
  2330. if (signedDistanceField === void 0) { signedDistanceField = false; }
  2331. if (bilinearFiltering === void 0) { bilinearFiltering = false; }
  2332. var dic = scene.getOrAddExternalDataWithFactory("FontTextureCache", function () { return new BABYLON.StringDictionary(); });
  2333. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF") + (bilinearFiltering ? "_+BF" : "_-BF");
  2334. var ft = dic.get(lfn);
  2335. if (ft) {
  2336. ++ft._usedCounter;
  2337. return ft;
  2338. }
  2339. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, (signedDistanceField || bilinearFiltering) ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, supersample, signedDistanceField);
  2340. ft._cachedFontId = lfn;
  2341. dic.add(lfn, ft);
  2342. return ft;
  2343. };
  2344. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField, bilinearFiltering) {
  2345. if (supersample === void 0) { supersample = false; }
  2346. if (signedDistanceField === void 0) { signedDistanceField = false; }
  2347. if (bilinearFiltering === void 0) { bilinearFiltering = false; }
  2348. var dic = scene.getExternalData("FontTextureCache");
  2349. if (!dic) {
  2350. return;
  2351. }
  2352. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF") + (bilinearFiltering ? "_+BF" : "_-BF");
  2353. var font = dic.get(lfn);
  2354. if (--font._usedCounter === 0) {
  2355. dic.remove(lfn);
  2356. font.dispose();
  2357. }
  2358. };
  2359. FontTexture.prototype._saveToImage = function (url) {
  2360. var base64Image = this._canvas.toDataURL("image/png");
  2361. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2362. if (("download" in document.createElement("a"))) {
  2363. var a = window.document.createElement("a");
  2364. a.href = base64Image;
  2365. var date = new Date();
  2366. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) +
  2367. "-" +
  2368. date.getDate() +
  2369. "_" +
  2370. date.getHours() +
  2371. "-" +
  2372. ('0' + date.getMinutes()).slice(-2);
  2373. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  2374. window.document.body.appendChild(a);
  2375. a.addEventListener("click", function () {
  2376. a.parentElement.removeChild(a);
  2377. });
  2378. a.click();
  2379. }
  2380. else {
  2381. var newWindow = window.open("");
  2382. var img = newWindow.document.createElement("img");
  2383. img.src = base64Image;
  2384. newWindow.document.body.appendChild(img);
  2385. }
  2386. };
  2387. /**
  2388. * Make sure the given char is present in the font map.
  2389. * @param char the character to get or add
  2390. * @return the CharInfo instance corresponding to the given character
  2391. */
  2392. FontTexture.prototype.getChar = function (char) {
  2393. var _this = this;
  2394. if (char.length !== 1) {
  2395. return null;
  2396. }
  2397. var info = this._charInfos.get(char);
  2398. if (info) {
  2399. return info;
  2400. }
  2401. info = new CharInfo();
  2402. var measure = this._context.measureText(char);
  2403. var textureSize = this.getSize();
  2404. // we reached the end of the current line?
  2405. var width = Math.ceil(measure.width);
  2406. if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
  2407. this._currentFreePosition.x = 0;
  2408. this._currentFreePosition.y += Math.ceil(this._lineHeightSuper + this._yMargin * 2);
  2409. // No more room?
  2410. if (this._currentFreePosition.y > textureSize.height) {
  2411. return this.getChar("!");
  2412. }
  2413. }
  2414. var curPosX = this._currentFreePosition.x + 0.5;
  2415. var curPosY = this._currentFreePosition.y + 0.5;
  2416. var curPosXMargin = curPosX + this._xMargin;
  2417. var curPosYMargin = curPosY + this._yMargin;
  2418. var drawDebug = function (ctx) {
  2419. ctx.strokeStyle = "green";
  2420. ctx.beginPath();
  2421. ctx.rect(curPosXMargin, curPosYMargin, width, _this._lineHeightSuper);
  2422. ctx.closePath();
  2423. ctx.stroke();
  2424. ctx.strokeStyle = "blue";
  2425. ctx.beginPath();
  2426. ctx.moveTo(curPosXMargin, curPosYMargin + Math.round(_this._baseLine));
  2427. ctx.lineTo(curPosXMargin + width, curPosYMargin + Math.round(_this._baseLine));
  2428. ctx.closePath();
  2429. ctx.stroke();
  2430. };
  2431. // In SDF mode we render the character in an intermediate 2D context which scale the character this._sdfScale times (which is required to compute the SDF map accurately)
  2432. if (this._signedDistanceField) {
  2433. var s = this._sdfScale;
  2434. this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
  2435. // Coordinates are subject to the context's scale
  2436. this._sdfContext.fillText(char, this._xMargin + 0.5, this._yMargin + 0.5 - this._offset);
  2437. // Canvas Pixel Coordinates, no scale
  2438. var data = this._sdfContext.getImageData(0, 0, (width + (this._xMargin * 2)) * s, this._sdfCanvas.height);
  2439. var res = this._computeSDFChar(data);
  2440. this._context.putImageData(res, curPosX, curPosY);
  2441. if (this.debugMode) {
  2442. drawDebug(this._context);
  2443. }
  2444. }
  2445. else {
  2446. if (this.debugMode) {
  2447. drawDebug(this._context);
  2448. }
  2449. // Draw the character in the HTML canvas
  2450. this._context.fillText(char, curPosXMargin, curPosYMargin - this._offset);
  2451. // Premul Alpha manually
  2452. var id = this._context.getImageData(curPosXMargin, curPosYMargin, width, this._lineHeightSuper);
  2453. for (var i = 0; i < id.data.length; i += 4) {
  2454. var v = id.data[i + 3];
  2455. if (v > 0 && v < 255) {
  2456. id.data[i + 0] = v;
  2457. id.data[i + 1] = v;
  2458. id.data[i + 2] = v;
  2459. id.data[i + 3] = v;
  2460. }
  2461. }
  2462. this._context.putImageData(id, curPosXMargin, curPosYMargin);
  2463. }
  2464. // Fill the CharInfo object
  2465. info.topLeftUV = new BABYLON.Vector2((curPosXMargin) / textureSize.width, (this._currentFreePosition.y + this._yMargin) / textureSize.height);
  2466. info.bottomRightUV = new BABYLON.Vector2((curPosXMargin + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + this._yMargin) / textureSize.height));
  2467. info.yOffset = info.xOffset = 0;
  2468. if (this._signedDistanceField) {
  2469. var off = 1 / textureSize.width;
  2470. info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
  2471. info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
  2472. }
  2473. info.charWidth = this._superSample ? (width / 2) : width;
  2474. info.xAdvance = info.charWidth;
  2475. // Add the info structure
  2476. this._charInfos.add(char, info);
  2477. this._curCharCount++;
  2478. // Set the next position
  2479. this._currentFreePosition.x += Math.ceil(width + this._xMargin * 2);
  2480. return info;
  2481. };
  2482. FontTexture.prototype._computeSDFChar = function (source) {
  2483. var scl = this._sdfScale;
  2484. var sw = source.width;
  2485. var sh = source.height;
  2486. var dw = sw / scl;
  2487. var dh = sh / scl;
  2488. var roffx = 0;
  2489. var roffy = 0;
  2490. // We shouldn't look beyond half of the biggest between width and height
  2491. var radius = scl;
  2492. var br = radius - 1;
  2493. var lookupSrc = function (dx, dy, offX, offY, lookVis) {
  2494. var sx = dx * scl;
  2495. var sy = dy * scl;
  2496. // Looking out of the area? return true to make the test going on
  2497. if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
  2498. return true;
  2499. }
  2500. // Get the pixel we want
  2501. var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
  2502. var res = (val > 0) === lookVis;
  2503. if (!res) {
  2504. roffx = offX;
  2505. roffy = offY;
  2506. }
  2507. return res;
  2508. };
  2509. var lookupArea = function (dx, dy, lookVis) {
  2510. // Fast rejection test, if we have the same result in N, S, W, E at a distance which is the radius-1 then it means the data will be consistent in this area. That's because we've scale the rendering of the letter "radius" times, so a letter's pixel will be at least radius wide
  2511. if (lookupSrc(dx, dy, 0, br, lookVis) &&
  2512. lookupSrc(dx, dy, 0, -br, lookVis) &&
  2513. lookupSrc(dx, dy, -br, 0, lookVis) &&
  2514. lookupSrc(dx, dy, br, 0, lookVis)) {
  2515. return 0;
  2516. }
  2517. for (var i = 1; i <= radius; i++) {
  2518. // Quick test N, S, W, E
  2519. if (!lookupSrc(dx, dy, 0, i, lookVis) || !lookupSrc(dx, dy, 0, -i, lookVis) || !lookupSrc(dx, dy, -i, 0, lookVis) || !lookupSrc(dx, dy, i, 0, lookVis)) {
  2520. return i * i; // Squared Distance is simple to compute in this case
  2521. }
  2522. // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
  2523. for (var j = 1; j <= i; j++) {
  2524. if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
  2525. !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
  2526. !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
  2527. !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
  2528. // We found the nearest texel having and opposite state, store the squared length
  2529. var res_1 = (i * i) + (j * j);
  2530. var count = 1;
  2531. // To improve quality we will sample the texels around this one, so it's 8 samples, we consider only the one having an opposite state, add them to the current res and will will compute the average at the end
  2532. if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
  2533. res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
  2534. ++count;
  2535. }
  2536. if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
  2537. res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
  2538. ++count;
  2539. }
  2540. if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
  2541. res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
  2542. ++count;
  2543. }
  2544. if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
  2545. res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
  2546. ++count;
  2547. }
  2548. if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
  2549. res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
  2550. ++count;
  2551. }
  2552. if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
  2553. res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
  2554. ++count;
  2555. }
  2556. if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
  2557. res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
  2558. ++count;
  2559. }
  2560. if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
  2561. res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
  2562. ++count;
  2563. }
  2564. // Compute the average based on the accumulated distance
  2565. return res_1 / count;
  2566. }
  2567. }
  2568. }
  2569. return 0;
  2570. };
  2571. var tmp = new Array(dw * dh);
  2572. for (var y = 0; y < dh; y++) {
  2573. for (var x = 0; x < dw; x++) {
  2574. var curState = lookupSrc(x, y, 0, 0, true);
  2575. var d = lookupArea(x, y, curState);
  2576. if (d === 0) {
  2577. d = radius * radius * 2;
  2578. }
  2579. tmp[(y * dw) + x] = curState ? d : -d;
  2580. }
  2581. }
  2582. var res = this._context.createImageData(dw, dh);
  2583. var size = dw * dh;
  2584. for (var j = 0; j < size; j++) {
  2585. var d = tmp[j];
  2586. var sign = (d < 0) ? -1 : 1;
  2587. d = Math.sqrt(Math.abs(d)) * sign;
  2588. d *= 127.5 / radius;
  2589. d += 127.5;
  2590. if (d < 0) {
  2591. d = 0;
  2592. }
  2593. else if (d > 255) {
  2594. d = 255;
  2595. }
  2596. d += 0.5;
  2597. res.data[j * 4 + 0] = d;
  2598. res.data[j * 4 + 1] = d;
  2599. res.data[j * 4 + 2] = d;
  2600. res.data[j * 4 + 3] = 255;
  2601. }
  2602. return res;
  2603. };
  2604. FontTexture.prototype.getSuperSampleFont = function (font) {
  2605. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  2606. var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z]+?)\s*$/;
  2607. var res = font.toLocaleLowerCase().match(regex);
  2608. if (res == null) {
  2609. return null;
  2610. }
  2611. var size = parseInt(res[4]);
  2612. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  2613. var newFont = "";
  2614. for (var j = 1; j < res.length; j++) {
  2615. if (res[j] != null) {
  2616. newFont += res[j] + " ";
  2617. }
  2618. }
  2619. return newFont;
  2620. };
  2621. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  2622. FontTexture.prototype.getFontHeight = function (font, chars) {
  2623. var fontDraw = document.createElement("canvas");
  2624. fontDraw.width = 600;
  2625. fontDraw.height = 600;
  2626. var ctx = fontDraw.getContext('2d');
  2627. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  2628. ctx.textBaseline = 'top';
  2629. ctx.fillStyle = 'white';
  2630. ctx.font = font;
  2631. ctx.fillText(chars, 0, 0);
  2632. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  2633. var start = -1;
  2634. var end = -1;
  2635. for (var row = 0; row < fontDraw.height; row++) {
  2636. for (var column = 0; column < fontDraw.width; column++) {
  2637. var index = (row * fontDraw.width + column) * 4;
  2638. var pix = pixels[index];
  2639. if (pix === 0) {
  2640. if (column === fontDraw.width - 1 && start !== -1) {
  2641. end = row;
  2642. row = fontDraw.height;
  2643. break;
  2644. }
  2645. continue;
  2646. }
  2647. else {
  2648. if (start === -1) {
  2649. start = row;
  2650. }
  2651. break;
  2652. }
  2653. }
  2654. }
  2655. return { height: (end - start) + 1, offset: start };
  2656. };
  2657. Object.defineProperty(FontTexture.prototype, "canRescale", {
  2658. get: function () {
  2659. return false;
  2660. },
  2661. enumerable: true,
  2662. configurable: true
  2663. });
  2664. FontTexture.prototype.getContext = function () {
  2665. return this._context;
  2666. };
  2667. /**
  2668. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  2669. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  2670. */
  2671. FontTexture.prototype.update = function () {
  2672. // Update only if there's new char added since the previous update
  2673. if (this._lastUpdateCharCount < this._curCharCount) {
  2674. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  2675. this._lastUpdateCharCount = this._curCharCount;
  2676. }
  2677. };
  2678. // cloning should be prohibited, there's no point to duplicate this texture at all
  2679. FontTexture.prototype.clone = function () {
  2680. return null;
  2681. };
  2682. /**
  2683. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  2684. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  2685. */
  2686. FontTexture.prototype.incCachedFontTextureCounter = function () {
  2687. ++this._usedCounter;
  2688. };
  2689. /**
  2690. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  2691. */
  2692. FontTexture.prototype.decCachedFontTextureCounter = function () {
  2693. var dic = this.getScene().getExternalData("FontTextureCache");
  2694. if (!dic) {
  2695. return;
  2696. }
  2697. if (--this._usedCounter === 0) {
  2698. dic.remove(this._cachedFontId);
  2699. this.dispose();
  2700. }
  2701. };
  2702. return FontTexture;
  2703. }(BaseFontTexture));
  2704. BABYLON.FontTexture = FontTexture;
  2705. /**
  2706. * Orginial code from cocos2d-js, converted to TypeScript by Nockawa
  2707. * Load the Text version of the BMFont format, no XML or binary supported, just plain old text
  2708. */
  2709. var BMFontLoaderTxt = BMFontLoaderTxt_1 = (function () {
  2710. function BMFontLoaderTxt() {
  2711. }
  2712. BMFontLoaderTxt.prototype._parseStrToObj = function (str) {
  2713. var arr = str.match(BMFontLoaderTxt_1.ITEM_EXP);
  2714. if (!arr) {
  2715. return null;
  2716. }
  2717. var obj = {};
  2718. for (var i = 0, li = arr.length; i < li; i++) {
  2719. var tempStr = arr[i];
  2720. var index = tempStr.indexOf("=");
  2721. var key = tempStr.substring(0, index);
  2722. var value = tempStr.substring(index + 1);
  2723. if (value.match(BMFontLoaderTxt_1.INT_EXP))
  2724. value = parseInt(value);
  2725. else if (value[0] === '"')
  2726. value = value.substring(1, value.length - 1);
  2727. obj[key] = value;
  2728. }
  2729. return obj;
  2730. };
  2731. BMFontLoaderTxt.prototype._buildCharInfo = function (bfi, initialLine, obj, textureSize, invertY, chars) {
  2732. var char = null;
  2733. var x = null;
  2734. var y = null;
  2735. var width = null;
  2736. var height = null;
  2737. var xoffset = 0;
  2738. var yoffset = 0;
  2739. var xadvance = 0;
  2740. var ci = new CharInfo();
  2741. for (var key in obj) {
  2742. var value = obj[key];
  2743. switch (key) {
  2744. case "id":
  2745. char = String.fromCharCode(value);
  2746. break;
  2747. case "x":
  2748. x = value;
  2749. break;
  2750. case "y":
  2751. y = value;
  2752. break;
  2753. case "width":
  2754. width = value;
  2755. break;
  2756. case "height":
  2757. height = value;
  2758. break;
  2759. case "xadvance":
  2760. xadvance = value;
  2761. break;
  2762. case "xoffset":
  2763. xoffset = value;
  2764. break;
  2765. case "yoffset":
  2766. yoffset = value;
  2767. break;
  2768. }
  2769. }
  2770. if (x != null && y != null && width != null && height != null && char != null) {
  2771. ci.xAdvance = xadvance;
  2772. ci.xOffset = xoffset;
  2773. ci.yOffset = bfi.lineHeight - height - yoffset;
  2774. if (invertY) {
  2775. ci.topLeftUV = new BABYLON.Vector2(1 - (x / textureSize.width), 1 - (y / textureSize.height));
  2776. ci.bottomRightUV = new BABYLON.Vector2(1 - ((x + width) / textureSize.width), 1 - ((y + height) / textureSize.height));
  2777. }
  2778. else {
  2779. ci.topLeftUV = new BABYLON.Vector2(x / textureSize.width, y / textureSize.height);
  2780. ci.bottomRightUV = new BABYLON.Vector2((x + width) / textureSize.width, (y + height) / textureSize.height);
  2781. }
  2782. ci.charWidth = width;
  2783. chars.add(char, ci);
  2784. }
  2785. else {
  2786. console.log("Error while parsing line " + initialLine);
  2787. }
  2788. };
  2789. BMFontLoaderTxt.prototype.loadFont = function (fontContent, scene, invertY) {
  2790. var fontStr = fontContent;
  2791. var bfi = new BitmapFontInfo();
  2792. var errorCode = 0;
  2793. var errorMsg = "OK";
  2794. //padding
  2795. var info = fontStr.match(BMFontLoaderTxt_1.INFO_EXP);
  2796. var infoObj = this._parseStrToObj(info[0]);
  2797. if (!infoObj) {
  2798. return null;
  2799. }
  2800. var paddingArr = infoObj["padding"].split(",");
  2801. bfi.padding = new BABYLON.Vector4(parseInt(paddingArr[0]), parseInt(paddingArr[1]), parseInt(paddingArr[2]), parseInt(paddingArr[3]));
  2802. //common
  2803. var commonObj = this._parseStrToObj(fontStr.match(BMFontLoaderTxt_1.COMMON_EXP)[0]);
  2804. bfi.lineHeight = commonObj["lineHeight"];
  2805. bfi.baseLine = commonObj["base"];
  2806. bfi.textureSize = new BABYLON.Size(commonObj["scaleW"], commonObj["scaleH"]);
  2807. var maxTextureSize = scene.getEngine()._gl.getParameter(0xd33);
  2808. if (commonObj["scaleW"] > maxTextureSize.width || commonObj["scaleH"] > maxTextureSize.height) {
  2809. errorMsg = "FontMap texture's size is bigger than what WebGL supports";
  2810. errorCode = -1;
  2811. }
  2812. else {
  2813. if (commonObj["pages"] !== 1) {
  2814. errorMsg = "FontMap must contain one page only.";
  2815. errorCode = -1;
  2816. }
  2817. else {
  2818. //page
  2819. var pageObj = this._parseStrToObj(fontStr.match(BMFontLoaderTxt_1.PAGE_EXP)[0]);
  2820. if (pageObj["id"] !== 0) {
  2821. errorMsg = "Only one page of ID 0 is supported";
  2822. errorCode = -1;
  2823. }
  2824. else {
  2825. bfi.textureFile = pageObj["file"];
  2826. //char
  2827. var charLines = fontStr.match(BMFontLoaderTxt_1.CHAR_EXP);
  2828. for (var i = 0, li = charLines.length; i < li; i++) {
  2829. var charObj = this._parseStrToObj(charLines[i]);
  2830. this._buildCharInfo(bfi, charLines[i], charObj, bfi.textureSize, invertY, bfi.charDic);
  2831. }
  2832. //kerning
  2833. var kerningLines = fontStr.match(BMFontLoaderTxt_1.KERNING_EXP);
  2834. if (kerningLines) {
  2835. for (var i = 0, li = kerningLines.length; i < li; i++) {
  2836. var kerningObj = this._parseStrToObj(kerningLines[i]);
  2837. bfi.kerningDic.add(((kerningObj["first"] << 16) | (kerningObj["second"] & 0xffff)).toString(), kerningObj["amount"]);
  2838. }
  2839. }
  2840. }
  2841. }
  2842. }
  2843. return { bfi: bfi, errorCode: errorCode, errorMsg: errorMsg };
  2844. };
  2845. return BMFontLoaderTxt;
  2846. }());
  2847. BMFontLoaderTxt.INFO_EXP = /info [^\r\n]*(\r\n|$)/gi;
  2848. BMFontLoaderTxt.COMMON_EXP = /common [^\n]*(\n|$)/gi;
  2849. BMFontLoaderTxt.PAGE_EXP = /page [^\n]*(\n|$)/gi;
  2850. BMFontLoaderTxt.CHAR_EXP = /char [^\n]*(\n|$)/gi;
  2851. BMFontLoaderTxt.KERNING_EXP = /kerning [^\n]*(\n|$)/gi;
  2852. BMFontLoaderTxt.ITEM_EXP = /\w+=[^ \r\n]+/gi;
  2853. BMFontLoaderTxt.INT_EXP = /^[\-]?\d+$/;
  2854. BMFontLoaderTxt = BMFontLoaderTxt_1 = __decorate([
  2855. BitmapFontLoaderPlugin("fnt", new BMFontLoaderTxt_1())
  2856. ], BMFontLoaderTxt);
  2857. ;
  2858. function BitmapFontLoaderPlugin(fileExtension, plugin) {
  2859. return function () {
  2860. BitmapFontTexture.addLoader(fileExtension, plugin);
  2861. };
  2862. }
  2863. BABYLON.BitmapFontLoaderPlugin = BitmapFontLoaderPlugin;
  2864. var BMFontLoaderTxt_1;
  2865. })(BABYLON || (BABYLON = {}));
  2866. //# sourceMappingURL=babylon.fontTexture.js.map
  2867. var BABYLON;
  2868. (function (BABYLON) {
  2869. /**
  2870. * Stores 2D Bounding Information.
  2871. * This class handles a circle area and a bounding rectangle one.
  2872. */
  2873. var BoundingInfo2D = (function () {
  2874. function BoundingInfo2D() {
  2875. this.radius = 0;
  2876. this.center = BABYLON.Vector2.Zero();
  2877. this.extent = BABYLON.Vector2.Zero();
  2878. this._worldAABBDirty = false;
  2879. this._worldAABBDirtyObservable = null;
  2880. this._worldAABB = BABYLON.Vector4.Zero();
  2881. }
  2882. /**
  2883. * Create a BoundingInfo2D object from a given size
  2884. * @param size the size that will be used to set the extend, radius will be computed from it.
  2885. */
  2886. BoundingInfo2D.CreateFromSize = function (size) {
  2887. var r = new BoundingInfo2D();
  2888. BoundingInfo2D.CreateFromSizeToRef(size, r);
  2889. return r;
  2890. };
  2891. /**
  2892. * Create a BoundingInfo2D object from a given radius
  2893. * @param radius the radius to use, the extent will be computed from it.
  2894. */
  2895. BoundingInfo2D.CreateFromRadius = function (radius) {
  2896. var r = new BoundingInfo2D();
  2897. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  2898. return r;
  2899. };
  2900. /**
  2901. * Create a BoundingInfo2D object from a list of points.
  2902. * The resulted object will be the smallest bounding area that includes all the given points.
  2903. * @param points an array of points to compute the bounding object from.
  2904. */
  2905. BoundingInfo2D.CreateFromPoints = function (points) {
  2906. var r = new BoundingInfo2D();
  2907. BoundingInfo2D.CreateFromPointsToRef(points, r);
  2908. return r;
  2909. };
  2910. /**
  2911. * Update a BoundingInfo2D object using the given Size as input
  2912. * @param size the bounding data will be computed from this size.
  2913. * @param b must be a valid/allocated object, it will contain the result of the operation
  2914. */
  2915. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  2916. if (!size) {
  2917. size = BABYLON.Size.Zero();
  2918. }
  2919. b.center.x = +size.width / 2;
  2920. b.center.y = +size.height / 2;
  2921. b.extent.x = b.center.x;
  2922. b.extent.y = b.center.y;
  2923. b.radius = b.extent.length();
  2924. b._worldAABBDirty = true;
  2925. };
  2926. /**
  2927. * Update a BoundingInfo2D object using the given radius as input
  2928. * @param radius the bounding data will be computed from this radius
  2929. * @param b must be a valid/allocated object, it will contain the result of the operation
  2930. */
  2931. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  2932. b.center.x = b.center.y = 0;
  2933. var r = +radius;
  2934. b.extent.x = r;
  2935. b.extent.y = r;
  2936. b.radius = r;
  2937. b._worldAABBDirty = true;
  2938. };
  2939. /**
  2940. * Update a BoundingInfo2D object using the given points array as input
  2941. * @param points the point array to use to update the bounding data
  2942. * @param b must be a valid/allocated object, it will contain the result of the operation
  2943. */
  2944. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  2945. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  2946. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  2947. var p = points_1[_i];
  2948. xmin = Math.min(p.x, xmin);
  2949. xmax = Math.max(p.x, xmax);
  2950. ymin = Math.min(p.y, ymin);
  2951. ymax = Math.max(p.y, ymax);
  2952. }
  2953. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  2954. };
  2955. /**
  2956. * Update a BoundingInfo2D object using the given min/max values as input
  2957. * @param xmin the smallest x coordinate
  2958. * @param xmax the biggest x coordinate
  2959. * @param ymin the smallest y coordinate
  2960. * @param ymax the buggest y coordinate
  2961. * @param b must be a valid/allocated object, it will contain the result of the operation
  2962. */
  2963. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  2964. var w = xmax - xmin;
  2965. var h = ymax - ymin;
  2966. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  2967. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  2968. b.radius = b.extent.length();
  2969. b._worldAABBDirty = true;
  2970. };
  2971. BoundingInfo2D.prototype.toString = function () {
  2972. return "Center: " + this.center + ", Extent: " + this.extent + ", Radius: " + this.radius;
  2973. };
  2974. /**
  2975. * Duplicate this instance and return a new one
  2976. * @return the duplicated instance
  2977. */
  2978. BoundingInfo2D.prototype.clone = function () {
  2979. var r = new BoundingInfo2D();
  2980. r.center = this.center.clone();
  2981. r.radius = this.radius;
  2982. r.extent = this.extent.clone();
  2983. return r;
  2984. };
  2985. BoundingInfo2D.prototype.clear = function () {
  2986. this.center.copyFromFloats(0, 0);
  2987. this.radius = 0;
  2988. this.extent.copyFromFloats(0, 0);
  2989. this._worldAABBDirty = true;
  2990. };
  2991. BoundingInfo2D.prototype.copyFrom = function (src) {
  2992. this.center.copyFrom(src.center);
  2993. this.radius = src.radius;
  2994. this.extent.copyFrom(src.extent);
  2995. this._worldAABBDirty = true;
  2996. };
  2997. BoundingInfo2D.prototype.equals = function (other) {
  2998. if (!other) {
  2999. return false;
  3000. }
  3001. return other.center.equals(this.center) && other.extent.equals(this.extent);
  3002. };
  3003. /**
  3004. * return the max extend of the bounding info
  3005. */
  3006. BoundingInfo2D.prototype.max = function () {
  3007. var r = BABYLON.Vector2.Zero();
  3008. this.maxToRef(r);
  3009. return r;
  3010. };
  3011. /**
  3012. * return the min/max extend of the bounding info.
  3013. * x, y, z, w are left, bottom, right and top
  3014. */
  3015. BoundingInfo2D.prototype.minMax = function () {
  3016. var r = BABYLON.Vector4.Zero();
  3017. this.minMaxToRef(r);
  3018. return r;
  3019. };
  3020. /**
  3021. * Update a vector2 with the max extend of the bounding info
  3022. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  3023. */
  3024. BoundingInfo2D.prototype.maxToRef = function (result) {
  3025. result.x = this.center.x + this.extent.x;
  3026. result.y = this.center.y + this.extent.y;
  3027. };
  3028. /**
  3029. * Update a vector4 with the min/max extend of the bounding info
  3030. * x, y, z, w are left, bottom, right and top
  3031. * @param result must be a valid/allocated vector4 that will contain the result of the operation
  3032. */
  3033. BoundingInfo2D.prototype.minMaxToRef = function (result) {
  3034. result.x = this.center.x - this.extent.x;
  3035. result.y = this.center.y - this.extent.y;
  3036. result.z = this.center.x + this.extent.x;
  3037. result.w = this.center.y + this.extent.y;
  3038. };
  3039. /**
  3040. * Return the size of the boundingInfo rect surface
  3041. */
  3042. BoundingInfo2D.prototype.size = function () {
  3043. var r = BABYLON.Size.Zero();
  3044. this.sizeToRef(r);
  3045. return r;
  3046. };
  3047. /**
  3048. * Stores in the result object the size of the boundingInfo rect surface
  3049. * @param result
  3050. */
  3051. BoundingInfo2D.prototype.sizeToRef = function (result) {
  3052. result.width = this.extent.x * 2;
  3053. result.height = this.extent.y * 2;
  3054. };
  3055. /**
  3056. * Inflate the boundingInfo with the given vector
  3057. * @param offset the extent will be incremented with offset and the radius will be computed again
  3058. */
  3059. BoundingInfo2D.prototype.inflate = function (offset) {
  3060. this.extent.addInPlace(offset);
  3061. this.radius = this.extent.length();
  3062. };
  3063. /**
  3064. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  3065. * @param matrix the transformation matrix to apply
  3066. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  3067. */
  3068. BoundingInfo2D.prototype.transform = function (matrix) {
  3069. var r = new BoundingInfo2D();
  3070. this.transformToRef(matrix, r);
  3071. return r;
  3072. };
  3073. /**
  3074. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  3075. * @param other the second BoundingInfo2D to compute the union with this one
  3076. * @return a new instance containing the result of the union
  3077. */
  3078. BoundingInfo2D.prototype.union = function (other) {
  3079. var r = new BoundingInfo2D();
  3080. this.unionToRef(other, r);
  3081. return r;
  3082. };
  3083. BoundingInfo2D.prototype.worldAABBIntersectionTest = function (other) {
  3084. var a = this.worldAABB;
  3085. var b = other.worldAABB;
  3086. return b.z >= a.x && b.x <= a.z && b.w >= a.y && b.y <= a.w;
  3087. };
  3088. /**
  3089. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  3090. * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
  3091. * @param matrix The matrix to use to compute the transformation
  3092. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  3093. */
  3094. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  3095. // Construct a bounding box based on the extent values
  3096. var p = BoundingInfo2D._transform;
  3097. p[0].x = this.center.x + this.extent.x;
  3098. p[0].y = this.center.y + this.extent.y;
  3099. p[1].x = this.center.x + this.extent.x;
  3100. p[1].y = this.center.y - this.extent.y;
  3101. p[2].x = this.center.x - this.extent.x;
  3102. p[2].y = this.center.y - this.extent.y;
  3103. p[3].x = this.center.x - this.extent.x;
  3104. p[3].y = this.center.y + this.extent.y;
  3105. // Transform the four points of the bounding box with the matrix
  3106. for (var i = 0; i < 4; i++) {
  3107. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  3108. }
  3109. BoundingInfo2D.CreateFromPointsToRef(p, result);
  3110. };
  3111. BoundingInfo2D.prototype._updateWorldAABB = function (worldMatrix) {
  3112. // Construct a bounding box based on the extent values
  3113. var p = BoundingInfo2D._transform;
  3114. p[0].x = this.center.x + this.extent.x;
  3115. p[0].y = this.center.y + this.extent.y;
  3116. p[1].x = this.center.x + this.extent.x;
  3117. p[1].y = this.center.y - this.extent.y;
  3118. p[2].x = this.center.x - this.extent.x;
  3119. p[2].y = this.center.y - this.extent.y;
  3120. p[3].x = this.center.x - this.extent.x;
  3121. p[3].y = this.center.y + this.extent.y;
  3122. // Transform the four points of the bounding box with the matrix
  3123. for (var i = 0; i < 4; i++) {
  3124. BABYLON.Vector2.TransformToRef(p[i], worldMatrix, p[i]);
  3125. }
  3126. this._worldAABB.x = Math.min(Math.min(p[0].x, p[1].x), Math.min(p[2].x, p[3].x));
  3127. this._worldAABB.y = Math.min(Math.min(p[0].y, p[1].y), Math.min(p[2].y, p[3].y));
  3128. this._worldAABB.z = Math.max(Math.max(p[0].x, p[1].x), Math.max(p[2].x, p[3].x));
  3129. this._worldAABB.w = Math.max(Math.max(p[0].y, p[1].y), Math.max(p[2].y, p[3].y));
  3130. };
  3131. Object.defineProperty(BoundingInfo2D.prototype, "worldAABBDirtyObservable", {
  3132. get: function () {
  3133. if (!this._worldAABBDirtyObservable) {
  3134. this._worldAABBDirtyObservable = new BABYLON.Observable();
  3135. }
  3136. return this._worldAABBDirtyObservable;
  3137. },
  3138. enumerable: true,
  3139. configurable: true
  3140. });
  3141. Object.defineProperty(BoundingInfo2D.prototype, "isWorldAABBDirty", {
  3142. get: function () {
  3143. return this._worldAABBDirty;
  3144. },
  3145. enumerable: true,
  3146. configurable: true
  3147. });
  3148. BoundingInfo2D.prototype.dirtyWorldAABB = function () {
  3149. if (this._worldAABBDirty) {
  3150. return;
  3151. }
  3152. this._worldAABBDirty = true;
  3153. if (this._worldAABBDirtyObservable && this._worldAABBDirtyObservable.hasObservers()) {
  3154. this._worldAABBDirtyObservable.notifyObservers(this);
  3155. }
  3156. };
  3157. Object.defineProperty(BoundingInfo2D.prototype, "worldAABB", {
  3158. /**
  3159. * Retrieve the world AABB, the Vector4's data is x=xmin, y=ymin, z=xmax, w=ymax
  3160. */
  3161. get: function () {
  3162. if (this._worldAABBDirty) {
  3163. if (!this.worldMatrixAccess) {
  3164. throw new Error("you must set the worldMatrixAccess function first");
  3165. }
  3166. this._updateWorldAABB(this.worldMatrixAccess());
  3167. this._worldAABBDirty = false;
  3168. }
  3169. return this._worldAABB;
  3170. },
  3171. enumerable: true,
  3172. configurable: true
  3173. });
  3174. /**
  3175. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  3176. * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
  3177. * @param other the second object used to compute the union
  3178. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  3179. */
  3180. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  3181. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  3182. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  3183. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  3184. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  3185. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  3186. };
  3187. /**
  3188. * Check if the given point is inside the BoundingInfo.
  3189. * The test is first made on the radius, then inside the rectangle described by the extent
  3190. * @param pickPosition the position to test
  3191. * @return true if the point is inside, false otherwise
  3192. */
  3193. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  3194. // is it inside the radius?
  3195. var pickLocal = pickPosition.subtract(this.center);
  3196. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  3197. // is it inside the rectangle?
  3198. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  3199. }
  3200. return false;
  3201. };
  3202. return BoundingInfo2D;
  3203. }());
  3204. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  3205. BABYLON.BoundingInfo2D = BoundingInfo2D;
  3206. })(BABYLON || (BABYLON = {}));
  3207. //# sourceMappingURL=babylon.bounding2d.js.map
  3208. var __extends = (this && this.__extends) || function (d, b) {
  3209. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3210. function __() { this.constructor = d; }
  3211. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3212. };
  3213. var BABYLON;
  3214. (function (BABYLON) {
  3215. /**
  3216. * The base class for all implementation of a Primitive Collision Manager
  3217. */
  3218. var PrimitiveCollisionManagerBase = (function () {
  3219. function PrimitiveCollisionManagerBase(owner) {
  3220. this._owner = owner;
  3221. }
  3222. PrimitiveCollisionManagerBase.allocBasicPCM = function (owner, enableBorders) {
  3223. return new BasicPrimitiveCollisionManager(owner, enableBorders);
  3224. };
  3225. return PrimitiveCollisionManagerBase;
  3226. }());
  3227. BABYLON.PrimitiveCollisionManagerBase = PrimitiveCollisionManagerBase;
  3228. /**
  3229. * Base class of an Actor
  3230. */
  3231. var ActorInfoBase = (function () {
  3232. function ActorInfoBase() {
  3233. }
  3234. return ActorInfoBase;
  3235. }());
  3236. BABYLON.ActorInfoBase = ActorInfoBase;
  3237. var ActorInfo = (function (_super) {
  3238. __extends(ActorInfo, _super);
  3239. function ActorInfo(owner, actor, deep) {
  3240. var _this = _super.call(this) || this;
  3241. _this.owner = owner;
  3242. _this.prim = actor;
  3243. _this.flags = 0;
  3244. _this.presentInClusters = new BABYLON.StringDictionary();
  3245. _this.intersectWith = new BABYLON.ObservableStringDictionary(false);
  3246. _this.setFlags((deep ? ActorInfo.flagDeep : 0) | ActorInfo.flagDirty);
  3247. var bi = (deep ? actor.boundingInfo : actor.levelBoundingInfo);
  3248. // Dirty Actor if its WorldAABB changed
  3249. bi.worldAABBDirtyObservable.add(function (e, d) {
  3250. _this.owner.actorDirty(_this);
  3251. });
  3252. // Dirty Actor if it's getting enabled/disabled
  3253. actor.propertyChanged.add(function (e, d) {
  3254. if (d.mask === -1) {
  3255. return;
  3256. }
  3257. _this.setFlagsValue(ActorInfo.flagEnabled, e.newValue === true);
  3258. _this.owner.actorDirty(_this);
  3259. }, BABYLON.Prim2DBase.isVisibleProperty.flagId);
  3260. return _this;
  3261. }
  3262. ActorInfo.prototype.setFlags = function (flags) {
  3263. this.flags |= flags;
  3264. };
  3265. ActorInfo.prototype.clearFlags = function (flags) {
  3266. this.flags &= ~flags;
  3267. };
  3268. ActorInfo.prototype.isAllFlagsSet = function (flags) {
  3269. return (this.flags & flags) === flags;
  3270. };
  3271. ActorInfo.prototype.isSomeFlagsSet = function (flags) {
  3272. return (this.flags & flags) !== 0;
  3273. };
  3274. ActorInfo.prototype.setFlagsValue = function (flags, value) {
  3275. if (value) {
  3276. this.flags |= flags;
  3277. }
  3278. else {
  3279. this.flags &= ~flags;
  3280. }
  3281. };
  3282. Object.defineProperty(ActorInfo.prototype, "worldAABB", {
  3283. get: function () {
  3284. return (this.isSomeFlagsSet(ActorInfo.flagDeep) ? this.prim.boundingInfo : this.prim.levelBoundingInfo).worldAABB;
  3285. },
  3286. enumerable: true,
  3287. configurable: true
  3288. });
  3289. Object.defineProperty(ActorInfo.prototype, "isEnabled", {
  3290. get: function () {
  3291. return this.isSomeFlagsSet(ActorInfo.flagEnabled);
  3292. },
  3293. enumerable: true,
  3294. configurable: true
  3295. });
  3296. Object.defineProperty(ActorInfo.prototype, "isDeep", {
  3297. get: function () {
  3298. return this.isSomeFlagsSet(ActorInfo.flagDeep);
  3299. },
  3300. enumerable: true,
  3301. configurable: true
  3302. });
  3303. Object.defineProperty(ActorInfo.prototype, "isDirty", {
  3304. get: function () {
  3305. return this.isSomeFlagsSet(ActorInfo.flagDirty);
  3306. },
  3307. enumerable: true,
  3308. configurable: true
  3309. });
  3310. Object.defineProperty(ActorInfo.prototype, "isRemoved", {
  3311. get: function () {
  3312. return this.isSomeFlagsSet(ActorInfo.flagRemoved);
  3313. },
  3314. enumerable: true,
  3315. configurable: true
  3316. });
  3317. return ActorInfo;
  3318. }(ActorInfoBase));
  3319. ActorInfo.flagDeep = 0x0001; // set if the actor boundingInfo must be used instead of the levelBoundingInfo
  3320. ActorInfo.flagEnabled = 0x0002; // set if the actor is enabled and should be considered for intersection tests
  3321. ActorInfo.flagDirty = 0x0004; // set if the actor's AABB is dirty
  3322. ActorInfo.flagRemoved = 0x0008; // set if the actor was removed from the PCM
  3323. var ClusterInfo = (function () {
  3324. function ClusterInfo() {
  3325. this.actors = new BABYLON.StringDictionary();
  3326. }
  3327. ClusterInfo.prototype.clear = function () {
  3328. this.actors.clear();
  3329. };
  3330. return ClusterInfo;
  3331. }());
  3332. var BasicPrimitiveCollisionManager = (function (_super) {
  3333. __extends(BasicPrimitiveCollisionManager, _super);
  3334. function BasicPrimitiveCollisionManager(owner, enableBorders) {
  3335. var _this = _super.call(this, owner) || this;
  3336. _this._actors = new BABYLON.StringDictionary();
  3337. _this._dirtyActors = new BABYLON.StringDictionary();
  3338. _this._clusters = null;
  3339. _this._maxActorByCluster = 0;
  3340. _this._AABBRenderPrim = null;
  3341. _this._canvasSize = BABYLON.Size.Zero();
  3342. _this._ClusterRenderPrim = null;
  3343. _this._debugTextBackground = null;
  3344. _this._clusterDirty = true;
  3345. _this._clusterSize = new BABYLON.Size(2, 2);
  3346. _this._clusterStep = BABYLON.Vector2.Zero();
  3347. _this._lastClusterResizeCounter = 0;
  3348. _this._freeClusters = new Array();
  3349. _this._enableBorder = enableBorders;
  3350. _this._debugUpdateOpCount = new BABYLON.PerfCounter();
  3351. _this._debugUpdateTime = new BABYLON.PerfCounter();
  3352. _this._intersectedActors = new BABYLON.ObservableStringDictionary(false);
  3353. _this._borderIntersecteddActors = new Array(4);
  3354. for (var j = 0; j < 4; j++) {
  3355. _this._borderIntersecteddActors[j] = new BABYLON.ObservableStringDictionary(false);
  3356. }
  3357. var flagId = BABYLON.Canvas2D.actualSizeProperty.flagId;
  3358. if (!BasicPrimitiveCollisionManager.WAABBCorners) {
  3359. BasicPrimitiveCollisionManager.WAABBCorners = new Array(4);
  3360. for (var i = 0; i < 4; i++) {
  3361. BasicPrimitiveCollisionManager.WAABBCorners[i] = BABYLON.Vector2.Zero();
  3362. }
  3363. BasicPrimitiveCollisionManager.WAABBCornersCluster = new Array(4);
  3364. for (var i = 0; i < 4; i++) {
  3365. BasicPrimitiveCollisionManager.WAABBCornersCluster[i] = BABYLON.Vector2.Zero();
  3366. }
  3367. }
  3368. owner.propertyChanged.add(function (e, d) {
  3369. if (d.mask === -1) {
  3370. return;
  3371. }
  3372. _this._clusterDirty = true;
  3373. console.log("canvas size changed");
  3374. }, flagId);
  3375. _this.debugRenderAABB = false;
  3376. _this.debugRenderClusters = false;
  3377. _this.debugStats = false;
  3378. return _this;
  3379. }
  3380. BasicPrimitiveCollisionManager.prototype._addActor = function (actor, deep) {
  3381. var _this = this;
  3382. return this._actors.getOrAddWithFactory(actor.uid, function () {
  3383. var ai = new ActorInfo(_this, actor, deep);
  3384. _this.actorDirty(ai);
  3385. return ai;
  3386. });
  3387. };
  3388. BasicPrimitiveCollisionManager.prototype._removeActor = function (actor) {
  3389. var ai = this._actors.getAndRemove(actor.uid);
  3390. ai.setFlags(ActorInfo.flagRemoved);
  3391. this.actorDirty(ai);
  3392. };
  3393. BasicPrimitiveCollisionManager.prototype.actorDirty = function (actor) {
  3394. actor.setFlags(ActorInfo.flagDirty);
  3395. this._dirtyActors.add(actor.prim.uid, actor);
  3396. };
  3397. BasicPrimitiveCollisionManager.prototype._update = function () {
  3398. this._canvasSize.copyFrom(this._owner.actualSize);
  3399. // Should we update the WireFrame2D Primitive that displays the WorldAABB ?
  3400. if (this.debugRenderAABB) {
  3401. if (this._dirtyActors.count > 0 || this._debugRenderAABBDirty) {
  3402. this._updateAABBDisplay();
  3403. }
  3404. }
  3405. if (this._AABBRenderPrim) {
  3406. this._AABBRenderPrim.levelVisible = this.debugRenderAABB;
  3407. }
  3408. var cw = this._clusterSize.width;
  3409. var ch = this._clusterSize.height;
  3410. // Check for Cluster resize
  3411. if (((this._clusterSize.width < 16 && this._clusterSize.height < 16 && this._maxActorByCluster >= 10) ||
  3412. (this._clusterSize.width > 2 && this._clusterSize.height > 2 && this._maxActorByCluster <= 7)) &&
  3413. this._lastClusterResizeCounter > 100) {
  3414. if (this._maxActorByCluster >= 10) {
  3415. ++cw;
  3416. ++ch;
  3417. }
  3418. else {
  3419. --cw;
  3420. --ch;
  3421. }
  3422. console.log("Change cluster size to " + cw + ":" + ch + ", max actor " + this._maxActorByCluster);
  3423. this._clusterDirty = true;
  3424. }
  3425. // Should we update the WireFrame2D Primitive that displays the clusters
  3426. if (this.debugRenderClusters && this._clusterDirty) {
  3427. this._updateClusterDisplay(cw, ch);
  3428. }
  3429. if (this._ClusterRenderPrim) {
  3430. this._ClusterRenderPrim.levelVisible = this.debugRenderClusters;
  3431. }
  3432. var updateStats = this.debugStats && (this._dirtyActors.count > 0 || this._clusterDirty);
  3433. this._debugUpdateTime.beginMonitoring();
  3434. // If the Cluster Size changed: rebuild it and add all actors. Otherwise add only new (dirty) actors
  3435. if (this._clusterDirty) {
  3436. this._initializeCluster(cw, ch);
  3437. this._rebuildAllActors();
  3438. }
  3439. else {
  3440. this._rebuildDirtyActors();
  3441. ++this._lastClusterResizeCounter;
  3442. }
  3443. // Proceed to the collision detection between primitives
  3444. this._collisionDetection();
  3445. this._debugUpdateTime.endMonitoring();
  3446. if (updateStats) {
  3447. this._updateDebugStats();
  3448. }
  3449. if (this._debugTextBackground) {
  3450. this._debugTextBackground.levelVisible = updateStats;
  3451. }
  3452. // Reset the dirty actor list: everything is processed
  3453. this._dirtyActors.clear();
  3454. };
  3455. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "debugRenderAABB", {
  3456. /**
  3457. * Renders the World AABB of all Actors
  3458. */
  3459. get: function () {
  3460. return this._debugRenderAABB;
  3461. },
  3462. set: function (val) {
  3463. if (this._debugRenderAABB === val) {
  3464. return;
  3465. }
  3466. this._debugRenderAABB = val;
  3467. this._debugRenderAABBDirty = true;
  3468. },
  3469. enumerable: true,
  3470. configurable: true
  3471. });
  3472. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "intersectedActors", {
  3473. get: function () {
  3474. return this._intersectedActors;
  3475. },
  3476. enumerable: true,
  3477. configurable: true
  3478. });
  3479. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "leftBorderIntersectedActors", {
  3480. get: function () {
  3481. return this._borderIntersecteddActors[0];
  3482. },
  3483. enumerable: true,
  3484. configurable: true
  3485. });
  3486. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "bottomBorderIntersectedActors", {
  3487. get: function () {
  3488. return this._borderIntersecteddActors[1];
  3489. },
  3490. enumerable: true,
  3491. configurable: true
  3492. });
  3493. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "rightBorderIntersectedActors", {
  3494. get: function () {
  3495. return this._borderIntersecteddActors[2];
  3496. },
  3497. enumerable: true,
  3498. configurable: true
  3499. });
  3500. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "topBorderIntersectedActors", {
  3501. get: function () {
  3502. return this._borderIntersecteddActors[3];
  3503. },
  3504. enumerable: true,
  3505. configurable: true
  3506. });
  3507. BasicPrimitiveCollisionManager.prototype._initializeCluster = function (countW, countH) {
  3508. // Check for free
  3509. if (this._clusters) {
  3510. for (var w = 0; w < this._clusterSize.height; w++) {
  3511. for (var h = 0; h < this._clusterSize.width; h++) {
  3512. this._freeClusterInfo(this._clusters[w][h]);
  3513. }
  3514. }
  3515. }
  3516. // Allocate
  3517. this._clusterSize.copyFromFloats(countW, countH);
  3518. this._clusters = [];
  3519. for (var w = 0; w < this._clusterSize.height; w++) {
  3520. this._clusters[w] = [];
  3521. for (var h = 0; h < this._clusterSize.width; h++) {
  3522. var ci = this._allocClusterInfo();
  3523. this._clusters[w][h] = ci;
  3524. }
  3525. }
  3526. this._clusterStep.copyFromFloats(this._owner.actualWidth / countW, this._owner.actualHeight / countH);
  3527. this._maxActorByCluster = 0;
  3528. this._lastClusterResizeCounter = 0;
  3529. this._clusterDirty = false;
  3530. };
  3531. BasicPrimitiveCollisionManager.prototype._rebuildAllActors = function () {
  3532. var _this = this;
  3533. this._actors.forEach(function (k, ai) {
  3534. _this._processActor(ai);
  3535. });
  3536. };
  3537. BasicPrimitiveCollisionManager.prototype._rebuildDirtyActors = function () {
  3538. var _this = this;
  3539. this._dirtyActors.forEach(function (k, ai) {
  3540. _this._processActor(ai);
  3541. });
  3542. };
  3543. BasicPrimitiveCollisionManager.prototype._processActor = function (actor) {
  3544. var _this = this;
  3545. // Check if the actor is being disabled or removed
  3546. if (!actor.isEnabled || actor.isRemoved) {
  3547. actor.presentInClusters.forEach(function (k, ci) {
  3548. ci.actors.remove(actor.prim.uid);
  3549. });
  3550. actor.presentInClusters.clear();
  3551. return;
  3552. }
  3553. var wab = actor.worldAABB;
  3554. // Build the worldAABB corners
  3555. var wac = BasicPrimitiveCollisionManager.WAABBCorners;
  3556. wac[0].copyFromFloats(wab.x, wab.y); // Bottom/Left
  3557. wac[1].copyFromFloats(wab.z, wab.y); // Bottom/Right
  3558. wac[2].copyFromFloats(wab.z, wab.w); // Top/Right
  3559. wac[3].copyFromFloats(wab.x, wab.w); // Top/Left
  3560. var cs = this._clusterStep;
  3561. var wacc = BasicPrimitiveCollisionManager.WAABBCornersCluster;
  3562. for (var i = 0; i < 4; i++) {
  3563. var p = wac[i];
  3564. var cx = (p.x - (p.x % cs.x)) / cs.x;
  3565. var cy = (p.y - (p.y % cs.y)) / cs.y;
  3566. wacc[i].copyFromFloats(Math.floor(cx), Math.floor(cy));
  3567. }
  3568. var opCount = 0;
  3569. var totalClusters = 0;
  3570. var newCI = new Array();
  3571. var sx = Math.max(0, wacc[0].x); // Start Cluster X
  3572. var sy = Math.max(0, wacc[0].y); // Start Cluster Y
  3573. var ex = Math.min(this._clusterSize.width - 1, wacc[2].x); // End Cluster X
  3574. var ey = Math.min(this._clusterSize.height - 1, wacc[2].y); // End Cluster Y
  3575. if (this._enableBorder) {
  3576. if (wac[0].x < 0) {
  3577. this._borderIntersecteddActors[0].add(actor.prim.uid, actor.prim);
  3578. }
  3579. else {
  3580. this._borderIntersecteddActors[0].remove(actor.prim.uid);
  3581. }
  3582. if (wac[0].y < 0) {
  3583. this._borderIntersecteddActors[1].add(actor.prim.uid, actor.prim);
  3584. }
  3585. else {
  3586. this._borderIntersecteddActors[1].remove(actor.prim.uid);
  3587. }
  3588. if (wac[2].x >= this._canvasSize.width) {
  3589. this._borderIntersecteddActors[2].add(actor.prim.uid, actor.prim);
  3590. }
  3591. else {
  3592. this._borderIntersecteddActors[2].remove(actor.prim.uid);
  3593. }
  3594. if (wac[2].y >= this._canvasSize.height) {
  3595. this._borderIntersecteddActors[3].add(actor.prim.uid, actor.prim);
  3596. }
  3597. else {
  3598. this._borderIntersecteddActors[3].remove(actor.prim.uid);
  3599. }
  3600. }
  3601. for (var y = sy; y <= ey; y++) {
  3602. var _loop_1 = function (x) {
  3603. var k = x + ":" + y;
  3604. var cx = x, cy = y;
  3605. var ci = actor.presentInClusters.getOrAddWithFactory(k, function (k) {
  3606. var nci = _this._getCluster(cx, cy);
  3607. nci.actors.add(actor.prim.uid, actor);
  3608. _this._maxActorByCluster = Math.max(_this._maxActorByCluster, nci.actors.count);
  3609. ++opCount;
  3610. ++totalClusters;
  3611. return nci;
  3612. });
  3613. newCI.push(ci);
  3614. };
  3615. for (var x = sx; x <= ex; x++) {
  3616. _loop_1(x);
  3617. }
  3618. }
  3619. // Check if there were no change
  3620. if (opCount === 0 && actor.presentInClusters.count === totalClusters) {
  3621. return;
  3622. }
  3623. // Build the array of the cluster where the actor is no longer in
  3624. var clusterToRemove = new Array();
  3625. actor.presentInClusters.forEach(function (k, ci) {
  3626. if (newCI.indexOf(ci) === -1) {
  3627. clusterToRemove.push(k);
  3628. // remove the primitive from the Cluster Info object
  3629. ci.actors.remove(actor.prim.uid);
  3630. }
  3631. });
  3632. // Remove these clusters from the actor's dictionary
  3633. for (var _i = 0, clusterToRemove_1 = clusterToRemove; _i < clusterToRemove_1.length; _i++) {
  3634. var key = clusterToRemove_1[_i];
  3635. actor.presentInClusters.remove(key);
  3636. }
  3637. };
  3638. // The algorithm is simple, we have previously partitioned the Actors in the Clusters: each actor has a list of the Cluster(s) it's inside.
  3639. // Then for a given Actor that is dirty we evaluate the intersection with all the other actors present in the same Cluster(s)
  3640. // So it's basically O(n²), BUT only inside a Cluster and only for dirty Actors.
  3641. BasicPrimitiveCollisionManager.prototype._collisionDetection = function () {
  3642. var _this = this;
  3643. var hash = BasicPrimitiveCollisionManager.CandidatesActors;
  3644. var prev = BasicPrimitiveCollisionManager.PreviousIntersections;
  3645. var opCount = 0;
  3646. this._dirtyActors.forEach(function (k1, ai1) {
  3647. ++opCount;
  3648. // Build the list of candidates
  3649. hash.clear();
  3650. ai1.presentInClusters.forEach(function (k, ci) {
  3651. ++opCount;
  3652. ci.actors.forEach(function (k, v) { return hash.add(k, v); });
  3653. });
  3654. var wab1 = ai1.worldAABB;
  3655. // Save the previous intersections
  3656. prev.clear();
  3657. prev.copyFrom(ai1.intersectWith);
  3658. ai1.intersectWith.clear();
  3659. // For each candidate
  3660. hash.forEach(function (k2, ai2) {
  3661. ++opCount;
  3662. // Check if we're testing against itself
  3663. if (k1 === k2) {
  3664. return;
  3665. }
  3666. var wab2 = ai2.worldAABB;
  3667. if (wab2.z >= wab1.x && wab2.x <= wab1.z && wab2.w >= wab1.y && wab2.y <= wab1.w) {
  3668. if (ai1.prim.intersectOtherPrim(ai2.prim)) {
  3669. ++opCount;
  3670. ai1.intersectWith.add(k2, ai2);
  3671. if (k1 < k2) {
  3672. _this._intersectedActors.add(k1 + ";" + k2, { a: ai1.prim, b: ai2.prim });
  3673. }
  3674. else {
  3675. _this._intersectedActors.add(k2 + ";" + k1, { a: ai2.prim, b: ai1.prim });
  3676. }
  3677. }
  3678. }
  3679. });
  3680. // Check and remove the associations that no longer exist in the main intersection list
  3681. prev.forEach(function (k, ai) {
  3682. if (!ai1.intersectWith.contains(k)) {
  3683. ++opCount;
  3684. _this._intersectedActors.remove((k < k1 ? k : k1) + ";" + (k < k1 ? k1 : k));
  3685. }
  3686. });
  3687. });
  3688. this._debugUpdateOpCount.fetchNewFrame();
  3689. this._debugUpdateOpCount.addCount(opCount, true);
  3690. };
  3691. BasicPrimitiveCollisionManager.prototype._getCluster = function (x, y) {
  3692. return this._clusters[x][y];
  3693. };
  3694. BasicPrimitiveCollisionManager.prototype._updateDebugStats = function () {
  3695. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  3696. var txt = "Primitive Collision Stats\n" +
  3697. (" - PCM Execution Time: " + format(this._debugUpdateTime.lastSecAverage) + "ms\n") +
  3698. (" - Operation Count: " + format(this._debugUpdateOpCount.current) + ", (avg:" + format(this._debugUpdateOpCount.lastSecAverage) + ", t:" + format(this._debugUpdateOpCount.total) + ")\n") +
  3699. (" - Max Actor per Cluster: " + this._maxActorByCluster + "\n") +
  3700. (" - Intersections count: " + this.intersectedActors.count);
  3701. if (!this._debugTextBackground) {
  3702. this._debugTextBackground = new BABYLON.Rectangle2D({
  3703. id: "###DEBUG PMC STATS###", parent: this._owner, marginAlignment: "h: left, v: top", fill: "#C0404080", padding: "10", margin: "10", roundRadius: 10, children: [
  3704. new BABYLON.Text2D(txt, { id: "###DEBUG PMC TEXT###", fontName: "12pt Lucida Console" })
  3705. ]
  3706. });
  3707. }
  3708. else {
  3709. this._debugTextBackground.levelVisible = true;
  3710. var text2d = this._debugTextBackground.children[0];
  3711. text2d.text = txt;
  3712. }
  3713. };
  3714. BasicPrimitiveCollisionManager.prototype._updateAABBDisplay = function () {
  3715. var g = new BABYLON.WireFrameGroup2D("main", new BABYLON.Color4(0.5, 0.8, 1.0, 1.0));
  3716. var v = BABYLON.Vector2.Zero();
  3717. this._actors.forEach(function (k, ai) {
  3718. if (ai.isEnabled) {
  3719. var ab = ai.worldAABB;
  3720. v.x = ab.x;
  3721. v.y = ab.y;
  3722. g.startLineStrip(v);
  3723. v.x = ab.z;
  3724. g.pushVertex(v);
  3725. v.y = ab.w;
  3726. g.pushVertex(v);
  3727. v.x = ab.x;
  3728. g.pushVertex(v);
  3729. v.y = ab.y;
  3730. g.endLineStrip(v);
  3731. }
  3732. });
  3733. if (!this._AABBRenderPrim) {
  3734. this._AABBRenderPrim = new BABYLON.WireFrame2D([g], { parent: this._owner, alignToPixel: false, id: "###DEBUG PCM AABB###" });
  3735. }
  3736. else {
  3737. this._AABBRenderPrim.wireFrameGroups.set("main", g);
  3738. this._AABBRenderPrim.wireFrameGroupsDirty();
  3739. }
  3740. this._debugRenderAABBDirty = false;
  3741. };
  3742. BasicPrimitiveCollisionManager.prototype._updateClusterDisplay = function (cw, ch) {
  3743. var g = new BABYLON.WireFrameGroup2D("main", new BABYLON.Color4(0.8, 0.1, 0.5, 1.0));
  3744. var v1 = BABYLON.Vector2.Zero();
  3745. var v2 = BABYLON.Vector2.Zero();
  3746. // Vertical lines
  3747. var step = (this._owner.actualWidth - 1) / cw;
  3748. v1.y = 0;
  3749. v2.y = this._owner.actualHeight;
  3750. for (var x = 0; x <= cw; x++) {
  3751. g.pushVertex(v1);
  3752. g.pushVertex(v2);
  3753. v1.x += step;
  3754. v2.x += step;
  3755. }
  3756. // Horizontal lines
  3757. step = (this._owner.actualHeight - 1) / ch;
  3758. v1.x = v1.y = v2.y = 0;
  3759. v2.x = this._owner.actualWidth;
  3760. for (var y = 0; y <= ch; y++) {
  3761. g.pushVertex(v1);
  3762. g.pushVertex(v2);
  3763. v1.y += step;
  3764. v2.y += step;
  3765. }
  3766. if (!this._ClusterRenderPrim) {
  3767. this._ClusterRenderPrim = new BABYLON.WireFrame2D([g], { parent: this._owner, alignToPixel: true, id: "###DEBUG PCM Clusters###" });
  3768. }
  3769. else {
  3770. this._ClusterRenderPrim.wireFrameGroups.set("main", g);
  3771. this._ClusterRenderPrim.wireFrameGroupsDirty();
  3772. }
  3773. };
  3774. // Basically: we don't want to spend our time playing with the GC each time the Cluster Array is rebuilt, so we keep a list of available
  3775. // ClusterInfo object and we have two method to allocate/free them. This way we always deal with the same objects.
  3776. // The free array never shrink, always grows...For the better...and the worst!
  3777. BasicPrimitiveCollisionManager.prototype._allocClusterInfo = function () {
  3778. if (this._freeClusters.length === 0) {
  3779. for (var i = 0; i < 8; i++) {
  3780. this._freeClusters.push(new ClusterInfo());
  3781. }
  3782. }
  3783. return this._freeClusters.pop();
  3784. };
  3785. BasicPrimitiveCollisionManager.prototype._freeClusterInfo = function (ci) {
  3786. ci.clear();
  3787. this._freeClusters.push(ci);
  3788. };
  3789. return BasicPrimitiveCollisionManager;
  3790. }(PrimitiveCollisionManagerBase));
  3791. BasicPrimitiveCollisionManager.WAABBCorners = null;
  3792. BasicPrimitiveCollisionManager.WAABBCornersCluster = null;
  3793. BasicPrimitiveCollisionManager.CandidatesActors = new BABYLON.StringDictionary();
  3794. BasicPrimitiveCollisionManager.PreviousIntersections = new BABYLON.StringDictionary();
  3795. })(BABYLON || (BABYLON = {}));
  3796. //# sourceMappingURL=babylon.primitiveCollisionManager.js.map
  3797. var __extends = (this && this.__extends) || function (d, b) {
  3798. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3799. function __() { this.constructor = d; }
  3800. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3801. };
  3802. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  3803. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3804. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  3805. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  3806. return c > 3 && r && Object.defineProperty(target, key, r), r;
  3807. };
  3808. var BABYLON;
  3809. (function (BABYLON) {
  3810. var LayoutEngineBase = (function () {
  3811. function LayoutEngineBase() {
  3812. this.layoutDirtyOnPropertyChangedMask = 0;
  3813. }
  3814. LayoutEngineBase.prototype.updateLayout = function (prim) {
  3815. };
  3816. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  3817. get: function () {
  3818. return false;
  3819. },
  3820. enumerable: true,
  3821. configurable: true
  3822. });
  3823. LayoutEngineBase.prototype.isLocked = function () {
  3824. return this._isLocked;
  3825. };
  3826. LayoutEngineBase.prototype.lock = function () {
  3827. if (this._isLocked) {
  3828. return false;
  3829. }
  3830. this._isLocked = true;
  3831. return true;
  3832. };
  3833. return LayoutEngineBase;
  3834. }());
  3835. LayoutEngineBase = __decorate([
  3836. BABYLON.className("LayoutEngineBase", "BABYLON")
  3837. ], LayoutEngineBase);
  3838. BABYLON.LayoutEngineBase = LayoutEngineBase;
  3839. var CanvasLayoutEngine = CanvasLayoutEngine_1 = (function (_super) {
  3840. __extends(CanvasLayoutEngine, _super);
  3841. function CanvasLayoutEngine() {
  3842. var _this = _super.call(this) || this;
  3843. _this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId | BABYLON.Prim2DBase.actualSizeProperty.flagId;
  3844. return _this;
  3845. }
  3846. Object.defineProperty(CanvasLayoutEngine, "Singleton", {
  3847. get: function () {
  3848. if (!CanvasLayoutEngine_1._singleton) {
  3849. CanvasLayoutEngine_1._singleton = new CanvasLayoutEngine_1();
  3850. }
  3851. return CanvasLayoutEngine_1._singleton;
  3852. },
  3853. enumerable: true,
  3854. configurable: true
  3855. });
  3856. // A very simple (no) layout computing...
  3857. // The Canvas and its direct children gets the Canvas' size as Layout Area
  3858. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  3859. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  3860. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  3861. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  3862. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  3863. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  3864. var child = _a[_i];
  3865. this._doUpdate(child);
  3866. }
  3867. }
  3868. };
  3869. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  3870. // Canvas ?
  3871. if (prim instanceof BABYLON.Canvas2D) {
  3872. prim.layoutArea = prim.actualSize; //.multiplyByFloats(prim.scaleX, prim.scaleY);
  3873. }
  3874. else if (prim.parent instanceof BABYLON.Canvas2D) {
  3875. prim.layoutArea = prim.owner.actualSize; //.multiplyByFloats(prim.owner.scaleX, prim.owner.scaleY);
  3876. }
  3877. else {
  3878. var contentArea = prim.parent.contentArea;
  3879. // Can be null if the parent's content area depend of its children, the computation will be done in many passes
  3880. if (contentArea) {
  3881. prim.layoutArea = contentArea;
  3882. }
  3883. }
  3884. };
  3885. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  3886. get: function () {
  3887. return true;
  3888. },
  3889. enumerable: true,
  3890. configurable: true
  3891. });
  3892. return CanvasLayoutEngine;
  3893. }(LayoutEngineBase));
  3894. CanvasLayoutEngine._singleton = null;
  3895. __decorate([
  3896. BABYLON.logMethod()
  3897. ], CanvasLayoutEngine.prototype, "updateLayout", null);
  3898. __decorate([
  3899. BABYLON.logMethod()
  3900. ], CanvasLayoutEngine.prototype, "_doUpdate", null);
  3901. CanvasLayoutEngine = CanvasLayoutEngine_1 = __decorate([
  3902. BABYLON.className("CanvasLayoutEngine", "BABYLON")
  3903. ], CanvasLayoutEngine);
  3904. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  3905. var StackPanelLayoutEngine = StackPanelLayoutEngine_1 = (function (_super) {
  3906. __extends(StackPanelLayoutEngine, _super);
  3907. function StackPanelLayoutEngine() {
  3908. var _this = _super.call(this) || this;
  3909. _this._isHorizontal = true;
  3910. _this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId | BABYLON.Prim2DBase.actualSizeProperty.flagId;
  3911. return _this;
  3912. }
  3913. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  3914. get: function () {
  3915. if (!StackPanelLayoutEngine_1._horizontal) {
  3916. StackPanelLayoutEngine_1._horizontal = new StackPanelLayoutEngine_1();
  3917. StackPanelLayoutEngine_1._horizontal.isHorizontal = true;
  3918. StackPanelLayoutEngine_1._horizontal.lock();
  3919. }
  3920. return StackPanelLayoutEngine_1._horizontal;
  3921. },
  3922. enumerable: true,
  3923. configurable: true
  3924. });
  3925. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  3926. get: function () {
  3927. if (!StackPanelLayoutEngine_1._vertical) {
  3928. StackPanelLayoutEngine_1._vertical = new StackPanelLayoutEngine_1();
  3929. StackPanelLayoutEngine_1._vertical.isHorizontal = false;
  3930. StackPanelLayoutEngine_1._vertical.lock();
  3931. }
  3932. return StackPanelLayoutEngine_1._vertical;
  3933. },
  3934. enumerable: true,
  3935. configurable: true
  3936. });
  3937. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  3938. get: function () {
  3939. return this._isHorizontal;
  3940. },
  3941. set: function (val) {
  3942. if (this.isLocked()) {
  3943. return;
  3944. }
  3945. this._isHorizontal = val;
  3946. },
  3947. enumerable: true,
  3948. configurable: true
  3949. });
  3950. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  3951. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  3952. var primLayoutArea = prim.layoutArea;
  3953. var isSizeAuto = prim.isSizeAuto;
  3954. // If we're not in autoSize the layoutArea of the prim having the stack panel must be computed in order for us to compute the children' position.
  3955. // If there's at least one auto size (Horizontal or Vertical) we will have to figure the layoutArea ourselves
  3956. if (!primLayoutArea && !isSizeAuto) {
  3957. return;
  3958. }
  3959. // console.log("Compute Stack Panel Layout " + ++StackPanelLayoutEngine.computeCounter);
  3960. var x = 0;
  3961. var y = 0;
  3962. var horizonStackPanel = this.isHorizontal;
  3963. // If the stack panel is horizontal we check if the primitive height is auto or not, if it's auto then we have to compute the required height, otherwise we just take the actualHeight. If the stack panel is vertical we do the same but with width
  3964. var max = 0;
  3965. var stackPanelLayoutArea = StackPanelLayoutEngine_1.stackPanelLayoutArea;
  3966. if (horizonStackPanel) {
  3967. if (prim.isVerticalSizeAuto) {
  3968. max = 0;
  3969. stackPanelLayoutArea.height = 0;
  3970. }
  3971. else {
  3972. max = prim.layoutArea.height;
  3973. stackPanelLayoutArea.height = prim.layoutArea.height;
  3974. stackPanelLayoutArea.width = 0;
  3975. }
  3976. }
  3977. else {
  3978. if (prim.isHorizontalSizeAuto) {
  3979. max = 0;
  3980. stackPanelLayoutArea.width = 0;
  3981. }
  3982. else {
  3983. max = prim.layoutArea.width;
  3984. stackPanelLayoutArea.width = prim.layoutArea.width;
  3985. stackPanelLayoutArea.height = 0;
  3986. }
  3987. }
  3988. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  3989. var child = _a[_i];
  3990. if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  3991. continue;
  3992. }
  3993. if (child._hasMargin) {
  3994. // Calling computeWithAlignment will return us the area taken by "child" which is its layoutArea
  3995. // We also have the dstOffset which will give us the y position in horizontal mode or x position in vertical mode.
  3996. // The alignment offset on the other axis is simply ignored as it doesn't make any sense (e.g. horizontal alignment is ignored in horizontal mode)
  3997. child.margin.computeWithAlignment(stackPanelLayoutArea, child.actualSize, child.marginAlignment, child.actualScale, StackPanelLayoutEngine_1.dstOffset, StackPanelLayoutEngine_1.dstArea, true);
  3998. child.layoutArea = StackPanelLayoutEngine_1.dstArea;
  3999. }
  4000. else {
  4001. child.margin.computeArea(child.actualSize, child.actualScale, StackPanelLayoutEngine_1.dstArea);
  4002. child.layoutArea = StackPanelLayoutEngine_1.dstArea;
  4003. }
  4004. max = Math.max(max, horizonStackPanel ? StackPanelLayoutEngine_1.dstArea.height : StackPanelLayoutEngine_1.dstArea.width);
  4005. }
  4006. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  4007. var child = _c[_b];
  4008. if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  4009. continue;
  4010. }
  4011. var layoutArea = child.layoutArea;
  4012. if (horizonStackPanel) {
  4013. child.layoutAreaPos = new BABYLON.Vector2(x, 0);
  4014. x += layoutArea.width;
  4015. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  4016. }
  4017. else {
  4018. child.layoutAreaPos = new BABYLON.Vector2(0, y);
  4019. y += layoutArea.height;
  4020. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  4021. }
  4022. }
  4023. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  4024. }
  4025. };
  4026. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  4027. get: function () {
  4028. return false;
  4029. },
  4030. enumerable: true,
  4031. configurable: true
  4032. });
  4033. return StackPanelLayoutEngine;
  4034. }(LayoutEngineBase));
  4035. StackPanelLayoutEngine._horizontal = null;
  4036. StackPanelLayoutEngine._vertical = null;
  4037. StackPanelLayoutEngine.stackPanelLayoutArea = BABYLON.Size.Zero();
  4038. StackPanelLayoutEngine.dstOffset = BABYLON.Vector4.Zero();
  4039. StackPanelLayoutEngine.dstArea = BABYLON.Size.Zero();
  4040. StackPanelLayoutEngine.computeCounter = 0;
  4041. StackPanelLayoutEngine = StackPanelLayoutEngine_1 = __decorate([
  4042. BABYLON.className("StackPanelLayoutEngine", "BABYLON")
  4043. ], StackPanelLayoutEngine);
  4044. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  4045. /**
  4046. * GridData is used specify what row(s) and column(s) a primitive is placed in when its parent is using a Grid Panel Layout.
  4047. */
  4048. var GridData = (function () {
  4049. /**
  4050. * Create a Grid Data that describes where a primitive will be placed in a Grid Panel Layout.
  4051. * @param row the row number of the grid
  4052. * @param column the column number of the grid
  4053. * @param rowSpan the number of rows a primitive will occupy
  4054. * @param columnSpan the number of columns a primitive will occupy
  4055. **/
  4056. function GridData(row, column, rowSpan, columnSpan) {
  4057. this.row = row;
  4058. this.column = column;
  4059. this.rowSpan = (rowSpan == null) ? 1 : rowSpan;
  4060. this.columnSpan = (columnSpan == null) ? 1 : columnSpan;
  4061. }
  4062. return GridData;
  4063. }());
  4064. BABYLON.GridData = GridData;
  4065. var GridDimensionDefinition = (function () {
  4066. function GridDimensionDefinition() {
  4067. }
  4068. GridDimensionDefinition.prototype._parse = function (value, res) {
  4069. var v = value.toLocaleLowerCase().trim();
  4070. if (v.indexOf("auto") === 0) {
  4071. res(null, null, GridDimensionDefinition.Auto);
  4072. }
  4073. else if (v.indexOf("*") !== -1) {
  4074. var i = v.indexOf("*");
  4075. var w = 1;
  4076. if (i > 0) {
  4077. w = parseFloat(v.substr(0, i));
  4078. }
  4079. res(w, null, GridDimensionDefinition.Stars);
  4080. }
  4081. else {
  4082. var w = parseFloat(v);
  4083. res(w, w, GridDimensionDefinition.Pixels);
  4084. }
  4085. };
  4086. return GridDimensionDefinition;
  4087. }());
  4088. GridDimensionDefinition.Pixels = 1;
  4089. GridDimensionDefinition.Stars = 2;
  4090. GridDimensionDefinition.Auto = 3;
  4091. var RowDefinition = (function (_super) {
  4092. __extends(RowDefinition, _super);
  4093. function RowDefinition() {
  4094. return _super.apply(this, arguments) || this;
  4095. }
  4096. return RowDefinition;
  4097. }(GridDimensionDefinition));
  4098. var ColumnDefinition = (function (_super) {
  4099. __extends(ColumnDefinition, _super);
  4100. function ColumnDefinition() {
  4101. return _super.apply(this, arguments) || this;
  4102. }
  4103. return ColumnDefinition;
  4104. }(GridDimensionDefinition));
  4105. var GridPanelLayoutEngine = GridPanelLayoutEngine_1 = (function (_super) {
  4106. __extends(GridPanelLayoutEngine, _super);
  4107. function GridPanelLayoutEngine(settings) {
  4108. var _this = _super.call(this) || this;
  4109. _this._children = [];
  4110. _this._rowBottoms = [];
  4111. _this._columnLefts = [];
  4112. _this._rowHeights = [];
  4113. _this._columnWidths = [];
  4114. _this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId | BABYLON.Prim2DBase.actualSizeProperty.flagId;
  4115. _this._rows = new Array();
  4116. _this._columns = new Array();
  4117. if (settings.rows) {
  4118. var _loop_1 = function (row) {
  4119. var r = new RowDefinition();
  4120. r._parse(row.height, function (v, vp, t) {
  4121. r.height = v;
  4122. r.heightPixels = vp;
  4123. r.heightType = t;
  4124. });
  4125. this_1._rows.push(r);
  4126. };
  4127. var this_1 = this;
  4128. for (var _i = 0, _a = settings.rows; _i < _a.length; _i++) {
  4129. var row = _a[_i];
  4130. _loop_1(row);
  4131. }
  4132. }
  4133. if (settings.columns) {
  4134. var _loop_2 = function (col) {
  4135. var r = new ColumnDefinition();
  4136. r._parse(col.width, function (v, vp, t) {
  4137. r.width = v;
  4138. r.widthPixels = vp;
  4139. r.widthType = t;
  4140. });
  4141. this_2._columns.push(r);
  4142. };
  4143. var this_2 = this;
  4144. for (var _b = 0, _c = settings.columns; _b < _c.length; _b++) {
  4145. var col = _c[_b];
  4146. _loop_2(col);
  4147. }
  4148. }
  4149. return _this;
  4150. }
  4151. GridPanelLayoutEngine.prototype.updateLayout = function (prim) {
  4152. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  4153. if (!prim.layoutArea) {
  4154. return;
  4155. }
  4156. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  4157. var child = _a[_i];
  4158. if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  4159. continue;
  4160. }
  4161. if (child._hasMargin) {
  4162. child.margin.computeWithAlignment(prim.layoutArea, child.actualSize, child.marginAlignment, child.actualScale, GridPanelLayoutEngine_1.dstOffset, GridPanelLayoutEngine_1.dstArea, true);
  4163. }
  4164. else {
  4165. child.margin.computeArea(child.actualSize, child.actualScale, GridPanelLayoutEngine_1.dstArea);
  4166. }
  4167. child.layoutArea = GridPanelLayoutEngine_1.dstArea;
  4168. }
  4169. this._updateGrid(prim);
  4170. var _children = this._children;
  4171. var rl = this._rows.length;
  4172. var cl = this._columns.length;
  4173. var columnWidth = 0;
  4174. var rowHeight = 0;
  4175. var dstArea = GridPanelLayoutEngine_1.dstArea;
  4176. var dstAreaPos = GridPanelLayoutEngine_1.dstAreaPos;
  4177. for (var i = 0; i < _children.length; i++) {
  4178. var children = _children[i];
  4179. if (children) {
  4180. var bottom = this._rowBottoms[i];
  4181. var rowHeight_1 = this._rowHeights[i];
  4182. var oBottom = bottom;
  4183. var oRowHeight = rowHeight_1;
  4184. for (var j = 0; j < children.length; j++) {
  4185. var left = this._columnLefts[j];
  4186. var columnWidth_1 = this._columnWidths[j];
  4187. var child = children[j];
  4188. if (child) {
  4189. var gd = child.layoutData;
  4190. if (gd.columnSpan > 1) {
  4191. for (var k = j + 1; k < gd.columnSpan + j && k < cl; k++) {
  4192. columnWidth_1 += this._columnWidths[k];
  4193. }
  4194. }
  4195. if (gd.rowSpan > 1) {
  4196. for (var k = i + 1; k < gd.rowSpan + i && k < rl; k++) {
  4197. rowHeight_1 += this._rowHeights[k];
  4198. bottom = this._rowBottoms[k];
  4199. }
  4200. }
  4201. dstArea.width = columnWidth_1;
  4202. dstArea.height = rowHeight_1;
  4203. child.layoutArea = dstArea;
  4204. dstAreaPos.x = left;
  4205. dstAreaPos.y = bottom;
  4206. child.layoutAreaPos = dstAreaPos;
  4207. bottom = oBottom;
  4208. rowHeight_1 = oRowHeight;
  4209. }
  4210. }
  4211. }
  4212. }
  4213. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  4214. }
  4215. };
  4216. Object.defineProperty(GridPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  4217. get: function () {
  4218. return false;
  4219. },
  4220. enumerable: true,
  4221. configurable: true
  4222. });
  4223. GridPanelLayoutEngine.prototype._getMaxChildHeightInRow = function (rowNum) {
  4224. var rows = this._rows;
  4225. var cl = this._columns.length;
  4226. var rl = this._rows.length;
  4227. var children = this._children;
  4228. var row = rows[rowNum];
  4229. var maxHeight = 0;
  4230. if (children && children[rowNum]) {
  4231. for (var i = 0; i < cl; i++) {
  4232. var child = children[rowNum][i];
  4233. if (child) {
  4234. var span = child.layoutData.rowSpan;
  4235. if (maxHeight < child.layoutArea.height / span) {
  4236. maxHeight = child.layoutArea.height / span;
  4237. }
  4238. }
  4239. }
  4240. }
  4241. return maxHeight;
  4242. };
  4243. GridPanelLayoutEngine.prototype._getMaxChildWidthInColumn = function (colNum) {
  4244. var columns = this._columns;
  4245. var cl = this._columns.length;
  4246. var rl = this._rows.length;
  4247. var children = this._children;
  4248. var column = columns[colNum];
  4249. var maxWidth = 0;
  4250. if (children) {
  4251. for (var i = 0; i < rl; i++) {
  4252. if (children[i]) {
  4253. var child = children[i][colNum];
  4254. if (child) {
  4255. var span = child.layoutData.columnSpan;
  4256. if (maxWidth < child.layoutArea.width / span) {
  4257. maxWidth = child.layoutArea.width / span;
  4258. }
  4259. }
  4260. }
  4261. }
  4262. }
  4263. return maxWidth;
  4264. };
  4265. GridPanelLayoutEngine.prototype._updateGrid = function (prim) {
  4266. var _children = this._children;
  4267. //remove prim.children from _children
  4268. for (var i_1 = 0; i_1 < _children.length; i_1++) {
  4269. var children = _children[i_1];
  4270. if (children) {
  4271. children.length = 0;
  4272. }
  4273. }
  4274. var childrenThatSpan;
  4275. //add prim.children to _children
  4276. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  4277. var child = _a[_i];
  4278. if (!child.layoutData) {
  4279. continue;
  4280. }
  4281. var gd = child.layoutData;
  4282. if (!_children[gd.row]) {
  4283. _children[gd.row] = [];
  4284. }
  4285. if (gd.columnSpan == 1 && gd.rowSpan == 1) {
  4286. _children[gd.row][gd.column] = child;
  4287. }
  4288. else {
  4289. if (!childrenThatSpan) {
  4290. childrenThatSpan = [];
  4291. }
  4292. //when children span, we need to add them to _children whereever they span to so that
  4293. //_getMaxChildHeightInRow and _getMaxChildWidthInColumn will work correctly.
  4294. childrenThatSpan.push(child);
  4295. for (var i_2 = gd.row; i_2 < gd.row + gd.rowSpan; i_2++) {
  4296. for (var j = gd.column; j < gd.column + gd.columnSpan; j++) {
  4297. _children[i_2][j] = child;
  4298. }
  4299. }
  4300. }
  4301. }
  4302. var rows = this._rows;
  4303. var columns = this._columns;
  4304. var rl = this._rows.length;
  4305. var cl = this._columns.length;
  4306. //get fixed and auto row heights first
  4307. var starIndexes = [];
  4308. var totalStars = 0;
  4309. var rowHeights = 0;
  4310. var columnWidths = 0;
  4311. for (var i_3 = 0; i_3 < rl; i_3++) {
  4312. var row = this._rows[i_3];
  4313. if (row.heightType == GridDimensionDefinition.Auto) {
  4314. this._rowHeights[i_3] = this._getMaxChildHeightInRow(i_3);
  4315. rowHeights += this._rowHeights[i_3];
  4316. }
  4317. else if (row.heightType == GridDimensionDefinition.Pixels) {
  4318. var maxChildHeight = this._getMaxChildHeightInRow(i_3);
  4319. this._rowHeights[i_3] = Math.max(row.heightPixels, maxChildHeight);
  4320. rowHeights += this._rowHeights[i_3];
  4321. }
  4322. else if (row.heightType == GridDimensionDefinition.Stars) {
  4323. starIndexes.push(i_3);
  4324. totalStars += row.height;
  4325. }
  4326. }
  4327. //star row heights
  4328. if (starIndexes.length > 0) {
  4329. var remainingHeight = prim.contentArea.height - rowHeights;
  4330. for (var i_4 = 0; i_4 < starIndexes.length; i_4++) {
  4331. var rowIndex = starIndexes[i_4];
  4332. var starHeight = (this._rows[rowIndex].height / totalStars) * remainingHeight;
  4333. var maxChildHeight = this._getMaxChildHeightInRow(i_4);
  4334. this._rowHeights[rowIndex] = Math.max(starHeight, maxChildHeight);
  4335. }
  4336. }
  4337. //get fixed and auto column widths
  4338. starIndexes.length = 0;
  4339. totalStars = 0;
  4340. for (var i_5 = 0; i_5 < cl; i_5++) {
  4341. var column = this._columns[i_5];
  4342. if (column.widthType == GridDimensionDefinition.Auto) {
  4343. this._columnWidths[i_5] = this._getMaxChildWidthInColumn(i_5);
  4344. columnWidths += this._columnWidths[i_5];
  4345. }
  4346. else if (column.widthType == GridDimensionDefinition.Pixels) {
  4347. var maxChildWidth = this._getMaxChildWidthInColumn(i_5);
  4348. this._columnWidths[i_5] = Math.max(column.widthPixels, maxChildWidth);
  4349. columnWidths += this._columnWidths[i_5];
  4350. }
  4351. else if (column.widthType == GridDimensionDefinition.Stars) {
  4352. starIndexes.push(i_5);
  4353. totalStars += column.width;
  4354. }
  4355. }
  4356. //star column widths
  4357. if (starIndexes.length > 0) {
  4358. var remainingWidth = prim.contentArea.width - columnWidths;
  4359. for (var i_6 = 0; i_6 < starIndexes.length; i_6++) {
  4360. var columnIndex = starIndexes[i_6];
  4361. var starWidth = (this._columns[columnIndex].width / totalStars) * remainingWidth;
  4362. var maxChildWidth = this._getMaxChildWidthInColumn(i_6);
  4363. this._columnWidths[columnIndex] = Math.max(starWidth, maxChildWidth);
  4364. }
  4365. }
  4366. var y = 0;
  4367. this._rowBottoms[rl - 1] = y;
  4368. for (var i_7 = rl - 2; i_7 >= 0; i_7--) {
  4369. y += this._rowHeights[i_7 + 1];
  4370. this._rowBottoms[i_7] = y;
  4371. }
  4372. var x = 0;
  4373. this._columnLefts[0] = x;
  4374. for (var i_8 = 1; i_8 < cl; i_8++) {
  4375. x += this._columnWidths[i_8 - 1];
  4376. this._columnLefts[i_8] = x;
  4377. }
  4378. //remove duplicate references to children that span
  4379. if (childrenThatSpan) {
  4380. for (var i = 0; i < childrenThatSpan.length; i++) {
  4381. var child = childrenThatSpan[i];
  4382. var gd = child.layoutData;
  4383. for (var i_9 = gd.row; i_9 < gd.row + gd.rowSpan; i_9++) {
  4384. for (var j = gd.column; j < gd.column + gd.columnSpan; j++) {
  4385. if (i_9 == gd.row && j == gd.column) {
  4386. continue;
  4387. }
  4388. if (_children[i_9][j] == child) {
  4389. _children[i_9][j] = null;
  4390. }
  4391. }
  4392. }
  4393. }
  4394. }
  4395. };
  4396. return GridPanelLayoutEngine;
  4397. }(LayoutEngineBase));
  4398. GridPanelLayoutEngine.dstOffset = BABYLON.Vector4.Zero();
  4399. GridPanelLayoutEngine.dstArea = BABYLON.Size.Zero();
  4400. GridPanelLayoutEngine.dstAreaPos = BABYLON.Vector2.Zero();
  4401. GridPanelLayoutEngine = GridPanelLayoutEngine_1 = __decorate([
  4402. BABYLON.className("GridPanelLayoutEngine", "BABYLON")
  4403. ], GridPanelLayoutEngine);
  4404. BABYLON.GridPanelLayoutEngine = GridPanelLayoutEngine;
  4405. var CanvasLayoutEngine_1, StackPanelLayoutEngine_1, GridPanelLayoutEngine_1;
  4406. })(BABYLON || (BABYLON = {}));
  4407. //# sourceMappingURL=babylon.canvas2dLayoutEngine.js.map
  4408. var __extends = (this && this.__extends) || function (d, b) {
  4409. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4410. function __() { this.constructor = d; }
  4411. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4412. };
  4413. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  4414. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  4415. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4416. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  4417. return c > 3 && r && Object.defineProperty(target, key, r), r;
  4418. };
  4419. var BABYLON;
  4420. (function (BABYLON) {
  4421. /**
  4422. * Base class implementing the ILocable interface.
  4423. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  4424. */
  4425. var LockableBase = (function () {
  4426. function LockableBase() {
  4427. }
  4428. LockableBase.prototype.isLocked = function () {
  4429. return this._isLocked;
  4430. };
  4431. LockableBase.prototype.lock = function () {
  4432. if (this._isLocked) {
  4433. return true;
  4434. }
  4435. this.onLock();
  4436. this._isLocked = true;
  4437. return false;
  4438. };
  4439. /**
  4440. * Protected handler that will be called when the instance is about to be locked.
  4441. */
  4442. LockableBase.prototype.onLock = function () {
  4443. };
  4444. return LockableBase;
  4445. }());
  4446. BABYLON.LockableBase = LockableBase;
  4447. var SolidColorBrush2D = (function (_super) {
  4448. __extends(SolidColorBrush2D, _super);
  4449. function SolidColorBrush2D(color, lock) {
  4450. if (lock === void 0) { lock = false; }
  4451. var _this = _super.call(this) || this;
  4452. _this._color = color;
  4453. if (lock) {
  4454. {
  4455. _this.lock();
  4456. }
  4457. }
  4458. return _this;
  4459. }
  4460. /**
  4461. * Return true if the brush is transparent, false if it's totally opaque
  4462. */
  4463. SolidColorBrush2D.prototype.isTransparent = function () {
  4464. return this._color && this._color.a < 1.0;
  4465. };
  4466. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  4467. /**
  4468. * The color used by this instance to render
  4469. * @returns the color object. Note that it's not a clone of the actual object stored in the instance so you MUST NOT modify it, otherwise unexpected behavior might occurs.
  4470. */
  4471. get: function () {
  4472. return this._color;
  4473. },
  4474. set: function (value) {
  4475. if (this.isLocked()) {
  4476. return;
  4477. }
  4478. this._color = value;
  4479. },
  4480. enumerable: true,
  4481. configurable: true
  4482. });
  4483. /**
  4484. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  4485. */
  4486. SolidColorBrush2D.prototype.toString = function () {
  4487. return this._color.toHexString();
  4488. };
  4489. return SolidColorBrush2D;
  4490. }(LockableBase));
  4491. SolidColorBrush2D = __decorate([
  4492. BABYLON.className("SolidColorBrush2D", "BABYLON")
  4493. ], SolidColorBrush2D);
  4494. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  4495. var GradientColorBrush2D = (function (_super) {
  4496. __extends(GradientColorBrush2D, _super);
  4497. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  4498. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  4499. if (rotation === void 0) { rotation = 0; }
  4500. if (scale === void 0) { scale = 1; }
  4501. if (lock === void 0) { lock = false; }
  4502. var _this = _super.call(this) || this;
  4503. _this._color1 = color1;
  4504. _this._color2 = color2;
  4505. _this._translation = translation;
  4506. _this._rotation = rotation;
  4507. _this._scale = scale;
  4508. if (lock) {
  4509. _this.lock();
  4510. }
  4511. return _this;
  4512. }
  4513. /**
  4514. * Return true if the brush is transparent, false if it's totally opaque
  4515. */
  4516. GradientColorBrush2D.prototype.isTransparent = function () {
  4517. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  4518. };
  4519. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  4520. /**
  4521. * First color, the blend will start from this color
  4522. */
  4523. get: function () {
  4524. return this._color1;
  4525. },
  4526. set: function (value) {
  4527. if (this.isLocked()) {
  4528. return;
  4529. }
  4530. this._color1 = value;
  4531. },
  4532. enumerable: true,
  4533. configurable: true
  4534. });
  4535. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  4536. /**
  4537. * Second color, the blend will end to this color
  4538. */
  4539. get: function () {
  4540. return this._color2;
  4541. },
  4542. set: function (value) {
  4543. if (this.isLocked()) {
  4544. return;
  4545. }
  4546. this._color2 = value;
  4547. },
  4548. enumerable: true,
  4549. configurable: true
  4550. });
  4551. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  4552. /**
  4553. * Translation vector to apply on the blend
  4554. * Default is [0;0]
  4555. */
  4556. get: function () {
  4557. return this._translation;
  4558. },
  4559. set: function (value) {
  4560. if (this.isLocked()) {
  4561. return;
  4562. }
  4563. this._translation = value;
  4564. },
  4565. enumerable: true,
  4566. configurable: true
  4567. });
  4568. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  4569. /**
  4570. * Rotation in radian to apply to the brush
  4571. * Default direction of the brush is vertical, you can change this using this property.
  4572. * Default is 0.
  4573. */
  4574. get: function () {
  4575. return this._rotation;
  4576. },
  4577. set: function (value) {
  4578. if (this.isLocked()) {
  4579. return;
  4580. }
  4581. this._rotation = value;
  4582. },
  4583. enumerable: true,
  4584. configurable: true
  4585. });
  4586. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  4587. /**
  4588. * Scale factor to apply to the gradient.
  4589. * Default is 1: no scale.
  4590. */
  4591. get: function () {
  4592. return this._scale;
  4593. },
  4594. set: function (value) {
  4595. if (this.isLocked()) {
  4596. return;
  4597. }
  4598. this._scale = value;
  4599. },
  4600. enumerable: true,
  4601. configurable: true
  4602. });
  4603. /**
  4604. * Return a string describing the brush
  4605. */
  4606. GradientColorBrush2D.prototype.toString = function () {
  4607. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  4608. };
  4609. /**
  4610. * Build a unique key string for the given parameters
  4611. */
  4612. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  4613. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  4614. };
  4615. return GradientColorBrush2D;
  4616. }(LockableBase));
  4617. GradientColorBrush2D = __decorate([
  4618. BABYLON.className("GradientColorBrush2D", "BABYLON")
  4619. ], GradientColorBrush2D);
  4620. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  4621. })(BABYLON || (BABYLON = {}));
  4622. //# sourceMappingURL=babylon.brushes2d.js.map
  4623. var __extends = (this && this.__extends) || function (d, b) {
  4624. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4625. function __() { this.constructor = d; }
  4626. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4627. };
  4628. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  4629. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  4630. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4631. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  4632. return c > 3 && r && Object.defineProperty(target, key, r), r;
  4633. };
  4634. var BABYLON;
  4635. (function (BABYLON) {
  4636. var Prim2DClassInfo = (function () {
  4637. function Prim2DClassInfo() {
  4638. }
  4639. return Prim2DClassInfo;
  4640. }());
  4641. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  4642. var Prim2DPropInfo = (function () {
  4643. function Prim2DPropInfo() {
  4644. }
  4645. return Prim2DPropInfo;
  4646. }());
  4647. Prim2DPropInfo.PROPKIND_MODEL = 1;
  4648. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  4649. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  4650. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  4651. var ClassTreeInfo = (function () {
  4652. function ClassTreeInfo(baseClass, type, classContentFactory) {
  4653. this._baseClass = baseClass;
  4654. this._type = type;
  4655. this._subClasses = new Array();
  4656. this._levelContent = new BABYLON.StringDictionary();
  4657. this._classContentFactory = classContentFactory;
  4658. }
  4659. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  4660. get: function () {
  4661. if (!this._classContent) {
  4662. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  4663. }
  4664. return this._classContent;
  4665. },
  4666. enumerable: true,
  4667. configurable: true
  4668. });
  4669. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  4670. get: function () {
  4671. return this._type;
  4672. },
  4673. enumerable: true,
  4674. configurable: true
  4675. });
  4676. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  4677. get: function () {
  4678. return this._levelContent;
  4679. },
  4680. enumerable: true,
  4681. configurable: true
  4682. });
  4683. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  4684. get: function () {
  4685. if (!this._fullContent) {
  4686. var dic_1 = new BABYLON.StringDictionary();
  4687. var curLevel = this;
  4688. while (curLevel) {
  4689. curLevel.levelContent.forEach(function (k, v) { return dic_1.add(k, v); });
  4690. curLevel = curLevel._baseClass;
  4691. }
  4692. this._fullContent = dic_1;
  4693. }
  4694. return this._fullContent;
  4695. },
  4696. enumerable: true,
  4697. configurable: true
  4698. });
  4699. ClassTreeInfo.prototype.getLevelOf = function (type) {
  4700. // Are we already there?
  4701. if (type === this._type) {
  4702. return this;
  4703. }
  4704. var baseProto = Object.getPrototypeOf(type);
  4705. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  4706. if (!curProtoContent) {
  4707. this.getLevelOf(baseProto);
  4708. }
  4709. return this.getOrAddType(baseProto, type);
  4710. };
  4711. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  4712. // Are we at the level corresponding to the baseType?
  4713. // If so, get or add the level we're looking for
  4714. if (baseType === this._type) {
  4715. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  4716. var subType = _a[_i];
  4717. if (subType.type === type) {
  4718. return subType.node;
  4719. }
  4720. }
  4721. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  4722. var info = { type: type, node: node };
  4723. this._subClasses.push(info);
  4724. return info.node;
  4725. }
  4726. // Recurse down to keep looking for the node corresponding to the baseTypeName
  4727. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  4728. var subType = _c[_b];
  4729. var info = subType.node.getOrAddType(baseType, type);
  4730. if (info) {
  4731. return info;
  4732. }
  4733. }
  4734. return null;
  4735. };
  4736. ClassTreeInfo.get = function (type) {
  4737. var dic = type["__classTreeInfo"];
  4738. if (!dic) {
  4739. return null;
  4740. }
  4741. return dic.getLevelOf(type);
  4742. };
  4743. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  4744. var dic = type["__classTreeInfo"];
  4745. if (!dic) {
  4746. dic = new ClassTreeInfo(null, type, classContentFactory);
  4747. type["__classTreeInfo"] = dic;
  4748. }
  4749. return dic;
  4750. };
  4751. return ClassTreeInfo;
  4752. }());
  4753. BABYLON.ClassTreeInfo = ClassTreeInfo;
  4754. var DataBinding = DataBinding_1 = (function () {
  4755. function DataBinding() {
  4756. this._converter = null;
  4757. this._mode = DataBinding_1.MODE_DEFAULT;
  4758. this._uiElementId = null;
  4759. this._dataSource = null;
  4760. this._currentDataSource = null;
  4761. this._propertyPathName = null;
  4762. this._stringFormat = null;
  4763. this._updateSourceTrigger = DataBinding_1.UPDATESOURCETRIGGER_PROPERTYCHANGED;
  4764. this._boundTo = null;
  4765. this._owner = null;
  4766. this._updateCounter = 0;
  4767. }
  4768. Object.defineProperty(DataBinding.prototype, "converter", {
  4769. /**
  4770. * Provide a callback that will convert the value obtained by the Data Binding to the type of the SmartProperty it's bound to.
  4771. * If no value are set, then it's assumed that the sourceValue is of the same type as the SmartProperty's one.
  4772. * If the SmartProperty type is a basic data type (string, boolean or number) and no converter is specified but the sourceValue is of a different type, the conversion will be implicitly made, if possible.
  4773. * @param sourceValue the source object retrieve by the Data Binding mechanism
  4774. * @returns the object of a compatible type with the SmartProperty it's bound to
  4775. */
  4776. get: function () {
  4777. return this._converter;
  4778. },
  4779. set: function (value) {
  4780. if (this._converter === value) {
  4781. return;
  4782. }
  4783. this._converter = value;
  4784. },
  4785. enumerable: true,
  4786. configurable: true
  4787. });
  4788. Object.defineProperty(DataBinding.prototype, "mode", {
  4789. /**
  4790. * Set the mode to use for the data flow in the binding. Set one of the MODE_xxx static member of this class. If not specified then MODE_DEFAULT will be used
  4791. */
  4792. get: function () {
  4793. if (this._mode === DataBinding_1.MODE_DEFAULT) {
  4794. return this._boundTo.bindingMode;
  4795. }
  4796. return this._mode;
  4797. },
  4798. set: function (value) {
  4799. if (this._mode === value) {
  4800. return;
  4801. }
  4802. this._mode = value;
  4803. },
  4804. enumerable: true,
  4805. configurable: true
  4806. });
  4807. Object.defineProperty(DataBinding.prototype, "uiElementId", {
  4808. /**
  4809. * You can override the Data Source object with this member which is the Id of a uiElement existing in the UI Logical tree.
  4810. * If not set and source no set too, then the dataSource property will be used.
  4811. */
  4812. get: function () {
  4813. return this._uiElementId;
  4814. },
  4815. set: function (value) {
  4816. if (this._uiElementId === value) {
  4817. return;
  4818. }
  4819. this._uiElementId = value;
  4820. },
  4821. enumerable: true,
  4822. configurable: true
  4823. });
  4824. Object.defineProperty(DataBinding.prototype, "dataSource", {
  4825. /**
  4826. * You can override the Data Source object with this member which is the source object to use directly.
  4827. * If not set and uiElement no set too, then the dataSource property of the SmartPropertyBase object will be used.
  4828. */
  4829. get: function () {
  4830. return this._dataSource;
  4831. },
  4832. set: function (value) {
  4833. if (this._dataSource === value) {
  4834. return;
  4835. }
  4836. this._dataSource = value;
  4837. },
  4838. enumerable: true,
  4839. configurable: true
  4840. });
  4841. Object.defineProperty(DataBinding.prototype, "propertyPathName", {
  4842. /**
  4843. * The path & name of the property to get from the source object.
  4844. * Once the Source object is evaluated (it's either the one got from uiElementId, source or dataSource) you can specify which property of this object is the value to bind to the smartProperty.
  4845. * If nothing is set then the source object will be used.
  4846. * You can specify an indirect property using the format "firstProperty.indirectProperty" like "address.postalCode" if the source is a Customer object which contains an address property and the Address class contains a postalCode property.
  4847. * If the property is an Array and you want to address a particular element then use the 'arrayProperty[index]' notation. For example "phoneNumbers[0]" to get the first element of the phoneNumber property which is an array.
  4848. */
  4849. get: function () {
  4850. return this._propertyPathName;
  4851. },
  4852. set: function (value) {
  4853. if (this._propertyPathName === value) {
  4854. return;
  4855. }
  4856. if (this._owner) {
  4857. }
  4858. this._propertyPathName = value;
  4859. if (this._owner) {
  4860. }
  4861. },
  4862. enumerable: true,
  4863. configurable: true
  4864. });
  4865. Object.defineProperty(DataBinding.prototype, "stringFormat", {
  4866. /**
  4867. * If the Smart Property is of the string type, you can use the string interpolation notation to provide how the sourceValue will be formatted, reference to the source value must be made via the token: ${value}. For instance `Customer Name: ${value}`
  4868. */
  4869. get: function () {
  4870. return this._stringFormat;
  4871. },
  4872. set: function (value) {
  4873. if (this._stringFormat === value) {
  4874. return;
  4875. }
  4876. this._stringFormat = value;
  4877. },
  4878. enumerable: true,
  4879. configurable: true
  4880. });
  4881. Object.defineProperty(DataBinding.prototype, "updateSourceTrigger", {
  4882. /**
  4883. * Specify how the source should be updated, use one of the UPDATESOURCETRIGGER_xxx member of this class, if not specified then UPDATESOURCETRIGGER_DEFAULT will be used.
  4884. */
  4885. get: function () {
  4886. return this._updateSourceTrigger;
  4887. },
  4888. set: function (value) {
  4889. if (this._updateSourceTrigger === value) {
  4890. return;
  4891. }
  4892. this._updateSourceTrigger = value;
  4893. },
  4894. enumerable: true,
  4895. configurable: true
  4896. });
  4897. DataBinding.prototype.canUpdateTarget = function (resetUpdateCounter) {
  4898. if (resetUpdateCounter) {
  4899. this._updateCounter = 0;
  4900. }
  4901. var mode = this.mode;
  4902. if (mode === DataBinding_1.MODE_ONETIME) {
  4903. return this._updateCounter === 0;
  4904. }
  4905. if (mode === DataBinding_1.MODE_ONEWAYTOSOURCE) {
  4906. return false;
  4907. }
  4908. return true;
  4909. };
  4910. DataBinding.prototype.updateTarget = function () {
  4911. var value = this._getActualDataSource();
  4912. var properties = this.propertyPathName.split(".");
  4913. for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) {
  4914. var propertyName = properties_1[_i];
  4915. value = value[propertyName];
  4916. }
  4917. this._storeBoundValue(this._owner, value);
  4918. };
  4919. DataBinding.prototype._storeBoundValue = function (watcher, value) {
  4920. if ((++this._updateCounter > 1) && (this.mode === DataBinding_1.MODE_ONETIME)) {
  4921. return;
  4922. }
  4923. var newValue = value;
  4924. if (this._converter) {
  4925. newValue = this._converter(value);
  4926. }
  4927. if (this._stringFormat) {
  4928. newValue = this._stringFormat(newValue);
  4929. }
  4930. watcher[this._boundTo.name] = newValue;
  4931. };
  4932. DataBinding.prototype._getActualDataSource = function () {
  4933. if (this.dataSource) {
  4934. return this.dataSource;
  4935. }
  4936. if (this.uiElementId) {
  4937. // TODO Find UIElement
  4938. return null;
  4939. }
  4940. return this._owner.dataSource;
  4941. };
  4942. DataBinding.prototype._registerDataSource = function (updateTarget) {
  4943. var ds = this._getActualDataSource();
  4944. if (ds === this._currentDataSource) {
  4945. return;
  4946. }
  4947. if (this._currentDataSource) {
  4948. BindingHelper.unregisterDataSource(this._currentDataSource, this, 0);
  4949. }
  4950. if (ds) {
  4951. BindingHelper.registerDataSource(ds, this);
  4952. if (updateTarget && this.canUpdateTarget(true)) {
  4953. this.updateTarget();
  4954. }
  4955. }
  4956. this._currentDataSource = ds;
  4957. };
  4958. DataBinding.prototype._unregisterDataSource = function () {
  4959. var ds = this._getActualDataSource();
  4960. if (ds) {
  4961. BindingHelper.unregisterDataSource(ds, this, 0);
  4962. }
  4963. };
  4964. return DataBinding;
  4965. }());
  4966. /**
  4967. * Use the mode specified in the SmartProperty declaration
  4968. */
  4969. DataBinding.MODE_DEFAULT = 1;
  4970. /**
  4971. * Update the binding target only once when the Smart Property's value is first accessed
  4972. */
  4973. DataBinding.MODE_ONETIME = 2;
  4974. /**
  4975. * Update the smart property when the source changes.
  4976. * The source won't be updated if the smart property value is set.
  4977. */
  4978. DataBinding.MODE_ONEWAY = 3;
  4979. /**
  4980. * Only update the source when the target's data is changing.
  4981. */
  4982. DataBinding.MODE_ONEWAYTOSOURCE = 4;
  4983. /**
  4984. * Update the bind target when the source changes and update the source when the Smart Property value is set.
  4985. */
  4986. DataBinding.MODE_TWOWAY = 5;
  4987. /**
  4988. * Use the Update Source Trigger defined in the SmartProperty declaration
  4989. */
  4990. DataBinding.UPDATESOURCETRIGGER_DEFAULT = 1;
  4991. /**
  4992. * Update the source as soon as the Smart Property has a value change
  4993. */
  4994. DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED = 2;
  4995. /**
  4996. * Update the source when the binding target loses focus
  4997. */
  4998. DataBinding.UPDATESOURCETRIGGER_LOSTFOCUS = 3;
  4999. /**
  5000. * Update the source will be made by explicitly calling the UpdateFromDataSource method
  5001. */
  5002. DataBinding.UPDATESOURCETRIGGER_EXPLICIT = 4;
  5003. DataBinding = DataBinding_1 = __decorate([
  5004. BABYLON.className("DataBinding", "BABYLON")
  5005. ], DataBinding);
  5006. BABYLON.DataBinding = DataBinding;
  5007. var SmartPropertyBase = SmartPropertyBase_1 = (function (_super) {
  5008. __extends(SmartPropertyBase, _super);
  5009. function SmartPropertyBase() {
  5010. var _this = _super.call(this) || this;
  5011. _this._dataSource = null;
  5012. _this._dataSourceObserver = null;
  5013. _this._instanceDirtyFlags = 0;
  5014. _this._isDisposed = false;
  5015. _this._bindings = null;
  5016. _this._hasBinding = 0;
  5017. _this._bindingSourceChanged = 0;
  5018. _this._disposeObservable = null;
  5019. return _this;
  5020. }
  5021. Object.defineProperty(SmartPropertyBase.prototype, "disposeObservable", {
  5022. get: function () {
  5023. if (!this._disposeObservable) {
  5024. this._disposeObservable = new BABYLON.Observable();
  5025. }
  5026. return this._disposeObservable;
  5027. },
  5028. enumerable: true,
  5029. configurable: true
  5030. });
  5031. Object.defineProperty(SmartPropertyBase.prototype, "isDisposed", {
  5032. /**
  5033. * Check if the object is disposed or not.
  5034. * @returns true if the object is dispose, false otherwise.
  5035. */
  5036. get: function () {
  5037. return this._isDisposed;
  5038. },
  5039. enumerable: true,
  5040. configurable: true
  5041. });
  5042. /**
  5043. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  5044. * @returns false if the object is already dispose, true otherwise. Your implementation must call super.dispose() and check for a false return and return immediately if it's the case.
  5045. */
  5046. SmartPropertyBase.prototype.dispose = function () {
  5047. if (this.isDisposed) {
  5048. return false;
  5049. }
  5050. if (this._disposeObservable && this._disposeObservable.hasObservers()) {
  5051. this._disposeObservable.notifyObservers(this);
  5052. }
  5053. this._isDisposed = true;
  5054. return true;
  5055. };
  5056. /**
  5057. * Check if a given set of properties are dirty or not.
  5058. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  5059. * @return true if at least one property is dirty, false if none of them are.
  5060. */
  5061. SmartPropertyBase.prototype.checkPropertiesDirty = function (flags) {
  5062. return (this._instanceDirtyFlags & flags) !== 0;
  5063. };
  5064. /**
  5065. * Clear a given set of properties.
  5066. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  5067. * @return the new set of property still marked as dirty
  5068. */
  5069. SmartPropertyBase.prototype.clearPropertiesDirty = function (flags) {
  5070. this._instanceDirtyFlags &= ~flags;
  5071. return this._instanceDirtyFlags;
  5072. };
  5073. SmartPropertyBase.prototype._resetPropertiesDirty = function () {
  5074. this._instanceDirtyFlags = 0;
  5075. };
  5076. /**
  5077. * Add an externally attached data from its key.
  5078. * This method call will fail and return false, if such key already exists.
  5079. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  5080. * @param key the unique key that identifies the data
  5081. * @param data the data object to associate to the key for this Engine instance
  5082. * @return true if no such key were already present and the data was added successfully, false otherwise
  5083. */
  5084. SmartPropertyBase.prototype.addExternalData = function (key, data) {
  5085. if (!this._externalData) {
  5086. this._externalData = new BABYLON.StringDictionary();
  5087. }
  5088. return this._externalData.add(key, data);
  5089. };
  5090. /**
  5091. * Get an externally attached data from its key
  5092. * @param key the unique key that identifies the data
  5093. * @return the associated data, if present (can be null), or undefined if not present
  5094. */
  5095. SmartPropertyBase.prototype.getExternalData = function (key) {
  5096. if (!this._externalData) {
  5097. return null;
  5098. }
  5099. return this._externalData.get(key);
  5100. };
  5101. /**
  5102. * Get an externally attached data from its key, create it using a factory if it's not already present
  5103. * @param key the unique key that identifies the data
  5104. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  5105. * @return the associated data, can be null if the factory returned null.
  5106. */
  5107. SmartPropertyBase.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  5108. if (!this._externalData) {
  5109. this._externalData = new BABYLON.StringDictionary();
  5110. }
  5111. return this._externalData.getOrAddWithFactory(key, factory);
  5112. };
  5113. /**
  5114. * Remove an externally attached data from the Engine instance
  5115. * @param key the unique key that identifies the data
  5116. * @return true if the data was successfully removed, false if it doesn't exist
  5117. */
  5118. SmartPropertyBase.prototype.removeExternalData = function (key) {
  5119. if (!this._externalData) {
  5120. return false;
  5121. }
  5122. return this._externalData.remove(key);
  5123. };
  5124. SmartPropertyBase._hookProperty = function (propId, piStore, kind, settings) {
  5125. return function (target, propName, descriptor) {
  5126. if (!settings) {
  5127. settings = {};
  5128. }
  5129. var propInfo = SmartPropertyBase_1._createPropInfo(target, propName, propId, kind, settings);
  5130. if (piStore) {
  5131. piStore(propInfo);
  5132. }
  5133. var getter = descriptor.get, setter = descriptor.set;
  5134. var typeLevelCompare = (settings.typeLevelCompare !== undefined) ? settings.typeLevelCompare : false;
  5135. // Overload the property setter implementation to add our own logic
  5136. descriptor.set = function (val) {
  5137. if (!setter) {
  5138. throw Error("Property '" + propInfo.name + "' of type '" + BABYLON.Tools.getFullClassName(this) + "' has no setter defined but was invoked as if it had one.");
  5139. }
  5140. // check for disposed first, do nothing
  5141. if (this.isDisposed) {
  5142. return;
  5143. }
  5144. var curVal = getter.call(this);
  5145. if (SmartPropertyBase_1._checkUnchanged(curVal, val)) {
  5146. return;
  5147. }
  5148. // Cast the object we're working one
  5149. var prim = this;
  5150. // Change the value
  5151. setter.call(this, val);
  5152. // Notify change, dirty flags update
  5153. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  5154. };
  5155. };
  5156. };
  5157. SmartPropertyBase._createPropInfo = function (target, propName, propId, kind, settings) {
  5158. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  5159. var node = dic.getLevelOf(target);
  5160. var propInfo = node.levelContent.get(propId.toString());
  5161. if (propInfo) {
  5162. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  5163. }
  5164. // Create, setup and add the PropInfo object to our prop dictionary
  5165. propInfo = new Prim2DPropInfo();
  5166. propInfo.id = propId;
  5167. propInfo.flagId = Math.pow(2, propId);
  5168. propInfo.kind = kind;
  5169. propInfo.name = propName;
  5170. propInfo.bindingMode = (settings.bindingMode !== undefined) ? settings.bindingMode : DataBinding.MODE_TWOWAY;
  5171. propInfo.bindingUpdateSourceTrigger = (settings.bindingUpdateSourceTrigger !== undefined) ? settings.bindingUpdateSourceTrigger : DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED;
  5172. propInfo.dirtyBoundingInfo = (settings.dirtyBoundingInfo !== undefined) ? settings.dirtyBoundingInfo : false;
  5173. propInfo.dirtyParentBoundingInfo = (settings.dirtyParentBoundingBox !== undefined) ? settings.dirtyParentBoundingBox : false;
  5174. propInfo.typeLevelCompare = (settings.typeLevelCompare !== undefined) ? settings.typeLevelCompare : false;
  5175. node.levelContent.add(propName, propInfo);
  5176. return propInfo;
  5177. };
  5178. Object.defineProperty(SmartPropertyBase.prototype, "propDic", {
  5179. /**
  5180. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  5181. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  5182. */
  5183. get: function () {
  5184. if (!this._propInfo) {
  5185. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  5186. if (!cti) {
  5187. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  5188. }
  5189. this._propInfo = cti.fullContent;
  5190. }
  5191. return this._propInfo;
  5192. },
  5193. enumerable: true,
  5194. configurable: true
  5195. });
  5196. SmartPropertyBase._checkUnchanged = function (curValue, newValue) {
  5197. // Nothing to nothing: nothing to do!
  5198. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  5199. return true;
  5200. }
  5201. // Check value unchanged
  5202. if ((curValue != null) && (newValue != null)) {
  5203. if (typeof (curValue.equals) == "function") {
  5204. if (curValue.equals(newValue)) {
  5205. return true;
  5206. }
  5207. }
  5208. else {
  5209. if (curValue === newValue) {
  5210. return true;
  5211. }
  5212. }
  5213. }
  5214. return false;
  5215. };
  5216. SmartPropertyBase.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  5217. // Trigger property changed
  5218. var info = SmartPropertyBase_1.propChangeGuarding ? new BABYLON.PropertyChangedInfo() : SmartPropertyPrim.propChangedInfo;
  5219. info.oldValue = curValue;
  5220. info.newValue = newValue;
  5221. info.propertyName = propName;
  5222. var propMask = propInfo ? propInfo.flagId : -1;
  5223. try {
  5224. SmartPropertyBase_1.propChangeGuarding = true;
  5225. this.propertyChanged.notifyObservers(info, propMask);
  5226. }
  5227. finally {
  5228. SmartPropertyBase_1.propChangeGuarding = false;
  5229. }
  5230. };
  5231. SmartPropertyBase.prototype._triggerPropertyChanged = function (propInfo, newValue) {
  5232. if (this.isDisposed) {
  5233. return;
  5234. }
  5235. if (!propInfo) {
  5236. return;
  5237. }
  5238. this._handlePropChanged(undefined, newValue, propInfo.name, propInfo, propInfo.typeLevelCompare);
  5239. };
  5240. Object.defineProperty(SmartPropertyBase.prototype, "dataSource", {
  5241. /**
  5242. * Set the object from which Smart Properties using Binding will take/update their data from/to.
  5243. * When the object is part of a graph (with parent/children relationship) if the dataSource of a given instance is not specified, then the parent's one is used.
  5244. */
  5245. get: function () {
  5246. // Don't access to _dataSource directly but via a call to the _getDataSource method which can be overloaded in inherited classes
  5247. return this._getDataSource();
  5248. },
  5249. set: function (value) {
  5250. if (this._dataSource === value) {
  5251. return;
  5252. }
  5253. var oldValue = this._dataSource;
  5254. this._dataSource = value;
  5255. if (this._bindings && value != null) {
  5256. // Register the bindings
  5257. for (var _i = 0, _a = this._bindings; _i < _a.length; _i++) {
  5258. var binding = _a[_i];
  5259. if (binding != null) {
  5260. binding._registerDataSource(true);
  5261. }
  5262. }
  5263. }
  5264. this.onPropertyChanged("dataSource", oldValue, value);
  5265. },
  5266. enumerable: true,
  5267. configurable: true
  5268. });
  5269. // Inheriting classes can overload this method to provides additional logic for dataSource access
  5270. SmartPropertyBase.prototype._getDataSource = function () {
  5271. return this._dataSource;
  5272. };
  5273. SmartPropertyBase.prototype.createSimpleDataBinding = function (propInfo, propertyPathName, mode) {
  5274. if (mode === void 0) { mode = DataBinding.MODE_DEFAULT; }
  5275. var binding = new DataBinding();
  5276. binding.propertyPathName = propertyPathName;
  5277. binding.mode = mode;
  5278. return this.createDataBinding(propInfo, binding);
  5279. };
  5280. SmartPropertyBase.prototype.createDataBinding = function (propInfo, binding) {
  5281. if (!this._bindings) {
  5282. this._bindings = new Array();
  5283. }
  5284. if (!binding || binding._owner != null) {
  5285. throw Error("A valid/unused Binding must be passed.");
  5286. }
  5287. // Unregister a potentially existing binding for this property
  5288. this.removeDataBinding(propInfo);
  5289. // register the binding
  5290. binding._owner = this;
  5291. binding._boundTo = propInfo;
  5292. this._bindings[propInfo.id] = binding;
  5293. this._hasBinding |= propInfo.flagId;
  5294. binding._registerDataSource(true);
  5295. return binding;
  5296. };
  5297. SmartPropertyBase.prototype.removeDataBinding = function (propInfo) {
  5298. if ((this._hasBinding & propInfo.flagId) === 0) {
  5299. return false;
  5300. }
  5301. var curBinding = this._bindings[propInfo.id];
  5302. curBinding._unregisterDataSource();
  5303. this._bindings[propInfo.id] = null;
  5304. this._hasBinding &= ~propInfo.flagId;
  5305. return true;
  5306. };
  5307. SmartPropertyBase.prototype.updateFromDataSource = function () {
  5308. for (var _i = 0, _a = this._bindings; _i < _a.length; _i++) {
  5309. var binding = _a[_i];
  5310. if (binding) {
  5311. }
  5312. }
  5313. };
  5314. return SmartPropertyBase;
  5315. }(BABYLON.PropertyChangedBase));
  5316. SmartPropertyBase.propChangedInfo = new BABYLON.PropertyChangedInfo();
  5317. SmartPropertyBase.propChangeGuarding = false;
  5318. __decorate([
  5319. BABYLON.logProp()
  5320. ], SmartPropertyBase.prototype, "_triggerPropertyChanged", null);
  5321. SmartPropertyBase = SmartPropertyBase_1 = __decorate([
  5322. BABYLON.className("SmartPropertyBase", "BABYLON")
  5323. ], SmartPropertyBase);
  5324. BABYLON.SmartPropertyBase = SmartPropertyBase;
  5325. var BindingInfo = (function () {
  5326. function BindingInfo(binding, level, isLast) {
  5327. this.binding = binding;
  5328. this.level = level;
  5329. this.isLast = isLast;
  5330. }
  5331. return BindingInfo;
  5332. }());
  5333. var MonitoredObjectData = (function () {
  5334. function MonitoredObjectData(monitoredObject) {
  5335. var _this = this;
  5336. this.monitoredObject = monitoredObject;
  5337. this.monitoredIntermediateProperties = new BABYLON.StringDictionary();
  5338. this.observer = this.monitoredObject.propertyChanged.add(function (e, s) { _this.propertyChangedHandler(e.propertyName, e.oldValue, e.newValue); });
  5339. this.boundProperties = new BABYLON.StringDictionary();
  5340. this.monitoredIntermediateMask = 0;
  5341. this.boundPropertiesMask = 0;
  5342. }
  5343. MonitoredObjectData.prototype.propertyChangedHandler = function (propName, oldValue, newValue) {
  5344. var propId = BindingHelper._getPropertyID(this.monitoredObject, propName);
  5345. var propIdStr = propId.toString();
  5346. // Loop through all the registered bindings for this property that had a value change
  5347. if ((this.boundPropertiesMask & propId) !== 0) {
  5348. var bindingInfos = this.boundProperties.get(propIdStr);
  5349. for (var _i = 0, bindingInfos_1 = bindingInfos; _i < bindingInfos_1.length; _i++) {
  5350. var bi = bindingInfos_1[_i];
  5351. if (!bi.isLast) {
  5352. BindingHelper.unregisterDataSource(this.monitoredObject, bi.binding, bi.level);
  5353. BindingHelper.registerDataSource(bi.binding._currentDataSource, bi.binding);
  5354. }
  5355. if (bi.binding.canUpdateTarget(false)) {
  5356. bi.binding.updateTarget();
  5357. }
  5358. }
  5359. }
  5360. };
  5361. return MonitoredObjectData;
  5362. }());
  5363. var BindingHelper = (function () {
  5364. function BindingHelper() {
  5365. }
  5366. BindingHelper.registerDataSource = function (dataSource, binding) {
  5367. var properties = binding.propertyPathName.split(".");
  5368. var ownerMod = null;
  5369. var ownerInterPropId = 0;
  5370. var propertyOwner = dataSource;
  5371. var _loop_1 = function (i) {
  5372. var propName = properties[i];
  5373. var propId = BindingHelper._getPropertyID(propertyOwner, propName);
  5374. var propIdStr = propId.toString();
  5375. var mod = void 0;
  5376. if (ownerMod) {
  5377. var o_1 = ownerMod;
  5378. var po_1 = propertyOwner;
  5379. var oii_1 = ownerInterPropId;
  5380. mod = ownerMod.monitoredIntermediateProperties.getOrAddWithFactory(oii_1.toString(), function (k) {
  5381. o_1.monitoredIntermediateMask |= oii_1;
  5382. return BindingHelper._getMonitoredObjectData(po_1);
  5383. });
  5384. }
  5385. else {
  5386. mod = BindingHelper._getMonitoredObjectData(propertyOwner);
  5387. }
  5388. var m = mod;
  5389. var bindingInfos = mod.boundProperties.getOrAddWithFactory(propIdStr, function (k) {
  5390. m.boundPropertiesMask |= propId;
  5391. return new Array();
  5392. });
  5393. var bi = BABYLON.Tools.first(bindingInfos, function (cbi) { return cbi.binding === binding; });
  5394. if (!bi) {
  5395. bindingInfos.push(new BindingInfo(binding, i, (i + 1) === properties.length));
  5396. }
  5397. ownerMod = mod;
  5398. ownerInterPropId = propId;
  5399. propertyOwner = propertyOwner[propName];
  5400. };
  5401. for (var i = 0; i < properties.length; i++) {
  5402. _loop_1(i);
  5403. }
  5404. };
  5405. BindingHelper.unregisterDataSource = function (dataSource, binding, level) {
  5406. var properties = binding.propertyPathName.split(".");
  5407. var propertyOwner = dataSource;
  5408. var mod = BindingHelper._getMonitoredObjectData(propertyOwner);
  5409. for (var i = 0; i < properties.length; i++) {
  5410. var propName = properties[i];
  5411. var propId = BindingHelper._getPropertyID(propertyOwner, propName);
  5412. var propIdStr = propId.toString();
  5413. if (i >= level) {
  5414. mod = BindingHelper._unregisterBinding(mod, propId, binding);
  5415. }
  5416. else {
  5417. mod = mod.monitoredIntermediateProperties.get(propIdStr);
  5418. }
  5419. propertyOwner = propertyOwner[propName];
  5420. }
  5421. };
  5422. BindingHelper._unregisterBinding = function (mod, propertyID, binding) {
  5423. var propertyIDStr = propertyID.toString();
  5424. var res = null;
  5425. // Check if the property is registered as an intermediate and remove it
  5426. if ((mod.monitoredIntermediateMask & propertyID) !== 0) {
  5427. res = mod.monitoredIntermediateProperties.get(propertyIDStr);
  5428. mod.monitoredIntermediateProperties.remove(propertyIDStr);
  5429. // Update the mask
  5430. mod.monitoredIntermediateMask &= ~propertyID;
  5431. }
  5432. // Check if the property is registered as a final property and remove it
  5433. if ((mod.boundPropertiesMask & propertyID) !== 0) {
  5434. var bindingInfos = mod.boundProperties.get(propertyIDStr);
  5435. // Find the binding and remove it
  5436. var bi = BABYLON.Tools.first(bindingInfos, function (cbi) { return cbi.binding === binding; });
  5437. if (bi) {
  5438. var bii = bindingInfos.indexOf(bi);
  5439. bindingInfos.splice(bii, 1);
  5440. }
  5441. // If the array is empty, update the mask
  5442. if (bindingInfos.length === 0) {
  5443. mod.boundPropertiesMask &= ~propertyID;
  5444. }
  5445. }
  5446. // Check if the MOD is empty and unregister the observer and remove it from the list of MODs
  5447. if (mod.boundPropertiesMask === 0 && mod.monitoredIntermediateMask === 0) {
  5448. // Unregister the observer on Property Change
  5449. mod.monitoredObject.propertyChanged.remove(mod.observer);
  5450. // Remove the MOD from the dic
  5451. var objectId = BindingHelper._getObjectId(mod.monitoredObject);
  5452. BindingHelper._monitoredObjects.remove(objectId);
  5453. }
  5454. return res;
  5455. };
  5456. BindingHelper._getMonitoredObjectData = function (object) {
  5457. var objectId = BindingHelper._getObjectId(object);
  5458. var mod = BindingHelper._monitoredObjects.getOrAddWithFactory(objectId, function (k) { return new MonitoredObjectData(object); });
  5459. return mod;
  5460. };
  5461. BindingHelper._getObjectId = function (obj) {
  5462. var id = obj["__bindingHelperObjectId__"];
  5463. if (id == null) {
  5464. id = BABYLON.Tools.RandomId();
  5465. obj["__bindingHelperObjectId__"] = id;
  5466. return id;
  5467. }
  5468. return id;
  5469. };
  5470. BindingHelper._getObjectTypePropertyIDs = function (obj) {
  5471. var fullName = BABYLON.Tools.getFullClassName(obj);
  5472. if (!fullName) {
  5473. throw Error("Types involved in Data Binding must be decorated with the @className decorator");
  5474. }
  5475. var d = BindingHelper._propertiesID.getOrAddWithFactory(fullName, function () { return new BABYLON.StringDictionary(); });
  5476. return d;
  5477. };
  5478. BindingHelper._getPropertyID = function (object, propName) {
  5479. var otd = BindingHelper._getObjectTypePropertyIDs(object);
  5480. // Make sure we have a WatchedPropertyData for this property of this object type. This will contains the flagIg of the watched property.
  5481. // We use this flagId to flag for each watched instance which properties are watched, as final or intermediate and which directions are used
  5482. var propData = otd.getOrAddWithFactory(propName, function (k) { return 1 << otd.count; });
  5483. return propData;
  5484. };
  5485. return BindingHelper;
  5486. }());
  5487. BindingHelper._propertiesID = new BABYLON.StringDictionary();
  5488. BindingHelper._monitoredObjects = new BABYLON.StringDictionary();
  5489. var SmartPropertyPrim = SmartPropertyPrim_1 = (function (_super) {
  5490. __extends(SmartPropertyPrim, _super);
  5491. function SmartPropertyPrim() {
  5492. var _this = _super.call(this) || this;
  5493. _this._flags = 0;
  5494. _this._uid = null;
  5495. _this._modelKey = null;
  5496. _this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  5497. _this._boundingInfo = new BABYLON.BoundingInfo2D();
  5498. _this.animations = new Array();
  5499. return _this;
  5500. }
  5501. /**
  5502. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  5503. * @returns false if the object is already dispose, true otherwise. Your implementation must call super.dispose() and check for a false return and return immediately if it's the case.
  5504. */
  5505. SmartPropertyPrim.prototype.dispose = function () {
  5506. if (this.isDisposed) {
  5507. return false;
  5508. }
  5509. _super.prototype.dispose.call(this);
  5510. // Don't set to null, it may upset somebody...
  5511. this.animations.splice(0);
  5512. return true;
  5513. };
  5514. Object.defineProperty(SmartPropertyPrim.prototype, "uid", {
  5515. /**
  5516. * return a unique identifier for the Canvas2D
  5517. */
  5518. get: function () {
  5519. if (!this._uid) {
  5520. this._uid = BABYLON.Tools.RandomId();
  5521. }
  5522. return this._uid;
  5523. },
  5524. enumerable: true,
  5525. configurable: true
  5526. });
  5527. /**
  5528. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  5529. * Look at Sprite2D for more information
  5530. */
  5531. SmartPropertyPrim.prototype.getAnimatables = function () {
  5532. return new Array();
  5533. };
  5534. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  5535. /**
  5536. * Property giving the Model Key associated to the property.
  5537. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  5538. * @returns the model key string.
  5539. */
  5540. get: function () {
  5541. var _this = this;
  5542. // No need to compute it?
  5543. if (!this._isFlagSet(SmartPropertyPrim_1.flagModelDirty) && this._modelKey) {
  5544. return this._modelKey;
  5545. }
  5546. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  5547. var propDic = this.propDic;
  5548. propDic.forEach(function (k, v) {
  5549. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  5550. var propVal = _this[v.name];
  5551. // Special case, array, this WON'T WORK IN ALL CASES, all entries have to be of the same type and it must be a BJS well known one
  5552. if (propVal && propVal.constructor === Array) {
  5553. var firstVal = propVal[0];
  5554. if (!firstVal) {
  5555. propVal = 0;
  5556. }
  5557. else {
  5558. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  5559. }
  5560. }
  5561. var value = "[null]";
  5562. if (propVal != null) {
  5563. if (v.typeLevelCompare) {
  5564. value = BABYLON.Tools.getClassName(propVal);
  5565. }
  5566. else {
  5567. // String Dictionaries' content are too complex, with use a Random GUID to make the model unique
  5568. if (propVal instanceof BABYLON.StringDictionary) {
  5569. value = BABYLON.Tools.RandomId();
  5570. }
  5571. else if (propVal instanceof BABYLON.BaseTexture) {
  5572. value = propVal.uid;
  5573. }
  5574. else {
  5575. value = propVal.toString();
  5576. }
  5577. }
  5578. }
  5579. modelKey += v.name + ":" + value + ";";
  5580. }
  5581. });
  5582. this._clearFlags(SmartPropertyPrim_1.flagModelDirty);
  5583. this._modelKey = modelKey;
  5584. return modelKey;
  5585. },
  5586. enumerable: true,
  5587. configurable: true
  5588. });
  5589. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  5590. /**
  5591. * States if the Primitive is dirty and should be rendered again next time.
  5592. * @returns true is dirty, false otherwise
  5593. */
  5594. get: function () {
  5595. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim_1.flagModelDirty | SmartPropertyPrim_1.flagModelUpdate | SmartPropertyPrim_1.flagPositioningDirty | SmartPropertyPrim_1.flagLayoutDirty);
  5596. },
  5597. enumerable: true,
  5598. configurable: true
  5599. });
  5600. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  5601. this._setFlags(SmartPropertyPrim_1.flagLevelBoundingInfoDirty | SmartPropertyPrim_1.flagLayoutBoundingInfoDirty);
  5602. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  5603. if (this instanceof BABYLON.Prim2DBase) {
  5604. var curprim = this;
  5605. while (curprim) {
  5606. curprim._setFlags(SmartPropertyPrim_1.flagBoundingInfoDirty | SmartPropertyPrim_1.flagLayoutBoundingInfoDirty);
  5607. if (curprim.isSizeAuto) {
  5608. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  5609. if (curprim._isFlagSet(SmartPropertyPrim_1.flagUsePositioning)) {
  5610. curprim._setFlags(SmartPropertyPrim_1.flagPositioningDirty);
  5611. }
  5612. }
  5613. if (curprim instanceof BABYLON.Group2D) {
  5614. if (curprim.isRenderableGroup) {
  5615. break;
  5616. }
  5617. }
  5618. curprim = curprim.parent;
  5619. }
  5620. }
  5621. };
  5622. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  5623. _super.prototype._handlePropChanged.call(this, curValue, newValue, propName, propInfo, typeLevelCompare);
  5624. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  5625. if (propInfo.dirtyBoundingInfo) {
  5626. this._boundingBoxDirty();
  5627. }
  5628. else if (propInfo.dirtyParentBoundingInfo) {
  5629. var p = this._parent;
  5630. if (p != null) {
  5631. p._boundingBoxDirty();
  5632. }
  5633. }
  5634. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  5635. if (this instanceof BABYLON.Group2D && this._renderableData) {
  5636. this.handleGroupChanged(propInfo);
  5637. }
  5638. // Check for parent layout dirty
  5639. if (this instanceof BABYLON.Prim2DBase) {
  5640. var p = this._parent;
  5641. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  5642. p._setLayoutDirty();
  5643. }
  5644. var that = this;
  5645. if (that.layoutEngine && (that.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  5646. this._setLayoutDirty();
  5647. }
  5648. }
  5649. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  5650. var instanceDirty = false;
  5651. if (typeLevelCompare && curValue != null && newValue != null) {
  5652. var cvProto = curValue.__proto__;
  5653. var nvProto = newValue.__proto__;
  5654. instanceDirty = (cvProto === nvProto);
  5655. }
  5656. // Set the dirty flags
  5657. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  5658. if (!this.isDirty) {
  5659. this.onPrimBecomesDirty();
  5660. this._setFlags(SmartPropertyPrim_1.flagModelDirty);
  5661. }
  5662. }
  5663. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  5664. var propMask = propInfo.flagId;
  5665. this.onPrimitivePropertyDirty(propMask);
  5666. }
  5667. };
  5668. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  5669. this.onPrimBecomesDirty();
  5670. this._instanceDirtyFlags |= propFlagId;
  5671. };
  5672. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  5673. };
  5674. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  5675. _super.prototype._resetPropertiesDirty.call(this);
  5676. this._clearFlags(SmartPropertyPrim_1.flagPrimInDirtyList | SmartPropertyPrim_1.flagNeedRefresh);
  5677. };
  5678. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  5679. /**
  5680. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  5681. */
  5682. get: function () {
  5683. if (this._isFlagSet(SmartPropertyPrim_1.flagLevelBoundingInfoDirty)) {
  5684. if (this.updateLevelBoundingInfo()) {
  5685. this._boundingInfo.dirtyWorldAABB();
  5686. this._clearFlags(SmartPropertyPrim_1.flagLevelBoundingInfoDirty);
  5687. }
  5688. else {
  5689. this._levelBoundingInfo.clear();
  5690. }
  5691. }
  5692. return this._levelBoundingInfo;
  5693. },
  5694. enumerable: true,
  5695. configurable: true
  5696. });
  5697. /**
  5698. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  5699. */
  5700. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  5701. return false;
  5702. };
  5703. /**
  5704. * Property method called when the Primitive becomes dirty
  5705. */
  5706. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  5707. };
  5708. /**
  5709. * Check if a given flag is set
  5710. * @param flag the flag value
  5711. * @return true if set, false otherwise
  5712. */
  5713. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  5714. return (this._flags & flag) !== 0;
  5715. };
  5716. /**
  5717. * Check if all given flags are set
  5718. * @param flags the flags ORed
  5719. * @return true if all the flags are set, false otherwise
  5720. */
  5721. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  5722. return (this._flags & flags) === flags;
  5723. };
  5724. /**
  5725. * Check if at least one flag of the given flags is set
  5726. * @param flags the flags ORed
  5727. * @return true if at least one flag is set, false otherwise
  5728. */
  5729. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  5730. return (this._flags & flags) !== 0;
  5731. };
  5732. /**
  5733. * Clear the given flags
  5734. * @param flags the flags to clear
  5735. */
  5736. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  5737. this._flags &= ~flags;
  5738. };
  5739. /**
  5740. * Set the given flags to true state
  5741. * @param flags the flags ORed to set
  5742. * @return the flags state before this call
  5743. */
  5744. SmartPropertyPrim.prototype._setFlags = function (flags) {
  5745. var cur = this._flags;
  5746. this._flags |= flags;
  5747. return cur;
  5748. };
  5749. /**
  5750. * Change the state of the given flags
  5751. * @param flags the flags ORed to change
  5752. * @param state true to set them, false to clear them
  5753. */
  5754. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  5755. if (state) {
  5756. this._flags |= flags;
  5757. }
  5758. else {
  5759. this._flags &= ~flags;
  5760. }
  5761. };
  5762. SmartPropertyPrim.prototype._getFlagsDebug = function (flags) {
  5763. var res = "";
  5764. if (flags & SmartPropertyPrim_1.flagNoPartOfLayout)
  5765. res += "NoPartOfLayout, ";
  5766. if (flags & SmartPropertyPrim_1.flagLevelBoundingInfoDirty)
  5767. res += "LevelBoundingInfoDirty, ";
  5768. if (flags & SmartPropertyPrim_1.flagModelDirty)
  5769. res += "ModelDirty, ";
  5770. if (flags & SmartPropertyPrim_1.flagLayoutDirty)
  5771. res += "LayoutDirty, ";
  5772. if (flags & SmartPropertyPrim_1.flagLevelVisible)
  5773. res += "LevelVisible, ";
  5774. if (flags & SmartPropertyPrim_1.flagBoundingInfoDirty)
  5775. res += "BoundingInfoDirty, ";
  5776. if (flags & SmartPropertyPrim_1.flagIsPickable)
  5777. res += "IsPickable, ";
  5778. if (flags & SmartPropertyPrim_1.flagIsVisible)
  5779. res += "IsVisible, ";
  5780. if (flags & SmartPropertyPrim_1.flagVisibilityChanged)
  5781. res += "VisibilityChanged, ";
  5782. if (flags & SmartPropertyPrim_1.flagPositioningDirty)
  5783. res += "PositioningDirty, ";
  5784. if (flags & SmartPropertyPrim_1.flagTrackedGroup)
  5785. res += "TrackedGroup, ";
  5786. if (flags & SmartPropertyPrim_1.flagWorldCacheChanged)
  5787. res += "WorldCacheChanged, ";
  5788. if (flags & SmartPropertyPrim_1.flagChildrenFlatZOrder)
  5789. res += "ChildrenFlatZOrder, ";
  5790. if (flags & SmartPropertyPrim_1.flagZOrderDirty)
  5791. res += "ZOrderDirty, ";
  5792. if (flags & SmartPropertyPrim_1.flagActualOpacityDirty)
  5793. res += "ActualOpacityDirty, ";
  5794. if (flags & SmartPropertyPrim_1.flagPrimInDirtyList)
  5795. res += "PrimInDirtyList, ";
  5796. if (flags & SmartPropertyPrim_1.flagIsContainer)
  5797. res += "IsContainer, ";
  5798. if (flags & SmartPropertyPrim_1.flagNeedRefresh)
  5799. res += "NeedRefresh, ";
  5800. if (flags & SmartPropertyPrim_1.flagActualScaleDirty)
  5801. res += "ActualScaleDirty, ";
  5802. if (flags & SmartPropertyPrim_1.flagDontInheritParentScale)
  5803. res += "DontInheritParentScale, ";
  5804. if (flags & SmartPropertyPrim_1.flagGlobalTransformDirty)
  5805. res += "GlobalTransformDirty, ";
  5806. if (flags & SmartPropertyPrim_1.flagLayoutBoundingInfoDirty)
  5807. res += "LayoutBoundingInfoDirty, ";
  5808. if (flags & SmartPropertyPrim_1.flagCollisionActor)
  5809. res += "CollisionActor, ";
  5810. if (flags & SmartPropertyPrim_1.flagModelUpdate)
  5811. res += "ModelUpdate, ";
  5812. if (flags & SmartPropertyPrim_1.flagLocalTransformDirty)
  5813. res += "LocalTransformDirty, ";
  5814. if (flags & SmartPropertyPrim_1.flagUsePositioning)
  5815. res += "UsePositioning, ";
  5816. if (flags & SmartPropertyPrim_1.flagComputingPositioning)
  5817. res += "ComputingPositioning, ";
  5818. return res.slice(0, res.length - 2);
  5819. };
  5820. return SmartPropertyPrim;
  5821. }(SmartPropertyBase));
  5822. SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT = 0;
  5823. SmartPropertyPrim.flagNoPartOfLayout = 0x0000001; // set if the primitive's position/size must not be computed by Layout Engine
  5824. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  5825. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  5826. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  5827. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  5828. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  5829. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  5830. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  5831. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  5832. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  5833. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  5834. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  5835. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  5836. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  5837. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  5838. SmartPropertyPrim.flagPrimInDirtyList = 0x0008000; // set if the primitive is in the primDirtyList
  5839. SmartPropertyPrim.flagIsContainer = 0x0010000; // set if the primitive is a container
  5840. SmartPropertyPrim.flagNeedRefresh = 0x0020000; // set if the primitive wasn't successful at refresh
  5841. SmartPropertyPrim.flagActualScaleDirty = 0x0040000; // set if the actualScale property needs to be recomputed
  5842. SmartPropertyPrim.flagDontInheritParentScale = 0x0080000; // set if the actualScale must not use its parent's scale to be computed
  5843. SmartPropertyPrim.flagGlobalTransformDirty = 0x0100000; // set if the global transform must be recomputed due to a local transform change
  5844. SmartPropertyPrim.flagLayoutBoundingInfoDirty = 0x0200000; // set if the layout bounding info is dirty
  5845. SmartPropertyPrim.flagCollisionActor = 0x0400000; // set if the primitive is part of the collision engine
  5846. SmartPropertyPrim.flagModelUpdate = 0x0800000; // set if the primitive's model data is to update
  5847. SmartPropertyPrim.flagLocalTransformDirty = 0x1000000; // set if the local transformation matrix must be recomputed
  5848. SmartPropertyPrim.flagUsePositioning = 0x2000000; // set if the primitive rely on the positioning engine (padding or margin is used)
  5849. SmartPropertyPrim.flagComputingPositioning = 0x4000000; // set if the positioning engine is computing the primitive, used to avoid re entrance
  5850. SmartPropertyPrim.flagAlignPrimitive = 0x8000000; // set if the primitive should be pixel aligned to the render target
  5851. __decorate([
  5852. BABYLON.logProp()
  5853. ], SmartPropertyPrim.prototype, "levelBoundingInfo", null);
  5854. SmartPropertyPrim = SmartPropertyPrim_1 = __decorate([
  5855. BABYLON.className("SmartPropertyPrim", "BABYLON")
  5856. ], SmartPropertyPrim);
  5857. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  5858. function dependencyProperty(propId, piStore, mode, updateSourceTrigger) {
  5859. if (mode === void 0) { mode = DataBinding.MODE_TWOWAY; }
  5860. if (updateSourceTrigger === void 0) { updateSourceTrigger = DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED; }
  5861. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_DYNAMIC, { bindingMode: mode, bindingUpdateSourceTrigger: updateSourceTrigger });
  5862. }
  5863. BABYLON.dependencyProperty = dependencyProperty;
  5864. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  5865. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  5866. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  5867. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  5868. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_MODEL, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  5869. }
  5870. BABYLON.modelLevelProperty = modelLevelProperty;
  5871. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  5872. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  5873. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  5874. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  5875. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_INSTANCE, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  5876. }
  5877. BABYLON.instanceLevelProperty = instanceLevelProperty;
  5878. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  5879. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  5880. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  5881. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  5882. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_DYNAMIC, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  5883. }
  5884. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  5885. var DataBinding_1, SmartPropertyBase_1, SmartPropertyPrim_1;
  5886. })(BABYLON || (BABYLON = {}));
  5887. //# sourceMappingURL=babylon.smartPropertyPrim.js.map
  5888. var __extends = (this && this.__extends) || function (d, b) {
  5889. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5890. function __() { this.constructor = d; }
  5891. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5892. };
  5893. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  5894. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  5895. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  5896. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5897. return c > 3 && r && Object.defineProperty(target, key, r), r;
  5898. };
  5899. var BABYLON;
  5900. (function (BABYLON) {
  5901. var PrepareRender2DContext = (function () {
  5902. function PrepareRender2DContext() {
  5903. this.forceRefreshPrimitive = false;
  5904. }
  5905. return PrepareRender2DContext;
  5906. }());
  5907. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  5908. var Render2DContext = (function () {
  5909. function Render2DContext(renderMode) {
  5910. this._renderMode = renderMode;
  5911. this.useInstancing = false;
  5912. this.groupInfoPartData = null;
  5913. this.partDataStartIndex = this.partDataEndIndex = null;
  5914. this.instancedBuffers = null;
  5915. }
  5916. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  5917. /**
  5918. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  5919. */
  5920. get: function () {
  5921. return this._renderMode;
  5922. },
  5923. enumerable: true,
  5924. configurable: true
  5925. });
  5926. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  5927. /**
  5928. * The set of primitives to render is opaque.
  5929. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  5930. */
  5931. get: function () {
  5932. return Render2DContext._renderModeOpaque;
  5933. },
  5934. enumerable: true,
  5935. configurable: true
  5936. });
  5937. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  5938. /**
  5939. * The set of primitives to render is using Alpha Test (aka masking).
  5940. * Alpha Blend is enabled, the AlphaMode must be manually set, the render occurs after the RenderModeOpaque and is depth independent (i.e. primitives are not sorted by depth). Depth Compare and Write are both enabled.
  5941. */
  5942. get: function () {
  5943. return Render2DContext._renderModeAlphaTest;
  5944. },
  5945. enumerable: true,
  5946. configurable: true
  5947. });
  5948. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  5949. /**
  5950. * The set of primitives to render is transparent.
  5951. * Alpha Blend is enabled, the AlphaMode must be manually set, the render occurs after the RenderModeAlphaTest and is depth dependent (i.e. primitives are stored by depth and rendered back to front). Depth Compare is on, but Depth write is Off.
  5952. */
  5953. get: function () {
  5954. return Render2DContext._renderModeTransparent;
  5955. },
  5956. enumerable: true,
  5957. configurable: true
  5958. });
  5959. return Render2DContext;
  5960. }());
  5961. Render2DContext._renderModeOpaque = 1;
  5962. Render2DContext._renderModeAlphaTest = 2;
  5963. Render2DContext._renderModeTransparent = 3;
  5964. BABYLON.Render2DContext = Render2DContext;
  5965. /**
  5966. * This class store information for the pointerEventObservable Observable.
  5967. * The Observable is divided into many sub events (using the Mask feature of the Observable pattern): PointerOver, PointerEnter, PointerDown, PointerMouseWheel, PointerMove, PointerUp, PointerDown, PointerLeave, PointerGotCapture and PointerLostCapture.
  5968. */
  5969. var PrimitivePointerInfo = (function () {
  5970. function PrimitivePointerInfo() {
  5971. this.primitivePointerPos = BABYLON.Vector2.Zero();
  5972. this.tilt = BABYLON.Vector2.Zero();
  5973. this.cancelBubble = false;
  5974. }
  5975. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  5976. // The behavior is based on the HTML specifications of the Pointer Events (https://www.w3.org/TR/pointerevents/#list-of-pointer-events). This is not 100% compliant and not meant to be, but still, it's based on these specs for most use cases to be programmed the same way (as closest as possible) as it would have been in HTML.
  5977. /**
  5978. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  5979. * Bubbles: yes
  5980. */
  5981. get: function () {
  5982. return PrimitivePointerInfo._pointerOver;
  5983. },
  5984. enumerable: true,
  5985. configurable: true
  5986. });
  5987. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  5988. /**
  5989. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  5990. * Bubbles: no
  5991. */
  5992. get: function () {
  5993. return PrimitivePointerInfo._pointerEnter;
  5994. },
  5995. enumerable: true,
  5996. configurable: true
  5997. });
  5998. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  5999. /**
  6000. * This event type is raised when a pointer enters the active button state (non-zero value in the buttons property). For mouse it's when the device transitions from no buttons depressed to at least one button depressed. For touch/pen this is when a physical contact is made.
  6001. * Bubbles: yes
  6002. */
  6003. get: function () {
  6004. return PrimitivePointerInfo._pointerDown;
  6005. },
  6006. enumerable: true,
  6007. configurable: true
  6008. });
  6009. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  6010. /**
  6011. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  6012. * Bubbles: yes
  6013. */
  6014. get: function () {
  6015. return PrimitivePointerInfo._pointerMouseWheel;
  6016. },
  6017. enumerable: true,
  6018. configurable: true
  6019. });
  6020. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  6021. /**
  6022. * This event type is raised when a pointer change coordinates or when a pointer changes button state, pressure, tilt, or contact geometry and the circumstances produce no other pointers events.
  6023. * Bubbles: yes
  6024. */
  6025. get: function () {
  6026. return PrimitivePointerInfo._pointerMove;
  6027. },
  6028. enumerable: true,
  6029. configurable: true
  6030. });
  6031. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  6032. /**
  6033. * This event type is raised when the pointer leaves the active buttons states (zero value in the buttons property). For mouse, this is when the device transitions from at least one button depressed to no buttons depressed. For touch/pen, this is when physical contact is removed.
  6034. * Bubbles: yes
  6035. */
  6036. get: function () {
  6037. return PrimitivePointerInfo._pointerUp;
  6038. },
  6039. enumerable: true,
  6040. configurable: true
  6041. });
  6042. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  6043. /**
  6044. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  6045. * Bubbles: yes
  6046. */
  6047. get: function () {
  6048. return PrimitivePointerInfo._pointerOut;
  6049. },
  6050. enumerable: true,
  6051. configurable: true
  6052. });
  6053. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  6054. /**
  6055. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  6056. * Bubbles: no
  6057. */
  6058. get: function () {
  6059. return PrimitivePointerInfo._pointerLeave;
  6060. },
  6061. enumerable: true,
  6062. configurable: true
  6063. });
  6064. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  6065. /**
  6066. * This event type is raised when a primitive receives the pointer capture. This event is fired at the element that is receiving pointer capture. Subsequent events for that pointer will be fired at this element.
  6067. * Bubbles: yes
  6068. */
  6069. get: function () {
  6070. return PrimitivePointerInfo._pointerGotCapture;
  6071. },
  6072. enumerable: true,
  6073. configurable: true
  6074. });
  6075. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  6076. /**
  6077. * This event type is raised after pointer capture is released for a pointer.
  6078. * Bubbles: yes
  6079. */
  6080. get: function () {
  6081. return PrimitivePointerInfo._pointerLostCapture;
  6082. },
  6083. enumerable: true,
  6084. configurable: true
  6085. });
  6086. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  6087. get: function () {
  6088. return PrimitivePointerInfo._mouseWheelPrecision;
  6089. },
  6090. enumerable: true,
  6091. configurable: true
  6092. });
  6093. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  6094. this.relatedTarget = prim;
  6095. this.relatedTargetPointerPos = primPointerPos;
  6096. };
  6097. PrimitivePointerInfo.getEventTypeName = function (mask) {
  6098. switch (mask) {
  6099. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  6100. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  6101. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  6102. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  6103. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  6104. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  6105. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  6106. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  6107. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  6108. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  6109. }
  6110. };
  6111. return PrimitivePointerInfo;
  6112. }());
  6113. PrimitivePointerInfo._pointerOver = 0x0001;
  6114. PrimitivePointerInfo._pointerEnter = 0x0002;
  6115. PrimitivePointerInfo._pointerDown = 0x0004;
  6116. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  6117. PrimitivePointerInfo._pointerMove = 0x0010;
  6118. PrimitivePointerInfo._pointerUp = 0x0020;
  6119. PrimitivePointerInfo._pointerOut = 0x0040;
  6120. PrimitivePointerInfo._pointerLeave = 0x0080;
  6121. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  6122. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  6123. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  6124. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  6125. /**
  6126. * Defines the horizontal and vertical alignment information for a Primitive.
  6127. */
  6128. var PrimitiveAlignment = PrimitiveAlignment_1 = (function () {
  6129. function PrimitiveAlignment(changeCallback) {
  6130. this._changedCallback = changeCallback;
  6131. this._horizontal = PrimitiveAlignment_1.AlignLeft;
  6132. this._vertical = PrimitiveAlignment_1.AlignBottom;
  6133. }
  6134. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  6135. /**
  6136. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  6137. */
  6138. get: function () { return PrimitiveAlignment_1._AlignLeft; },
  6139. enumerable: true,
  6140. configurable: true
  6141. });
  6142. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  6143. /**
  6144. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  6145. */
  6146. get: function () { return PrimitiveAlignment_1._AlignTop; },
  6147. enumerable: true,
  6148. configurable: true
  6149. });
  6150. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  6151. /**
  6152. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  6153. */
  6154. get: function () { return PrimitiveAlignment_1._AlignRight; },
  6155. enumerable: true,
  6156. configurable: true
  6157. });
  6158. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  6159. /**
  6160. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  6161. */
  6162. get: function () { return PrimitiveAlignment_1._AlignBottom; },
  6163. enumerable: true,
  6164. configurable: true
  6165. });
  6166. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  6167. /**
  6168. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  6169. */
  6170. get: function () { return PrimitiveAlignment_1._AlignCenter; },
  6171. enumerable: true,
  6172. configurable: true
  6173. });
  6174. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  6175. /**
  6176. * The content is stretched toward the opposite edges of the Primitive
  6177. */
  6178. get: function () { return PrimitiveAlignment_1._AlignStretch; },
  6179. enumerable: true,
  6180. configurable: true
  6181. });
  6182. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  6183. /**
  6184. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  6185. */
  6186. get: function () {
  6187. return this._horizontal;
  6188. },
  6189. set: function (value) {
  6190. if (this._horizontal === value) {
  6191. return;
  6192. }
  6193. this._horizontal = value;
  6194. this.onChangeCallback();
  6195. },
  6196. enumerable: true,
  6197. configurable: true
  6198. });
  6199. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  6200. /**
  6201. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  6202. */
  6203. get: function () {
  6204. return this._vertical;
  6205. },
  6206. set: function (value) {
  6207. if (this._vertical === value) {
  6208. return;
  6209. }
  6210. this._vertical = value;
  6211. this.onChangeCallback();
  6212. },
  6213. enumerable: true,
  6214. configurable: true
  6215. });
  6216. PrimitiveAlignment.prototype.onChangeCallback = function () {
  6217. if (this._changedCallback) {
  6218. this._changedCallback();
  6219. }
  6220. };
  6221. /**
  6222. * Set the horizontal alignment from a string value.
  6223. * @param text can be either: 'left','right','center','stretch'
  6224. */
  6225. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  6226. var v = text.trim().toLocaleLowerCase();
  6227. switch (v) {
  6228. case "left":
  6229. this.horizontal = PrimitiveAlignment_1.AlignLeft;
  6230. return;
  6231. case "right":
  6232. this.horizontal = PrimitiveAlignment_1.AlignRight;
  6233. return;
  6234. case "center":
  6235. this.horizontal = PrimitiveAlignment_1.AlignCenter;
  6236. return;
  6237. case "stretch":
  6238. this.horizontal = PrimitiveAlignment_1.AlignStretch;
  6239. return;
  6240. }
  6241. };
  6242. /**
  6243. * Set the vertical alignment from a string value.
  6244. * @param text can be either: 'top','bottom','center','stretch'
  6245. */
  6246. PrimitiveAlignment.prototype.setVertical = function (text) {
  6247. var v = text.trim().toLocaleLowerCase();
  6248. switch (v) {
  6249. case "top":
  6250. this.vertical = PrimitiveAlignment_1.AlignTop;
  6251. return;
  6252. case "bottom":
  6253. this.vertical = PrimitiveAlignment_1.AlignBottom;
  6254. return;
  6255. case "center":
  6256. this.vertical = PrimitiveAlignment_1.AlignCenter;
  6257. return;
  6258. case "stretch":
  6259. this.vertical = PrimitiveAlignment_1.AlignStretch;
  6260. return;
  6261. }
  6262. };
  6263. /**
  6264. * Set the horizontal and or vertical alignments from a string value.
  6265. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  6266. */
  6267. PrimitiveAlignment.prototype.fromString = function (value) {
  6268. var m = value.trim().split(",");
  6269. if (m.length === 1) {
  6270. this.setHorizontal(m[0]);
  6271. this.setVertical(m[0]);
  6272. }
  6273. else {
  6274. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  6275. var v = m_1[_i];
  6276. v = v.toLocaleLowerCase().trim();
  6277. // Horizontal
  6278. var i = v.indexOf("h:");
  6279. if (i === -1) {
  6280. i = v.indexOf("horizontal:");
  6281. }
  6282. if (i !== -1) {
  6283. v = v.substr(v.indexOf(":") + 1);
  6284. this.setHorizontal(v);
  6285. continue;
  6286. }
  6287. // Vertical
  6288. i = v.indexOf("v:");
  6289. if (i === -1) {
  6290. i = v.indexOf("vertical:");
  6291. }
  6292. if (i !== -1) {
  6293. v = v.substr(v.indexOf(":") + 1);
  6294. this.setVertical(v);
  6295. continue;
  6296. }
  6297. }
  6298. }
  6299. };
  6300. PrimitiveAlignment.prototype.copyFrom = function (pa) {
  6301. this._horizontal = pa._horizontal;
  6302. this._vertical = pa._vertical;
  6303. this.onChangeCallback();
  6304. };
  6305. PrimitiveAlignment.prototype.clone = function () {
  6306. var pa = new PrimitiveAlignment_1();
  6307. pa._horizontal = this._horizontal;
  6308. pa._vertical = this._vertical;
  6309. return pa;
  6310. };
  6311. Object.defineProperty(PrimitiveAlignment.prototype, "isDefault", {
  6312. get: function () {
  6313. return this.horizontal === PrimitiveAlignment_1.AlignLeft && this.vertical === PrimitiveAlignment_1.AlignBottom;
  6314. },
  6315. enumerable: true,
  6316. configurable: true
  6317. });
  6318. return PrimitiveAlignment;
  6319. }());
  6320. PrimitiveAlignment._AlignLeft = 1;
  6321. PrimitiveAlignment._AlignTop = 1; // Same as left
  6322. PrimitiveAlignment._AlignRight = 2;
  6323. PrimitiveAlignment._AlignBottom = 2; // Same as right
  6324. PrimitiveAlignment._AlignCenter = 3;
  6325. PrimitiveAlignment._AlignStretch = 4;
  6326. PrimitiveAlignment = PrimitiveAlignment_1 = __decorate([
  6327. BABYLON.className("PrimitiveAlignment", "BABYLON")
  6328. ], PrimitiveAlignment);
  6329. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  6330. /**
  6331. * Stores information about a Primitive that was intersected
  6332. */
  6333. var PrimitiveIntersectedInfo = (function () {
  6334. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  6335. this.prim = prim;
  6336. this.intersectionLocation = intersectionLocation;
  6337. }
  6338. return PrimitiveIntersectedInfo;
  6339. }());
  6340. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  6341. /**
  6342. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  6343. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  6344. */
  6345. var PrimitiveThickness = PrimitiveThickness_1 = (function () {
  6346. function PrimitiveThickness(parentAccess, changedCallback) {
  6347. this._parentAccess = parentAccess;
  6348. this._changedCallback = changedCallback;
  6349. this._pixels = new Array(4);
  6350. this._percentages = new Array(4);
  6351. this._setType(0, PrimitiveThickness_1.Auto);
  6352. this._setType(1, PrimitiveThickness_1.Auto);
  6353. this._setType(2, PrimitiveThickness_1.Auto);
  6354. this._setType(3, PrimitiveThickness_1.Auto);
  6355. this._pixels[0] = 0;
  6356. this._pixels[1] = 0;
  6357. this._pixels[2] = 0;
  6358. this._pixels[3] = 0;
  6359. }
  6360. /**
  6361. * Set the thickness from a string value
  6362. * @param thickness format is "top: <value>, left:<value>, right:<value>, bottom:<value>" or "<value>" (same for all edges) each are optional, auto will be set if it's omitted.
  6363. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  6364. */
  6365. PrimitiveThickness.prototype.fromString = function (thickness) {
  6366. this._clear();
  6367. var m = thickness.trim().split(",");
  6368. // Special case, one value to apply to all edges
  6369. if (m.length === 1 && thickness.indexOf(":") === -1) {
  6370. this._setStringValue(m[0], 0, false);
  6371. this._setStringValue(m[0], 1, false);
  6372. this._setStringValue(m[0], 2, false);
  6373. this._setStringValue(m[0], 3, false);
  6374. this.onChangeCallback();
  6375. return;
  6376. }
  6377. var res = false;
  6378. for (var _i = 0, m_2 = m; _i < m_2.length; _i++) {
  6379. var cm = m_2[_i];
  6380. res = this._extractString(cm, false) || res;
  6381. }
  6382. if (!res) {
  6383. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  6384. }
  6385. // Check the margin that weren't set and set them in auto
  6386. if ((this._flags & 0x000F) === 0)
  6387. this._flags |= PrimitiveThickness_1.Pixel << 0;
  6388. if ((this._flags & 0x00F0) === 0)
  6389. this._flags |= PrimitiveThickness_1.Pixel << 4;
  6390. if ((this._flags & 0x0F00) === 0)
  6391. this._flags |= PrimitiveThickness_1.Pixel << 8;
  6392. if ((this._flags & 0xF000) === 0)
  6393. this._flags |= PrimitiveThickness_1.Pixel << 12;
  6394. this.onChangeCallback();
  6395. };
  6396. /**
  6397. * Set the thickness from multiple string
  6398. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  6399. * @param top the top thickness to set
  6400. * @param left the left thickness to set
  6401. * @param right the right thickness to set
  6402. * @param bottom the bottom thickness to set
  6403. */
  6404. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  6405. this._clear();
  6406. this._setStringValue(top, 0, false);
  6407. this._setStringValue(left, 1, false);
  6408. this._setStringValue(right, 2, false);
  6409. this._setStringValue(bottom, 3, false);
  6410. this.onChangeCallback();
  6411. return this;
  6412. };
  6413. /**
  6414. * Set the thickness from pixel values
  6415. * @param top the top thickness in pixels to set
  6416. * @param left the left thickness in pixels to set
  6417. * @param right the right thickness in pixels to set
  6418. * @param bottom the bottom thickness in pixels to set
  6419. */
  6420. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  6421. this._clear();
  6422. this._pixels[0] = top;
  6423. this._pixels[1] = left;
  6424. this._pixels[2] = right;
  6425. this._pixels[3] = bottom;
  6426. this.onChangeCallback();
  6427. return this;
  6428. };
  6429. /**
  6430. * Apply the same pixel value to all edges
  6431. * @param margin the value to set, in pixels.
  6432. */
  6433. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  6434. this._clear();
  6435. this._pixels[0] = margin;
  6436. this._pixels[1] = margin;
  6437. this._pixels[2] = margin;
  6438. this._pixels[3] = margin;
  6439. this.onChangeCallback();
  6440. return this;
  6441. };
  6442. PrimitiveThickness.prototype.copyFrom = function (pt) {
  6443. this._clear();
  6444. for (var i = 0; i < 4; i++) {
  6445. this._pixels[i] = pt._pixels[i];
  6446. this._percentages[i] = pt._percentages[i];
  6447. }
  6448. this._flags = pt._flags;
  6449. this.onChangeCallback();
  6450. };
  6451. /**
  6452. * Set all edges in auto
  6453. */
  6454. PrimitiveThickness.prototype.auto = function () {
  6455. this._clear();
  6456. this._flags = (PrimitiveThickness_1.Auto << 0) | (PrimitiveThickness_1.Auto << 4) | (PrimitiveThickness_1.Auto << 8) | (PrimitiveThickness_1.Auto << 12);
  6457. this._pixels[0] = 0;
  6458. this._pixels[1] = 0;
  6459. this._pixels[2] = 0;
  6460. this._pixels[3] = 0;
  6461. this.onChangeCallback();
  6462. return this;
  6463. };
  6464. PrimitiveThickness.prototype._clear = function () {
  6465. this._flags = 0;
  6466. this._pixels[0] = 0;
  6467. this._pixels[1] = 0;
  6468. this._pixels[2] = 0;
  6469. this._pixels[3] = 0;
  6470. this._percentages[0] = null;
  6471. this._percentages[1] = null;
  6472. this._percentages[2] = null;
  6473. this._percentages[3] = null;
  6474. };
  6475. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  6476. var v = value.trim().toLocaleLowerCase();
  6477. if (v.indexOf("top:") === 0) {
  6478. v = v.substr(4).trim();
  6479. return this._setStringValue(v, 0, emitChanged);
  6480. }
  6481. if (v.indexOf("left:") === 0) {
  6482. v = v.substr(5).trim();
  6483. return this._setStringValue(v, 1, emitChanged);
  6484. }
  6485. if (v.indexOf("right:") === 0) {
  6486. v = v.substr(6).trim();
  6487. return this._setStringValue(v, 2, emitChanged);
  6488. }
  6489. if (v.indexOf("bottom:") === 0) {
  6490. v = v.substr(7).trim();
  6491. return this._setStringValue(v, 3, emitChanged);
  6492. }
  6493. return false;
  6494. };
  6495. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  6496. // Check for auto
  6497. var v = value.trim().toLocaleLowerCase();
  6498. if (v === "auto") {
  6499. if (this._isType(index, PrimitiveThickness_1.Auto)) {
  6500. return true;
  6501. }
  6502. this._setType(index, PrimitiveThickness_1.Auto);
  6503. this._pixels[index] = 0;
  6504. if (emitChanged) {
  6505. this.onChangeCallback();
  6506. }
  6507. }
  6508. else if (v === "inherit") {
  6509. if (this._isType(index, PrimitiveThickness_1.Inherit)) {
  6510. return true;
  6511. }
  6512. this._setType(index, PrimitiveThickness_1.Inherit);
  6513. this._pixels[index] = null;
  6514. if (emitChanged) {
  6515. this.onChangeCallback();
  6516. }
  6517. }
  6518. else {
  6519. var pI = v.indexOf("%");
  6520. // Check for percentage
  6521. if (pI !== -1) {
  6522. var n_1 = v.substr(0, pI);
  6523. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  6524. if (this._isType(index, PrimitiveThickness_1.Percentage) && (this._percentages[index] === number_1)) {
  6525. return true;
  6526. }
  6527. this._setType(index, PrimitiveThickness_1.Percentage);
  6528. if (isNaN(number_1)) {
  6529. return false;
  6530. }
  6531. this._percentages[index] = number_1;
  6532. if (emitChanged) {
  6533. this.onChangeCallback();
  6534. }
  6535. return true;
  6536. }
  6537. // Check for pixel
  6538. var n = void 0;
  6539. pI = v.indexOf("px");
  6540. if (pI !== -1) {
  6541. n = v.substr(0, pI).trim();
  6542. }
  6543. else {
  6544. n = v;
  6545. }
  6546. var number = Number(n);
  6547. if (this._isType(index, PrimitiveThickness_1.Pixel) && (this._pixels[index] === number)) {
  6548. return true;
  6549. }
  6550. if (isNaN(number)) {
  6551. return false;
  6552. }
  6553. this._pixels[index] = number;
  6554. this._setType(index, PrimitiveThickness_1.Pixel);
  6555. if (emitChanged) {
  6556. this.onChangeCallback();
  6557. }
  6558. return true;
  6559. }
  6560. };
  6561. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  6562. // Round the value because, well, it's the thing to do! Otherwise we'll have sub-pixel stuff, and the no change comparison just below will almost never work for PrimitiveThickness values inside a hierarchy of Primitives
  6563. value = Math.round(value);
  6564. if (this._isType(index, PrimitiveThickness_1.Pixel) && this._pixels[index] === value) {
  6565. return;
  6566. }
  6567. this._setType(index, PrimitiveThickness_1.Pixel);
  6568. this._pixels[index] = value;
  6569. if (emitChanged) {
  6570. this.onChangeCallback();
  6571. }
  6572. };
  6573. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  6574. // Clip Value to bounds
  6575. value = Math.min(1, value);
  6576. value = Math.max(0, value);
  6577. value = Math.round(value * 100) / 100; // 0.01 precision
  6578. if (this._isType(index, PrimitiveThickness_1.Percentage) && this._percentages[index] === value) {
  6579. return;
  6580. }
  6581. this._setType(index, PrimitiveThickness_1.Percentage);
  6582. this._percentages[index] = value;
  6583. if (emitChanged) {
  6584. this.onChangeCallback();
  6585. }
  6586. };
  6587. PrimitiveThickness.prototype._getStringValue = function (index) {
  6588. var f = (this._flags >> (index * 4)) & 0xF;
  6589. switch (f) {
  6590. case PrimitiveThickness_1.Auto:
  6591. return "auto";
  6592. case PrimitiveThickness_1.Pixel:
  6593. return this._pixels[index] + "px";
  6594. case PrimitiveThickness_1.Percentage:
  6595. return this._percentages[index] * 100 + "%";
  6596. case PrimitiveThickness_1.Inherit:
  6597. return "inherit";
  6598. }
  6599. return "";
  6600. };
  6601. PrimitiveThickness.prototype._isType = function (index, type) {
  6602. var f = (this._flags >> (index * 4)) & 0xF;
  6603. return f === type;
  6604. };
  6605. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  6606. var t = (this._flags >> (index * 4)) & 0xF;
  6607. if (processInherit && (t === PrimitiveThickness_1.Inherit)) {
  6608. var p = this._parentAccess();
  6609. if (p) {
  6610. return p._getType(index, true);
  6611. }
  6612. return PrimitiveThickness_1.Auto;
  6613. }
  6614. return t;
  6615. };
  6616. PrimitiveThickness.prototype._setType = function (index, type) {
  6617. this._flags &= ~(0xF << (index * 4));
  6618. this._flags |= type << (index * 4);
  6619. };
  6620. PrimitiveThickness.prototype.setTop = function (value) {
  6621. if (typeof value === "string") {
  6622. this._setStringValue(value, 0, true);
  6623. }
  6624. else {
  6625. this.topPixels = value;
  6626. }
  6627. };
  6628. PrimitiveThickness.prototype.setLeft = function (value) {
  6629. if (typeof value === "string") {
  6630. this._setStringValue(value, 1, true);
  6631. }
  6632. else {
  6633. this.leftPixels = value;
  6634. }
  6635. };
  6636. PrimitiveThickness.prototype.setRight = function (value) {
  6637. if (typeof value === "string") {
  6638. this._setStringValue(value, 2, true);
  6639. }
  6640. else {
  6641. this.rightPixels = value;
  6642. }
  6643. };
  6644. PrimitiveThickness.prototype.setBottom = function (value) {
  6645. if (typeof value === "string") {
  6646. this._setStringValue(value, 3, true);
  6647. }
  6648. else {
  6649. this.bottomPixels = value;
  6650. }
  6651. };
  6652. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  6653. /**
  6654. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  6655. */
  6656. get: function () {
  6657. return this._getStringValue(0);
  6658. },
  6659. set: function (value) {
  6660. this._setStringValue(value, 0, true);
  6661. },
  6662. enumerable: true,
  6663. configurable: true
  6664. });
  6665. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  6666. /**
  6667. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  6668. */
  6669. get: function () {
  6670. return this._getStringValue(1);
  6671. },
  6672. set: function (value) {
  6673. this._setStringValue(value, 1, true);
  6674. },
  6675. enumerable: true,
  6676. configurable: true
  6677. });
  6678. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  6679. /**
  6680. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  6681. */
  6682. get: function () {
  6683. return this._getStringValue(2);
  6684. },
  6685. set: function (value) {
  6686. this._setStringValue(value, 2, true);
  6687. },
  6688. enumerable: true,
  6689. configurable: true
  6690. });
  6691. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  6692. /**
  6693. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  6694. */
  6695. get: function () {
  6696. return this._getStringValue(3);
  6697. },
  6698. set: function (value) {
  6699. this._setStringValue(value, 3, true);
  6700. },
  6701. enumerable: true,
  6702. configurable: true
  6703. });
  6704. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  6705. /**
  6706. * Get/set the top thickness in pixel.
  6707. */
  6708. get: function () {
  6709. return this._pixels[0];
  6710. },
  6711. set: function (value) {
  6712. this._setPixels(value, 0, true);
  6713. },
  6714. enumerable: true,
  6715. configurable: true
  6716. });
  6717. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  6718. /**
  6719. * Get/set the left thickness in pixel.
  6720. */
  6721. get: function () {
  6722. return this._pixels[1];
  6723. },
  6724. set: function (value) {
  6725. this._setPixels(value, 1, true);
  6726. },
  6727. enumerable: true,
  6728. configurable: true
  6729. });
  6730. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  6731. /**
  6732. * Get/set the right thickness in pixel.
  6733. */
  6734. get: function () {
  6735. return this._pixels[2];
  6736. },
  6737. set: function (value) {
  6738. this._setPixels(value, 2, true);
  6739. },
  6740. enumerable: true,
  6741. configurable: true
  6742. });
  6743. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  6744. /**
  6745. * Get/set the bottom thickness in pixel.
  6746. */
  6747. get: function () {
  6748. return this._pixels[3];
  6749. },
  6750. set: function (value) {
  6751. this._setPixels(value, 3, true);
  6752. },
  6753. enumerable: true,
  6754. configurable: true
  6755. });
  6756. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  6757. /**
  6758. * Get/set the top thickness in percentage.
  6759. * The get will return a valid value only if the edge type is percentage.
  6760. * The Set will change the edge mode if needed
  6761. */
  6762. get: function () {
  6763. return this._percentages[0];
  6764. },
  6765. set: function (value) {
  6766. this._setPercentage(value, 0, true);
  6767. },
  6768. enumerable: true,
  6769. configurable: true
  6770. });
  6771. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  6772. /**
  6773. * Get/set the left thickness in percentage.
  6774. * The get will return a valid value only if the edge mode is percentage.
  6775. * The Set will change the edge mode if needed
  6776. */
  6777. get: function () {
  6778. return this._percentages[1];
  6779. },
  6780. set: function (value) {
  6781. this._setPercentage(value, 1, true);
  6782. },
  6783. enumerable: true,
  6784. configurable: true
  6785. });
  6786. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  6787. /**
  6788. * Get/set the right thickness in percentage.
  6789. * The get will return a valid value only if the edge mode is percentage.
  6790. * The Set will change the edge mode if needed
  6791. */
  6792. get: function () {
  6793. return this._percentages[2];
  6794. },
  6795. set: function (value) {
  6796. this._setPercentage(value, 2, true);
  6797. },
  6798. enumerable: true,
  6799. configurable: true
  6800. });
  6801. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  6802. /**
  6803. * Get/set the bottom thickness in percentage.
  6804. * The get will return a valid value only if the edge mode is percentage.
  6805. * The Set will change the edge mode if needed
  6806. */
  6807. get: function () {
  6808. return this._percentages[3];
  6809. },
  6810. set: function (value) {
  6811. this._setPercentage(value, 3, true);
  6812. },
  6813. enumerable: true,
  6814. configurable: true
  6815. });
  6816. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  6817. /**
  6818. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  6819. */
  6820. get: function () {
  6821. return this._getType(0, false);
  6822. },
  6823. set: function (mode) {
  6824. this._setType(0, mode);
  6825. },
  6826. enumerable: true,
  6827. configurable: true
  6828. });
  6829. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  6830. /**
  6831. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  6832. */
  6833. get: function () {
  6834. return this._getType(1, false);
  6835. },
  6836. set: function (mode) {
  6837. this._setType(1, mode);
  6838. },
  6839. enumerable: true,
  6840. configurable: true
  6841. });
  6842. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  6843. /**
  6844. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  6845. */
  6846. get: function () {
  6847. return this._getType(2, false);
  6848. },
  6849. set: function (mode) {
  6850. this._setType(2, mode);
  6851. },
  6852. enumerable: true,
  6853. configurable: true
  6854. });
  6855. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  6856. /**
  6857. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  6858. */
  6859. get: function () {
  6860. return this._getType(3, false);
  6861. },
  6862. set: function (mode) {
  6863. this._setType(3, mode);
  6864. },
  6865. enumerable: true,
  6866. configurable: true
  6867. });
  6868. Object.defineProperty(PrimitiveThickness.prototype, "isDefault", {
  6869. get: function () {
  6870. return this._flags === 0x1111;
  6871. },
  6872. enumerable: true,
  6873. configurable: true
  6874. });
  6875. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  6876. var type = this._getType(index, false);
  6877. if (type === PrimitiveThickness_1.Inherit) {
  6878. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  6879. return;
  6880. }
  6881. if (type !== PrimitiveThickness_1.Percentage) {
  6882. return;
  6883. }
  6884. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  6885. this._pixels[index] = pixels;
  6886. if (emitChanged) {
  6887. this.onChangeCallback();
  6888. }
  6889. };
  6890. PrimitiveThickness.prototype.onChangeCallback = function () {
  6891. if (this._changedCallback) {
  6892. this._changedCallback();
  6893. }
  6894. };
  6895. /**
  6896. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  6897. * @param sourceArea the source area where the content must be sized/positioned
  6898. * @param contentSize the content size to position/resize
  6899. * @param alignment the alignment setting
  6900. * @param dstOffset the position of the content, x, y, z, w are left, bottom, right, top
  6901. * @param dstArea the new size of the content
  6902. */
  6903. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, contentScale, dstOffset, dstArea, computeLayoutArea, computeAxis) {
  6904. if (computeLayoutArea === void 0) { computeLayoutArea = false; }
  6905. if (computeAxis === void 0) { computeAxis = PrimitiveThickness_1.ComputeAll; }
  6906. // Fetch some data
  6907. var topType = this._getType(0, true);
  6908. var leftType = this._getType(1, true);
  6909. var rightType = this._getType(2, true);
  6910. var bottomType = this._getType(3, true);
  6911. var hasWidth = contentSize && (contentSize.width != null);
  6912. var hasHeight = contentSize && (contentSize.height != null);
  6913. var sx = contentScale.x;
  6914. var sy = contentScale.y;
  6915. var isx = 1 / sx;
  6916. var isy = 1 / sy;
  6917. var width = hasWidth ? contentSize.width : 0;
  6918. var height = hasHeight ? contentSize.height : 0;
  6919. var isTopAuto = topType === PrimitiveThickness_1.Auto;
  6920. var isLeftAuto = leftType === PrimitiveThickness_1.Auto;
  6921. var isRightAuto = rightType === PrimitiveThickness_1.Auto;
  6922. var isBottomAuto = bottomType === PrimitiveThickness_1.Auto;
  6923. if (computeAxis & PrimitiveThickness_1.ComputeH) {
  6924. switch (alignment.horizontal) {
  6925. case PrimitiveAlignment.AlignLeft:
  6926. {
  6927. var leftPixels = 0;
  6928. if (!isLeftAuto) {
  6929. this._computePixels(1, sourceArea, true);
  6930. leftPixels = this.leftPixels;
  6931. }
  6932. dstOffset.x = leftPixels;
  6933. dstArea.width = width * isx;
  6934. dstOffset.z = sourceArea.width - (width * sx + leftPixels);
  6935. if (computeLayoutArea) {
  6936. var rightPixels = 0;
  6937. if (!isRightAuto) {
  6938. this._computePixels(2, sourceArea, true);
  6939. rightPixels = this.rightPixels;
  6940. }
  6941. dstArea.width += (leftPixels + rightPixels) * isx;
  6942. }
  6943. break;
  6944. }
  6945. case PrimitiveAlignment.AlignRight:
  6946. {
  6947. var rightPixels = 0;
  6948. if (!isRightAuto) {
  6949. this._computePixels(2, sourceArea, true);
  6950. rightPixels = this.rightPixels;
  6951. }
  6952. dstOffset.x = sourceArea.width - (width * sx + rightPixels);
  6953. dstArea.width = width * isx;
  6954. dstOffset.z = rightPixels;
  6955. if (computeLayoutArea) {
  6956. var leftPixels = 0;
  6957. if (!isLeftAuto) {
  6958. this._computePixels(1, sourceArea, true);
  6959. leftPixels = this.leftPixels;
  6960. }
  6961. dstArea.width += (leftPixels + rightPixels) * isx;
  6962. }
  6963. break;
  6964. }
  6965. case PrimitiveAlignment.AlignStretch:
  6966. {
  6967. if (isLeftAuto) {
  6968. dstOffset.x = 0;
  6969. }
  6970. else {
  6971. this._computePixels(1, sourceArea, true);
  6972. dstOffset.x = this.leftPixels;
  6973. }
  6974. var rightPixels = 0;
  6975. if (!isRightAuto) {
  6976. this._computePixels(2, sourceArea, true);
  6977. rightPixels = this.rightPixels;
  6978. }
  6979. if (computeLayoutArea) {
  6980. dstArea.width = sourceArea.width * isx;
  6981. }
  6982. else {
  6983. dstArea.width = (sourceArea.width * isx) - (dstOffset.x + rightPixels) * isx;
  6984. }
  6985. dstOffset.z = this.rightPixels;
  6986. break;
  6987. }
  6988. case PrimitiveAlignment.AlignCenter:
  6989. {
  6990. var leftPixels = 0;
  6991. if (!isLeftAuto) {
  6992. this._computePixels(1, sourceArea, true);
  6993. leftPixels = this.leftPixels;
  6994. }
  6995. var rightPixels = 0;
  6996. if (!isRightAuto) {
  6997. this._computePixels(2, sourceArea, true);
  6998. rightPixels = this.rightPixels;
  6999. }
  7000. var center = ((sourceArea.width - (leftPixels + rightPixels)) - (width * sx)) / 2;
  7001. dstOffset.x = leftPixels + center;
  7002. if (computeLayoutArea) {
  7003. dstArea.width = (width * isx) + (this.leftPixels + this.rightPixels) * isx;
  7004. }
  7005. else {
  7006. dstArea.width = (width * isx);
  7007. }
  7008. dstOffset.z = rightPixels + center;
  7009. break;
  7010. }
  7011. }
  7012. }
  7013. if (computeAxis & PrimitiveThickness_1.ComputeV) {
  7014. switch (alignment.vertical) {
  7015. case PrimitiveAlignment.AlignBottom:
  7016. {
  7017. var bottomPixels = 0;
  7018. if (!isBottomAuto) {
  7019. this._computePixels(3, sourceArea, true);
  7020. bottomPixels = this.bottomPixels;
  7021. }
  7022. dstOffset.y = bottomPixels;
  7023. dstArea.height = height * isy;
  7024. dstOffset.w = sourceArea.height - (height * sy + bottomPixels);
  7025. if (computeLayoutArea) {
  7026. var topPixels = 0;
  7027. if (!isTopAuto) {
  7028. this._computePixels(0, sourceArea, true);
  7029. topPixels = this.topPixels;
  7030. }
  7031. dstArea.height += (bottomPixels + topPixels) * isy;
  7032. }
  7033. break;
  7034. }
  7035. case PrimitiveAlignment.AlignTop:
  7036. {
  7037. var topPixels = 0;
  7038. if (!isTopAuto) {
  7039. this._computePixels(0, sourceArea, true);
  7040. topPixels = this.topPixels;
  7041. }
  7042. dstOffset.y = sourceArea.height - ((height * sy) + topPixels);
  7043. dstArea.height = height * isy;
  7044. dstOffset.w = topPixels;
  7045. if (computeLayoutArea) {
  7046. var bottomPixels = 0;
  7047. if (!isBottomAuto) {
  7048. this._computePixels(3, sourceArea, true);
  7049. bottomPixels = this.bottomPixels;
  7050. }
  7051. dstArea.height += (bottomPixels + topPixels) * isy;
  7052. }
  7053. break;
  7054. }
  7055. case PrimitiveAlignment.AlignStretch:
  7056. {
  7057. var bottom = 0;
  7058. if (!isBottomAuto) {
  7059. this._computePixels(3, sourceArea, true);
  7060. bottom = this.bottomPixels;
  7061. }
  7062. dstOffset.y = bottom;
  7063. var top_1 = 0;
  7064. if (!isTopAuto) {
  7065. this._computePixels(0, sourceArea, true);
  7066. top_1 = this.topPixels;
  7067. }
  7068. dstOffset.w = top_1;
  7069. if (computeLayoutArea) {
  7070. dstArea.height = sourceArea.height * isy;
  7071. }
  7072. else {
  7073. dstArea.height = (sourceArea.height * isy) - (top_1 + bottom) * isy;
  7074. }
  7075. break;
  7076. }
  7077. case PrimitiveAlignment.AlignCenter:
  7078. {
  7079. var bottomPixels = 0;
  7080. if (!isBottomAuto) {
  7081. this._computePixels(3, sourceArea, true);
  7082. bottomPixels = this.bottomPixels;
  7083. }
  7084. var topPixels = 0;
  7085. if (!isTopAuto) {
  7086. this._computePixels(0, sourceArea, true);
  7087. topPixels = this.topPixels;
  7088. }
  7089. var center = ((sourceArea.height - (bottomPixels + topPixels)) - (height * sy)) / 2;
  7090. dstOffset.y = bottomPixels + center;
  7091. if (computeLayoutArea) {
  7092. dstArea.height = (height * isy) + (bottomPixels + topPixels) * isy;
  7093. }
  7094. else {
  7095. dstArea.height = (height * isy);
  7096. }
  7097. dstOffset.w = topPixels + center;
  7098. break;
  7099. }
  7100. }
  7101. }
  7102. };
  7103. /**
  7104. * Compute an area and its position considering this thickness properties based on a given source area
  7105. * @param sourceArea the source area
  7106. * @param dstOffset the position of the resulting area
  7107. * @param dstArea the size of the resulting area
  7108. */
  7109. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea, computeLayoutArea) {
  7110. if (computeLayoutArea === void 0) { computeLayoutArea = false; }
  7111. this._computePixels(0, sourceArea, true);
  7112. this._computePixels(1, sourceArea, true);
  7113. this._computePixels(2, sourceArea, true);
  7114. this._computePixels(3, sourceArea, true);
  7115. dstOffset.x = this.leftPixels;
  7116. if (computeLayoutArea) {
  7117. dstArea.width = (sourceArea.width) + (dstOffset.x + this.rightPixels);
  7118. }
  7119. else {
  7120. dstArea.width = (sourceArea.width) - (dstOffset.x + this.rightPixels);
  7121. }
  7122. dstOffset.y = this.bottomPixels;
  7123. if (computeLayoutArea) {
  7124. dstArea.height = (sourceArea.height) + (dstOffset.y + this.topPixels);
  7125. }
  7126. else {
  7127. dstArea.height = (sourceArea.height) - (dstOffset.y + this.topPixels);
  7128. }
  7129. dstOffset.z = this.rightPixels;
  7130. dstOffset.w = this.topPixels;
  7131. };
  7132. /**
  7133. * Compute an area considering this thickness properties based on a given source area
  7134. * @param sourceArea the source area
  7135. * @param result the resulting area
  7136. */
  7137. PrimitiveThickness.prototype.computeArea = function (sourceArea, sourceScale, result) {
  7138. this._computePixels(0, sourceArea, true);
  7139. this._computePixels(1, sourceArea, true);
  7140. this._computePixels(2, sourceArea, true);
  7141. this._computePixels(3, sourceArea, true);
  7142. result.width = this.leftPixels + (sourceArea.width * sourceScale.x) + this.rightPixels;
  7143. result.height = this.bottomPixels + (sourceArea.height * sourceScale.y) + this.topPixels;
  7144. };
  7145. PrimitiveThickness.prototype.enlarge = function (sourceArea, sourceScale, dstOffset, enlargedArea) {
  7146. this._computePixels(0, sourceArea, true);
  7147. this._computePixels(1, sourceArea, true);
  7148. this._computePixels(2, sourceArea, true);
  7149. this._computePixels(3, sourceArea, true);
  7150. dstOffset.x = this.leftPixels;
  7151. enlargedArea.width = (sourceArea.width * sourceScale.x) + (dstOffset.x + this.rightPixels);
  7152. dstOffset.y = this.bottomPixels;
  7153. enlargedArea.height = (sourceArea.height * sourceScale.y) + (dstOffset.y + this.topPixels);
  7154. dstOffset.z = this.rightPixels;
  7155. dstOffset.w = this.topPixels;
  7156. };
  7157. return PrimitiveThickness;
  7158. }());
  7159. PrimitiveThickness.Auto = 0x1;
  7160. PrimitiveThickness.Inherit = 0x2;
  7161. PrimitiveThickness.Percentage = 0x4;
  7162. PrimitiveThickness.Pixel = 0x8;
  7163. PrimitiveThickness.ComputeH = 0x1;
  7164. PrimitiveThickness.ComputeV = 0x2;
  7165. PrimitiveThickness.ComputeAll = 0x03;
  7166. PrimitiveThickness = PrimitiveThickness_1 = __decorate([
  7167. BABYLON.className("PrimitiveThickness", "BABYLON")
  7168. ], PrimitiveThickness);
  7169. BABYLON.PrimitiveThickness = PrimitiveThickness;
  7170. /**
  7171. * Main class used for the Primitive Intersection API
  7172. */
  7173. var IntersectInfo2D = (function () {
  7174. function IntersectInfo2D() {
  7175. this.findFirstOnly = false;
  7176. this.intersectHidden = false;
  7177. this.pickPosition = BABYLON.Vector2.Zero();
  7178. }
  7179. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  7180. /**
  7181. * true if at least one primitive intersected during the test
  7182. */
  7183. get: function () {
  7184. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  7185. },
  7186. enumerable: true,
  7187. configurable: true
  7188. });
  7189. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  7190. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  7191. var cur = _a[_i];
  7192. if (cur.prim === prim) {
  7193. return cur.intersectionLocation;
  7194. }
  7195. }
  7196. return null;
  7197. };
  7198. // Internals, don't use
  7199. IntersectInfo2D.prototype._exit = function (firstLevel) {
  7200. if (firstLevel) {
  7201. this._globalPickPosition = null;
  7202. }
  7203. };
  7204. return IntersectInfo2D;
  7205. }());
  7206. BABYLON.IntersectInfo2D = IntersectInfo2D;
  7207. var Prim2DBase = Prim2DBase_1 = (function (_super) {
  7208. __extends(Prim2DBase, _super);
  7209. function Prim2DBase(settings) {
  7210. var _this;
  7211. // Avoid checking every time if the object exists
  7212. if (settings == null) {
  7213. settings = {};
  7214. }
  7215. // BASE CLASS CALL
  7216. _this = _super.call(this) || this;
  7217. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  7218. var owner;
  7219. var parent;
  7220. if (Prim2DBase_1._isCanvasInit) {
  7221. owner = _this;
  7222. parent = null;
  7223. _this._canvasPreInit(settings);
  7224. }
  7225. else {
  7226. if (settings.parent != null) {
  7227. parent = settings.parent;
  7228. owner = settings.parent.owner;
  7229. if (!owner) {
  7230. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  7231. }
  7232. if (!(_this instanceof BABYLON.Group2D) && !(_this instanceof BABYLON.Sprite2D && settings.id != null && settings.id.indexOf("__cachedSpriteOfGroup__") === 0) && (owner.cachingStrategy === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) && (parent === owner)) {
  7233. throw new Error("Can't create a primitive with the canvas as direct parent when the caching strategy is TOPLEVELGROUPS. You need to create a Group below the canvas and use it as the parent for the primitive");
  7234. }
  7235. }
  7236. }
  7237. // Fields initialization
  7238. _this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  7239. _this._size = null; //Size.Zero();
  7240. _this._scale = new BABYLON.Vector2(1, 1);
  7241. _this._postScale = new BABYLON.Vector2(1, 1);
  7242. _this._actualSize = null;
  7243. _this._internalSize = BABYLON.Size.Zero();
  7244. _this._layoutArea = null;
  7245. _this._layoutAreaPos = null;
  7246. _this._layoutBoundingInfo = null;
  7247. _this._marginOffset = BABYLON.Vector4.Zero();
  7248. _this._paddingOffset = BABYLON.Vector4.Zero();
  7249. _this._parentPaddingOffset = BABYLON.Vector2.Zero();
  7250. _this._parentContentArea = BABYLON.Size.Zero();
  7251. _this._lastAutoSizeArea = BABYLON.Size.Zero();
  7252. _this._contentArea = BABYLON.Size.Zero();
  7253. _this._pointerEventObservable = new BABYLON.Observable();
  7254. _this._owner = owner;
  7255. _this._parent = null;
  7256. _this._margin = null;
  7257. _this._padding = null;
  7258. _this._marginAlignment = null;
  7259. _this._id = settings.id;
  7260. _this._children = new Array();
  7261. _this._localTransform = new BABYLON.Matrix();
  7262. _this._localLayoutTransform = new BABYLON.Matrix();
  7263. _this._globalTransform = null;
  7264. _this._invGlobalTransform = null;
  7265. _this._globalTransformProcessStep = 0;
  7266. _this._globalTransformStep = 0;
  7267. _this._prepareProcessStep = 0;
  7268. _this._updateCachesProcessStep = 0;
  7269. _this._renderGroup = null;
  7270. _this._primLinearPosition = 0;
  7271. _this._manualZOrder = null;
  7272. _this._zOrder = 0;
  7273. _this._zMax = 0;
  7274. _this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  7275. _this._actualOpacity = 0;
  7276. _this._actualScale = BABYLON.Vector2.Zero();
  7277. _this._displayDebugAreas = false;
  7278. _this._debugAreaGroup = null;
  7279. _this._primTriArray = null;
  7280. _this._primTriArrayDirty = true;
  7281. if (owner) {
  7282. _this.onSetOwner();
  7283. }
  7284. _this._levelBoundingInfo.worldMatrixAccess = function () { return _this.globalTransform; };
  7285. _this._boundingInfo.worldMatrixAccess = function () { return _this.globalTransform; };
  7286. var isPickable = true;
  7287. var isContainer = true;
  7288. if (settings.isPickable !== undefined) {
  7289. isPickable = settings.isPickable;
  7290. }
  7291. if (settings.isContainer !== undefined) {
  7292. isContainer = settings.isContainer;
  7293. }
  7294. if (settings.dontInheritParentScale) {
  7295. _this._setFlags(BABYLON.SmartPropertyPrim.flagDontInheritParentScale);
  7296. }
  7297. if (settings.alignToPixel) {
  7298. _this.alignToPixel = true;
  7299. }
  7300. _this._setFlags((isPickable ? BABYLON.SmartPropertyPrim.flagIsPickable : 0) | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty | (isContainer ? BABYLON.SmartPropertyPrim.flagIsContainer : 0) | BABYLON.SmartPropertyPrim.flagActualScaleDirty | BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  7301. if (settings.opacity != null) {
  7302. _this._opacity = settings.opacity;
  7303. }
  7304. else {
  7305. _this._opacity = 1;
  7306. }
  7307. _this._updateRenderMode();
  7308. if (settings.childrenFlatZOrder) {
  7309. _this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  7310. }
  7311. // If the parent is given, initialize the hierarchy/owner related data
  7312. if (parent != null) {
  7313. parent.addChild(_this);
  7314. _this._hierarchyDepth = parent._hierarchyDepth + 1;
  7315. _this._patchHierarchy(parent.owner);
  7316. }
  7317. // If it's a group, detect its own states
  7318. if (_this.owner && _this instanceof BABYLON.Group2D) {
  7319. var group = _this;
  7320. group.detectGroupStates();
  7321. }
  7322. // Time to insert children if some are specified
  7323. if (settings.children != null) {
  7324. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  7325. var child = _a[_i];
  7326. _this.addChild(child);
  7327. // Good time to patch the hierarchy, it won't go very far if there's no need to
  7328. if (_this.owner != null && _this._hierarchyDepth != null) {
  7329. child._patchHierarchy(_this.owner);
  7330. }
  7331. }
  7332. }
  7333. if (settings.zOrder != null) {
  7334. _this.zOrder = settings.zOrder;
  7335. }
  7336. // Set the model related properties
  7337. if (settings.position != null) {
  7338. _this.position = settings.position;
  7339. }
  7340. else if (settings.x != null || settings.y != null) {
  7341. _this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  7342. }
  7343. else {
  7344. _this._position = null;
  7345. }
  7346. _this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  7347. if (settings.scale != null) {
  7348. _this.scale = settings.scale;
  7349. }
  7350. else {
  7351. if (settings.scaleX != null) {
  7352. _this.scaleX = settings.scaleX;
  7353. }
  7354. if (settings.scaleY != null) {
  7355. _this.scaleY = settings.scaleY;
  7356. }
  7357. }
  7358. _this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  7359. _this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  7360. // Layout Engine
  7361. if (settings.layoutEngine != null) {
  7362. if (typeof settings.layoutEngine === "string") {
  7363. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  7364. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  7365. _this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  7366. }
  7367. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  7368. _this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  7369. }
  7370. else if (name_1.indexOf("verticalstackpanel") === 0) {
  7371. _this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  7372. }
  7373. }
  7374. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  7375. _this.layoutEngine = settings.layoutEngine;
  7376. }
  7377. }
  7378. // Set the layout/margin stuffs
  7379. if (settings.marginTop) {
  7380. _this.margin.setTop(settings.marginTop);
  7381. }
  7382. if (settings.marginLeft) {
  7383. _this.margin.setLeft(settings.marginLeft);
  7384. }
  7385. if (settings.marginRight) {
  7386. _this.margin.setRight(settings.marginRight);
  7387. }
  7388. if (settings.marginBottom) {
  7389. _this.margin.setBottom(settings.marginBottom);
  7390. }
  7391. if (settings.margin) {
  7392. if (typeof settings.margin === "string") {
  7393. _this.margin.fromString(settings.margin);
  7394. }
  7395. else {
  7396. _this.margin.fromUniformPixels(settings.margin);
  7397. }
  7398. }
  7399. if (settings.marginHAlignment) {
  7400. _this.marginAlignment.horizontal = settings.marginHAlignment;
  7401. }
  7402. if (settings.marginVAlignment) {
  7403. _this.marginAlignment.vertical = settings.marginVAlignment;
  7404. }
  7405. if (settings.marginAlignment) {
  7406. _this.marginAlignment.fromString(settings.marginAlignment);
  7407. }
  7408. if (settings.paddingTop) {
  7409. _this.padding.setTop(settings.paddingTop);
  7410. }
  7411. if (settings.paddingLeft) {
  7412. _this.padding.setLeft(settings.paddingLeft);
  7413. }
  7414. if (settings.paddingRight) {
  7415. _this.padding.setRight(settings.paddingRight);
  7416. }
  7417. if (settings.paddingBottom) {
  7418. _this.padding.setBottom(settings.paddingBottom);
  7419. }
  7420. if (settings.padding) {
  7421. if (typeof settings.padding === "string") {
  7422. _this.padding.fromString(settings.padding);
  7423. }
  7424. else {
  7425. _this.padding.fromUniformPixels(settings.padding);
  7426. }
  7427. }
  7428. if (settings.layoutData) {
  7429. _this.layoutData = settings.layoutData;
  7430. }
  7431. _this._updatePositioningState();
  7432. // Dirty layout and positioning
  7433. _this._parentLayoutDirty();
  7434. _this._positioningDirty();
  7435. // Add in the PCM
  7436. if (settings.levelCollision || settings.deepCollision) {
  7437. _this._actorInfo = _this.owner._primitiveCollisionManager._addActor(_this, settings.deepCollision === true);
  7438. _this._setFlags(BABYLON.SmartPropertyPrim.flagCollisionActor);
  7439. }
  7440. else {
  7441. _this._actorInfo = null;
  7442. }
  7443. return _this;
  7444. }
  7445. Object.defineProperty(Prim2DBase.prototype, "intersectWithObservable", {
  7446. /**
  7447. * Return the ChangedDictionary observable of the StringDictionary containing the primitives intersecting with this one
  7448. */
  7449. get: function () {
  7450. if (!this._actorInfo) {
  7451. return null;
  7452. }
  7453. return this._actorInfo.intersectWith.dictionaryChanged;
  7454. },
  7455. enumerable: true,
  7456. configurable: true
  7457. });
  7458. Object.defineProperty(Prim2DBase.prototype, "intersectWith", {
  7459. /**
  7460. * Return the ObservableStringDictionary containing all the primitives intersecting with this one.
  7461. * The key is the primitive uid, the value is the ActorInfo object
  7462. * @returns {}
  7463. */
  7464. get: function () {
  7465. if (!this._actorInfo) {
  7466. return null;
  7467. }
  7468. return this._actorInfo.intersectWith;
  7469. },
  7470. enumerable: true,
  7471. configurable: true
  7472. });
  7473. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  7474. get: function () {
  7475. if (!this._actionManager) {
  7476. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  7477. }
  7478. return this._actionManager;
  7479. },
  7480. enumerable: true,
  7481. configurable: true
  7482. });
  7483. /**
  7484. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  7485. * @param predicate the predicate to test on each parent
  7486. * @return the first primitive where the predicate was successful
  7487. */
  7488. Prim2DBase.prototype.traverseUp = function (predicate) {
  7489. var p = this;
  7490. while (p != null) {
  7491. if (predicate(p)) {
  7492. return p;
  7493. }
  7494. p = p._parent;
  7495. }
  7496. return null;
  7497. };
  7498. Object.defineProperty(Prim2DBase.prototype, "owner", {
  7499. /**
  7500. * Retrieve the owner Canvas2D
  7501. */
  7502. get: function () {
  7503. return this._owner;
  7504. },
  7505. enumerable: true,
  7506. configurable: true
  7507. });
  7508. Object.defineProperty(Prim2DBase.prototype, "parent", {
  7509. /**
  7510. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  7511. */
  7512. get: function () {
  7513. return this._parent;
  7514. },
  7515. enumerable: true,
  7516. configurable: true
  7517. });
  7518. Object.defineProperty(Prim2DBase.prototype, "children", {
  7519. /**
  7520. * The array of direct children primitives
  7521. */
  7522. get: function () {
  7523. return this._children;
  7524. },
  7525. enumerable: true,
  7526. configurable: true
  7527. });
  7528. Object.defineProperty(Prim2DBase.prototype, "id", {
  7529. /**
  7530. * The identifier of this primitive, may not be unique, it's for information purpose only
  7531. */
  7532. get: function () {
  7533. return this._id;
  7534. },
  7535. set: function (value) {
  7536. if (this._id === value) {
  7537. return;
  7538. }
  7539. var oldValue = this._id;
  7540. this.onPropertyChanged("id", oldValue, this._id);
  7541. },
  7542. enumerable: true,
  7543. configurable: true
  7544. });
  7545. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  7546. get: function () {
  7547. // If we don't use positioning engine the actual position is the position
  7548. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  7549. return this.position;
  7550. }
  7551. // We use the positioning engine, if the variable is fetched, it's up to date, return it
  7552. if (this._actualPosition != null) {
  7553. return this._actualPosition;
  7554. }
  7555. this._updatePositioning();
  7556. return this._actualPosition;
  7557. },
  7558. /**
  7559. * DO NOT INVOKE for internal purpose only
  7560. */
  7561. set: function (val) {
  7562. if (!this._actualPosition) {
  7563. this._actualPosition = val.clone();
  7564. }
  7565. else {
  7566. this._actualPosition.copyFrom(val);
  7567. }
  7568. },
  7569. enumerable: true,
  7570. configurable: true
  7571. });
  7572. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  7573. /**
  7574. * Shortcut to actualPosition.x
  7575. */
  7576. get: function () {
  7577. return this.actualPosition.x;
  7578. },
  7579. set: function (val) {
  7580. this._actualPosition.x = val;
  7581. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualPosition);
  7582. },
  7583. enumerable: true,
  7584. configurable: true
  7585. });
  7586. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  7587. /**
  7588. * Shortcut to actualPosition.y
  7589. */
  7590. get: function () {
  7591. return this.actualPosition.y;
  7592. },
  7593. set: function (val) {
  7594. this._actualPosition.y = val;
  7595. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualPosition);
  7596. },
  7597. enumerable: true,
  7598. configurable: true
  7599. });
  7600. Object.defineProperty(Prim2DBase.prototype, "position", {
  7601. /**
  7602. * Position of the primitive, relative to its parent.
  7603. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  7604. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  7605. * Setting this property may have no effect is specific alignment are in effect.
  7606. */
  7607. get: function () {
  7608. if (!this._position) {
  7609. this._position = BABYLON.Vector2.Zero();
  7610. }
  7611. return this._position;
  7612. },
  7613. set: function (value) {
  7614. if (!this._checkPositionChange()) {
  7615. return;
  7616. }
  7617. if (!value) {
  7618. this._position = null;
  7619. }
  7620. else {
  7621. if (!this._position) {
  7622. this._position = value.clone();
  7623. }
  7624. else {
  7625. this._position.copyFrom(value);
  7626. }
  7627. }
  7628. this._actualPosition = null;
  7629. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
  7630. },
  7631. enumerable: true,
  7632. configurable: true
  7633. });
  7634. Object.defineProperty(Prim2DBase.prototype, "x", {
  7635. /**
  7636. * Direct access to the position.x value of the primitive
  7637. * Use this property when you only want to change one component of the position property
  7638. */
  7639. get: function () {
  7640. if (!this._position) {
  7641. return null;
  7642. }
  7643. return this._position.x;
  7644. },
  7645. set: function (value) {
  7646. if (!this._checkPositionChange()) {
  7647. return;
  7648. }
  7649. if (value == null) {
  7650. throw new Error("Can't set a null x in primitive " + this.id + ", only the position can be turned to null");
  7651. }
  7652. if (!this._position) {
  7653. this._position = BABYLON.Vector2.Zero();
  7654. }
  7655. if (this._position.x === value) {
  7656. return;
  7657. }
  7658. this._position.x = value;
  7659. this._actualPosition = null;
  7660. this._triggerPropertyChanged(Prim2DBase_1.positionProperty, value);
  7661. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
  7662. },
  7663. enumerable: true,
  7664. configurable: true
  7665. });
  7666. Object.defineProperty(Prim2DBase.prototype, "y", {
  7667. /**
  7668. * Direct access to the position.y value of the primitive
  7669. * Use this property when you only want to change one component of the position property
  7670. */
  7671. get: function () {
  7672. if (!this._position) {
  7673. return null;
  7674. }
  7675. return this._position.y;
  7676. },
  7677. set: function (value) {
  7678. if (!this._checkPositionChange()) {
  7679. return;
  7680. }
  7681. if (value == null) {
  7682. throw new Error("Can't set a null y in primitive " + this.id + ", only the position can be turned to null");
  7683. }
  7684. if (!this._position) {
  7685. this._position = BABYLON.Vector2.Zero();
  7686. }
  7687. if (this._position.y === value) {
  7688. return;
  7689. }
  7690. this._position.y = value;
  7691. this._actualPosition = null;
  7692. this._triggerPropertyChanged(Prim2DBase_1.positionProperty, value);
  7693. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
  7694. },
  7695. enumerable: true,
  7696. configurable: true
  7697. });
  7698. Object.defineProperty(Prim2DBase.prototype, "size", {
  7699. get: function () {
  7700. return this.internalGetSize();
  7701. },
  7702. set: function (value) {
  7703. this.internalSetSize(value);
  7704. },
  7705. enumerable: true,
  7706. configurable: true
  7707. });
  7708. Prim2DBase.prototype.internalGetSize = function () {
  7709. if (!this._size || this._size.width == null || this._size.height == null) {
  7710. var bbr = Prim2DBase_1.boundinbBoxReentrency;
  7711. if (bbr !== -1 && bbr <= (this.hierarchyDepth || 0)) {
  7712. BABYLON.C2DLogging.setPostMessage(function () { return "re entrancy detected"; });
  7713. return Prim2DBase_1.nullSize;
  7714. }
  7715. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty)) {
  7716. BABYLON.C2DLogging.setPostMessage(function () { return "cache hit"; });
  7717. return this._internalSize;
  7718. }
  7719. BABYLON.C2DLogging.setPostMessage(function () { return "cache miss"; });
  7720. Prim2DBase_1.boundinbBoxReentrency = this.hierarchyDepth || 0;
  7721. var b = this.boundingInfo;
  7722. Prim2DBase_1.boundinbBoxReentrency = -1;
  7723. Prim2DBase_1._size.copyFrom(this._internalSize);
  7724. b.sizeToRef(this._internalSize);
  7725. if (!this._internalSize.equals(Prim2DBase_1._size)) {
  7726. this._triggerPropertyChanged(Prim2DBase_1.sizeProperty, this._internalSize);
  7727. this._positioningDirty();
  7728. }
  7729. return this._internalSize || Prim2DBase_1._nullSize;
  7730. }
  7731. else {
  7732. BABYLON.C2DLogging.setPostMessage(function () { return "user set size"; });
  7733. }
  7734. return this._size || Prim2DBase_1._nullSize;
  7735. };
  7736. Prim2DBase.prototype.internalSetSize = function (value) {
  7737. if (!value) {
  7738. this._size = null;
  7739. }
  7740. else {
  7741. if (!this._size) {
  7742. this._size = value.clone();
  7743. }
  7744. else {
  7745. this._size.copyFrom(value);
  7746. }
  7747. }
  7748. this._actualSize = null;
  7749. this._updatePositioningState();
  7750. this._positioningDirty();
  7751. };
  7752. Object.defineProperty(Prim2DBase.prototype, "width", {
  7753. get: function () {
  7754. if (!this.size) {
  7755. return null;
  7756. }
  7757. return this.size.width;
  7758. },
  7759. set: function (value) {
  7760. if (this.size && this.size.width === value) {
  7761. return;
  7762. }
  7763. if (!this.size) {
  7764. this.size = new BABYLON.Size(value, 0);
  7765. }
  7766. else {
  7767. this.size.width = value;
  7768. }
  7769. this._actualSize = null;
  7770. this._triggerPropertyChanged(Prim2DBase_1.sizeProperty, value);
  7771. this._positioningDirty();
  7772. },
  7773. enumerable: true,
  7774. configurable: true
  7775. });
  7776. Object.defineProperty(Prim2DBase.prototype, "height", {
  7777. get: function () {
  7778. if (!this.size) {
  7779. return null;
  7780. }
  7781. return this.size.height;
  7782. },
  7783. set: function (value) {
  7784. if (this.size && this.size.height === value) {
  7785. return;
  7786. }
  7787. if (!this.size) {
  7788. this.size = new BABYLON.Size(0, value);
  7789. }
  7790. else {
  7791. this.size.height = value;
  7792. }
  7793. this._actualSize = null;
  7794. this._triggerPropertyChanged(Prim2DBase_1.sizeProperty, value);
  7795. this._positioningDirty();
  7796. },
  7797. enumerable: true,
  7798. configurable: true
  7799. });
  7800. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  7801. get: function () {
  7802. return this._rotation;
  7803. },
  7804. set: function (value) {
  7805. this._rotation = value;
  7806. if (this._hasMargin) {
  7807. this._positioningDirty();
  7808. }
  7809. },
  7810. enumerable: true,
  7811. configurable: true
  7812. });
  7813. Object.defineProperty(Prim2DBase.prototype, "scale", {
  7814. get: function () {
  7815. return this._scale.x;
  7816. },
  7817. set: function (value) {
  7818. this._scale.x = this._scale.y = value;
  7819. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  7820. this._spreadActualScaleDirty();
  7821. this._positioningDirty();
  7822. },
  7823. enumerable: true,
  7824. configurable: true
  7825. });
  7826. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  7827. get: function () {
  7828. // If we don't use positioning engine the actual size is the size
  7829. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  7830. return this.size;
  7831. }
  7832. // We use the positioning engine, if the variable is fetched, it's up to date, return it
  7833. if (this._actualSize) {
  7834. return this._actualSize;
  7835. }
  7836. this._updatePositioning();
  7837. return this._actualSize;
  7838. },
  7839. set: function (value) {
  7840. if (this._actualSize && this._actualSize.equals(value)) {
  7841. return;
  7842. }
  7843. if (!this._actualSize) {
  7844. this._actualSize = value.clone();
  7845. }
  7846. else {
  7847. this._actualSize.copyFrom(value);
  7848. }
  7849. },
  7850. enumerable: true,
  7851. configurable: true
  7852. });
  7853. Object.defineProperty(Prim2DBase.prototype, "actualWidth", {
  7854. get: function () {
  7855. return this.actualSize.width;
  7856. },
  7857. set: function (val) {
  7858. this._actualSize.width = val;
  7859. this._triggerPropertyChanged(Prim2DBase_1.actualSizeProperty, this._actualSize);
  7860. },
  7861. enumerable: true,
  7862. configurable: true
  7863. });
  7864. Object.defineProperty(Prim2DBase.prototype, "actualHeight", {
  7865. get: function () {
  7866. return this.actualSize.height;
  7867. },
  7868. set: function (val) {
  7869. this._actualSize.height = val;
  7870. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualSize);
  7871. },
  7872. enumerable: true,
  7873. configurable: true
  7874. });
  7875. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  7876. get: function () {
  7877. if (this._manualZOrder != null) {
  7878. return this._manualZOrder;
  7879. }
  7880. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  7881. this._updateZOrder();
  7882. }
  7883. return (1 - this._zOrder);
  7884. },
  7885. enumerable: true,
  7886. configurable: true
  7887. });
  7888. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  7889. /**
  7890. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  7891. * The Primitive's size won't be less than specified.
  7892. * The default value depends of the Primitive type
  7893. */
  7894. get: function () {
  7895. return this._minSize;
  7896. },
  7897. set: function (value) {
  7898. if (this._minSize && value && this._minSize.equals(value)) {
  7899. return;
  7900. }
  7901. if (!this._minSize) {
  7902. this._minSize = value.clone();
  7903. }
  7904. else {
  7905. this._minSize.copyFrom(value);
  7906. }
  7907. this._parentLayoutDirty();
  7908. },
  7909. enumerable: true,
  7910. configurable: true
  7911. });
  7912. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  7913. /**
  7914. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  7915. * The Primitive's size won't be more than specified.
  7916. * The default value depends of the Primitive type
  7917. */
  7918. get: function () {
  7919. return this._maxSize;
  7920. },
  7921. set: function (value) {
  7922. if (this._maxSize && value && this._maxSize.equals(value)) {
  7923. return;
  7924. }
  7925. if (!this._maxSize) {
  7926. this._maxSize = value.clone();
  7927. }
  7928. else {
  7929. this._maxSize.copyFrom(value);
  7930. }
  7931. this._parentLayoutDirty();
  7932. },
  7933. enumerable: true,
  7934. configurable: true
  7935. });
  7936. Object.defineProperty(Prim2DBase.prototype, "origin", {
  7937. /**
  7938. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  7939. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  7940. * For instance:
  7941. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  7942. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  7943. * 0,1 means the center is top/left
  7944. * @returns The normalized center.
  7945. */
  7946. get: function () {
  7947. return this._origin;
  7948. },
  7949. set: function (value) {
  7950. if (!this._origin) {
  7951. this._origin = value.clone();
  7952. }
  7953. else {
  7954. this._origin.copyFrom(value);
  7955. }
  7956. },
  7957. enumerable: true,
  7958. configurable: true
  7959. });
  7960. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  7961. get: function () {
  7962. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  7963. },
  7964. set: function (value) {
  7965. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  7966. },
  7967. enumerable: true,
  7968. configurable: true
  7969. });
  7970. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  7971. get: function () {
  7972. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  7973. },
  7974. set: function (value) {
  7975. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  7976. },
  7977. enumerable: true,
  7978. configurable: true
  7979. });
  7980. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  7981. get: function () {
  7982. return this._manualZOrder;
  7983. },
  7984. set: function (value) {
  7985. if (this._manualZOrder === value) {
  7986. return;
  7987. }
  7988. this._manualZOrder = value;
  7989. this.onZOrderChanged();
  7990. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  7991. this._actualZOrderChangedObservable.notifyObservers(value);
  7992. }
  7993. },
  7994. enumerable: true,
  7995. configurable: true
  7996. });
  7997. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  7998. get: function () {
  7999. return this._manualZOrder != null;
  8000. },
  8001. enumerable: true,
  8002. configurable: true
  8003. });
  8004. Object.defineProperty(Prim2DBase.prototype, "margin", {
  8005. get: function () {
  8006. var _this = this;
  8007. if (!this._margin) {
  8008. this._margin = new PrimitiveThickness(function () {
  8009. if (!_this.parent) {
  8010. return null;
  8011. }
  8012. return _this.parent.margin;
  8013. }, function () { return _this._positioningDirty(); });
  8014. this._updatePositioningState();
  8015. }
  8016. return this._margin;
  8017. },
  8018. set: function (value) {
  8019. if (!value) {
  8020. this._margin = null;
  8021. }
  8022. else {
  8023. this.margin.copyFrom(value);
  8024. }
  8025. this._updatePositioningState();
  8026. },
  8027. enumerable: true,
  8028. configurable: true
  8029. });
  8030. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  8031. /**
  8032. * Check for both margin and marginAlignment, return true if at least one of them is specified with a non default value
  8033. */
  8034. get: function () {
  8035. return (this._margin !== null && !this._margin.isDefault) || (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  8036. },
  8037. enumerable: true,
  8038. configurable: true
  8039. });
  8040. Object.defineProperty(Prim2DBase.prototype, "padding", {
  8041. get: function () {
  8042. var _this = this;
  8043. if (!this._padding) {
  8044. this._padding = new PrimitiveThickness(function () {
  8045. if (!_this.parent) {
  8046. return null;
  8047. }
  8048. return _this.parent.padding;
  8049. }, function () { return _this._positioningDirty(); });
  8050. this._updatePositioningState();
  8051. }
  8052. return this._padding;
  8053. },
  8054. set: function (value) {
  8055. if (!value) {
  8056. this._padding = null;
  8057. }
  8058. else {
  8059. this.padding.copyFrom(value);
  8060. }
  8061. this._updatePositioningState();
  8062. },
  8063. enumerable: true,
  8064. configurable: true
  8065. });
  8066. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  8067. get: function () {
  8068. return this._padding !== null && !this._padding.isDefault;
  8069. },
  8070. enumerable: true,
  8071. configurable: true
  8072. });
  8073. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  8074. get: function () {
  8075. var _this = this;
  8076. if (!this._marginAlignment) {
  8077. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  8078. this._updatePositioningState();
  8079. }
  8080. return this._marginAlignment;
  8081. },
  8082. set: function (value) {
  8083. if (!value) {
  8084. this._marginAlignment = null;
  8085. }
  8086. else {
  8087. this.marginAlignment.copyFrom(value);
  8088. }
  8089. this._updatePositioningState();
  8090. },
  8091. enumerable: true,
  8092. configurable: true
  8093. });
  8094. Object.defineProperty(Prim2DBase.prototype, "_hasMarginAlignment", {
  8095. /**
  8096. * Check if there a marginAlignment specified (non null and not default)
  8097. */
  8098. get: function () {
  8099. return (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  8100. },
  8101. enumerable: true,
  8102. configurable: true
  8103. });
  8104. Prim2DBase.prototype._updatePositioningState = function () {
  8105. var value = this._hasMargin || this._hasPadding || this.isSizeAuto;
  8106. // console.log(`${this.id} with parent ${this._parent ? this._parent.id : "[none]"} state: ${value} `);
  8107. this._changeFlags(BABYLON.SmartPropertyPrim.flagUsePositioning, value);
  8108. };
  8109. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  8110. get: function () {
  8111. return this._opacity;
  8112. },
  8113. set: function (value) {
  8114. if (value < 0) {
  8115. value = 0;
  8116. }
  8117. else if (value > 1) {
  8118. value = 1;
  8119. }
  8120. if (this._opacity === value) {
  8121. return;
  8122. }
  8123. this._opacity = value;
  8124. this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  8125. this._spreadActualOpacityChanged();
  8126. this._updateRenderMode();
  8127. },
  8128. enumerable: true,
  8129. configurable: true
  8130. });
  8131. Object.defineProperty(Prim2DBase.prototype, "scaleX", {
  8132. get: function () {
  8133. return this._scale.x;
  8134. },
  8135. set: function (value) {
  8136. this._scale.x = value;
  8137. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  8138. this._spreadActualScaleDirty();
  8139. this._positioningDirty();
  8140. },
  8141. enumerable: true,
  8142. configurable: true
  8143. });
  8144. Object.defineProperty(Prim2DBase.prototype, "scaleY", {
  8145. get: function () {
  8146. return this._scale.y;
  8147. },
  8148. set: function (value) {
  8149. this._scale.y = value;
  8150. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  8151. this._spreadActualScaleDirty();
  8152. this._positioningDirty();
  8153. },
  8154. enumerable: true,
  8155. configurable: true
  8156. });
  8157. Prim2DBase.prototype._spreadActualScaleDirty = function () {
  8158. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8159. var child = _a[_i];
  8160. child._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  8161. child._spreadActualScaleDirty();
  8162. }
  8163. };
  8164. Object.defineProperty(Prim2DBase.prototype, "actualScale", {
  8165. /**
  8166. * Returns the actual scale of this Primitive, the value is computed from the scale property of this primitive, multiplied by the actualScale of its parent one (if any). The Vector2 object returned contains the scale for both X and Y axis
  8167. */
  8168. get: function () {
  8169. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualScaleDirty)) {
  8170. var cur = this._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : this.parent;
  8171. var sx = this.scaleX;
  8172. var sy = this.scaleY;
  8173. while (cur) {
  8174. sx *= cur.scaleX;
  8175. sy *= cur.scaleY;
  8176. cur = cur._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : cur.parent;
  8177. }
  8178. this._actualScale.copyFromFloats(sx, sy);
  8179. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  8180. }
  8181. return this._actualScale;
  8182. },
  8183. enumerable: true,
  8184. configurable: true
  8185. });
  8186. Object.defineProperty(Prim2DBase.prototype, "actualScaleX", {
  8187. /**
  8188. * Get the actual Scale of the X axis, shortcut for this.actualScale.x
  8189. */
  8190. get: function () {
  8191. return this.actualScale.x;
  8192. },
  8193. enumerable: true,
  8194. configurable: true
  8195. });
  8196. /**
  8197. * This method stores the actual global scale (including DesignMode and DPR related scales) in the given Vector2
  8198. * @param res the object that will receive the actual global scale: this is actualScale * DPRScale * DesignModeScale
  8199. */
  8200. Prim2DBase.prototype.getActualGlobalScaleToRef = function (res) {
  8201. var as = this.actualScale;
  8202. var cls = this.owner._canvasLevelScale || BABYLON.Canvas2D._iv3;
  8203. res.x = as.x * cls.x;
  8204. res.y = as.y * cls.y;
  8205. };
  8206. Object.defineProperty(Prim2DBase.prototype, "actualScaleY", {
  8207. /**
  8208. * Get the actual Scale of the Y axis, shortcut for this.actualScale.y
  8209. */
  8210. get: function () {
  8211. return this.actualScale.y;
  8212. },
  8213. enumerable: true,
  8214. configurable: true
  8215. });
  8216. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  8217. /**
  8218. * Get the actual opacity level, this property is computed from the opacity property, multiplied by the actualOpacity of its parent (if any)
  8219. */
  8220. get: function () {
  8221. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  8222. var cur = this.parent;
  8223. var op = this.opacity;
  8224. while (cur) {
  8225. op *= cur.opacity;
  8226. cur = cur.parent;
  8227. }
  8228. this._actualOpacity = op;
  8229. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  8230. }
  8231. return this._actualOpacity;
  8232. },
  8233. enumerable: true,
  8234. configurable: true
  8235. });
  8236. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  8237. /**
  8238. * Get/set the layout engine to use for this primitive.
  8239. * The default layout engine is the CanvasLayoutEngine.
  8240. */
  8241. get: function () {
  8242. if (!this._layoutEngine) {
  8243. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  8244. }
  8245. return this._layoutEngine;
  8246. },
  8247. set: function (value) {
  8248. if (this._layoutEngine === value) {
  8249. return;
  8250. }
  8251. this._changeLayoutEngine(value);
  8252. },
  8253. enumerable: true,
  8254. configurable: true
  8255. });
  8256. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  8257. /**
  8258. * Get/set the layout are of this primitive.
  8259. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  8260. * The setter should only be called by a Layout Engine class.
  8261. */
  8262. get: function () {
  8263. return this._layoutArea;
  8264. },
  8265. set: function (val) {
  8266. if (this._layoutArea && this._layoutArea.equals(val)) {
  8267. return;
  8268. }
  8269. this._positioningDirty();
  8270. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  8271. if (this.parent) {
  8272. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  8273. }
  8274. if (!this._layoutArea) {
  8275. this._layoutArea = val.clone();
  8276. }
  8277. else {
  8278. this._layoutArea.copyFrom(val);
  8279. }
  8280. },
  8281. enumerable: true,
  8282. configurable: true
  8283. });
  8284. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  8285. /**
  8286. * Get/set the layout area position (relative to the parent primitive).
  8287. * The setter should only be called by a Layout Engine class.
  8288. */
  8289. get: function () {
  8290. return this._layoutAreaPos;
  8291. },
  8292. set: function (val) {
  8293. if (this._layoutAreaPos && this._layoutAreaPos.equals(val)) {
  8294. return;
  8295. }
  8296. if (this.parent) {
  8297. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  8298. }
  8299. this._positioningDirty();
  8300. if (!this._layoutAreaPos) {
  8301. this._layoutAreaPos = val.clone();
  8302. }
  8303. else {
  8304. this._layoutAreaPos.copyFrom(val);
  8305. }
  8306. this._setFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty);
  8307. },
  8308. enumerable: true,
  8309. configurable: true
  8310. });
  8311. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  8312. /**
  8313. * Define if the Primitive can be subject to intersection test or not (default is true)
  8314. */
  8315. get: function () {
  8316. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  8317. },
  8318. set: function (value) {
  8319. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  8320. },
  8321. enumerable: true,
  8322. configurable: true
  8323. });
  8324. Object.defineProperty(Prim2DBase.prototype, "isContainer", {
  8325. /**
  8326. * Define if the Primitive acts as a container or not
  8327. * A container will encapsulate its children for interaction event.
  8328. * If it's not a container events will be process down to children if the primitive is not pickable.
  8329. * Default value is true
  8330. */
  8331. get: function () {
  8332. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsContainer);
  8333. },
  8334. set: function (value) {
  8335. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsContainer, value);
  8336. },
  8337. enumerable: true,
  8338. configurable: true
  8339. });
  8340. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  8341. /**
  8342. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  8343. */
  8344. get: function () {
  8345. return this._hierarchyDepth;
  8346. },
  8347. enumerable: true,
  8348. configurable: true
  8349. });
  8350. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  8351. /**
  8352. * Retrieve the Group that is responsible to render this primitive
  8353. */
  8354. get: function () {
  8355. return this._renderGroup;
  8356. },
  8357. enumerable: true,
  8358. configurable: true
  8359. });
  8360. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  8361. /**
  8362. * Get the global transformation matrix of the primitive
  8363. */
  8364. get: function () {
  8365. if (!this._globalTransform || (this._globalTransformProcessStep !== this.owner._globalTransformProcessStep)) {
  8366. this.updateCachedStates(false);
  8367. }
  8368. return this._globalTransform;
  8369. },
  8370. enumerable: true,
  8371. configurable: true
  8372. });
  8373. /**
  8374. * return the global position of the primitive, relative to its canvas
  8375. */
  8376. Prim2DBase.prototype.getGlobalPosition = function () {
  8377. var v = new BABYLON.Vector2(0, 0);
  8378. this.getGlobalPositionByRef(v);
  8379. return v;
  8380. };
  8381. /**
  8382. * return the global position of the primitive, relative to its canvas
  8383. * @param v the valid Vector2 object where the global position will be stored
  8384. */
  8385. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  8386. v.x = this.globalTransform.m[12];
  8387. v.y = this.globalTransform.m[13];
  8388. };
  8389. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  8390. /**
  8391. * Get invert of the global transformation matrix of the primitive
  8392. */
  8393. get: function () {
  8394. this._updateLocalTransform();
  8395. return this._invGlobalTransform;
  8396. },
  8397. enumerable: true,
  8398. configurable: true
  8399. });
  8400. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  8401. /**
  8402. * Get the local transformation of the primitive
  8403. */
  8404. get: function () {
  8405. this._updateLocalTransform();
  8406. return this._localTransform;
  8407. },
  8408. enumerable: true,
  8409. configurable: true
  8410. });
  8411. Object.defineProperty(Prim2DBase.prototype, "localLayoutTransform", {
  8412. get: function () {
  8413. this._updateLocalTransform();
  8414. return this._localLayoutTransform;
  8415. },
  8416. enumerable: true,
  8417. configurable: true
  8418. });
  8419. Object.defineProperty(Prim2DBase.prototype, "alignToPixel", {
  8420. /**
  8421. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  8422. */
  8423. get: function () {
  8424. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagAlignPrimitive);
  8425. },
  8426. set: function (value) {
  8427. this._changeFlags(BABYLON.SmartPropertyPrim.flagAlignPrimitive, value);
  8428. },
  8429. enumerable: true,
  8430. configurable: true
  8431. });
  8432. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  8433. /**
  8434. * Get the boundingInfo associated to the primitive and its children.
  8435. */
  8436. get: function () {
  8437. // Check if we must update the boundingInfo
  8438. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  8439. if (this.owner) {
  8440. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  8441. }
  8442. BABYLON.C2DLogging.setPostMessage(function () { return "cache miss"; });
  8443. var sizedByContent = this.isSizedByContent;
  8444. if (sizedByContent) {
  8445. this._boundingInfo.clear();
  8446. }
  8447. else {
  8448. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  8449. }
  8450. if (this._children.length > 0) {
  8451. var contentBI = new BABYLON.BoundingInfo2D();
  8452. var tps = Prim2DBase_1._tpsBB2;
  8453. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8454. var curChild = _a[_i];
  8455. if (curChild._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  8456. continue;
  8457. }
  8458. var bb = curChild.layoutBoundingInfo;
  8459. bb.transformToRef(curChild.localLayoutTransform, tps);
  8460. contentBI.unionToRef(tps, contentBI);
  8461. }
  8462. // Apply padding
  8463. if (this._hasPadding) {
  8464. var padding = this.padding;
  8465. var minmax = Prim2DBase_1._bMinMax;
  8466. contentBI.minMaxToRef(minmax);
  8467. this._paddingOffset.copyFromFloats(padding.leftPixels, padding.bottomPixels, padding.rightPixels, padding.topPixels);
  8468. var size = Prim2DBase_1._size2;
  8469. contentBI.sizeToRef(size);
  8470. this._getActualSizeFromContentToRef(size, this._paddingOffset, size);
  8471. minmax.z += this._paddingOffset.z + this._paddingOffset.x;
  8472. minmax.w += this._paddingOffset.w + this._paddingOffset.y;
  8473. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(minmax.x, minmax.z, minmax.y, minmax.w, contentBI);
  8474. }
  8475. else {
  8476. this._paddingOffset.copyFromFloats(0, 0, 0, 0);
  8477. }
  8478. this._boundingInfo.unionToRef(contentBI, this._boundingInfo);
  8479. }
  8480. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  8481. }
  8482. else {
  8483. BABYLON.C2DLogging.setPostMessage(function () { return "cache hit"; });
  8484. }
  8485. return this._boundingInfo;
  8486. },
  8487. enumerable: true,
  8488. configurable: true
  8489. });
  8490. Object.defineProperty(Prim2DBase.prototype, "layoutBoundingInfo", {
  8491. /**
  8492. * Get the boundingInfo of the primitive's content arranged by a layout Engine
  8493. * If a particular child is not arranged by layout, it's boundingInfo is used instead to produce something as accurate as possible
  8494. */
  8495. get: function () {
  8496. var usePositioning = this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning);
  8497. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty)) {
  8498. BABYLON.C2DLogging.setPostMessage(function () { return "cache miss"; });
  8499. if (this._owner) {
  8500. this._owner.addLayoutBoundingInfoUpdateCounter(1);
  8501. }
  8502. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  8503. this.owner.addUpdateLayoutCounter(1);
  8504. this._layoutEngine.updateLayout(this);
  8505. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  8506. }
  8507. if (usePositioning) {
  8508. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  8509. this._updatePositioning();
  8510. }
  8511. // Safety check, code re entrance is a PITA in this part of the code
  8512. if (!this._layoutBoundingInfo) {
  8513. BABYLON.C2DLogging.setPostMessage(function () { return "re entrance detected, boundingInfo returned"; });
  8514. return this.boundingInfo;
  8515. }
  8516. }
  8517. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  8518. }
  8519. else {
  8520. BABYLON.C2DLogging.setPostMessage(function () { return "cache hit"; });
  8521. }
  8522. return usePositioning ? this._layoutBoundingInfo : this.boundingInfo;
  8523. },
  8524. enumerable: true,
  8525. configurable: true
  8526. });
  8527. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  8528. /**
  8529. * Determine if the size is automatically computed or fixed because manually specified.
  8530. * Use the actualSize property to get the final/real size of the primitive
  8531. * @returns true if the size is automatically computed, false if it were manually specified.
  8532. */
  8533. get: function () {
  8534. var size = this._size;
  8535. return size == null || (size.width == null && size.height == null);
  8536. },
  8537. enumerable: true,
  8538. configurable: true
  8539. });
  8540. Object.defineProperty(Prim2DBase.prototype, "isHorizontalSizeAuto", {
  8541. /**
  8542. * Determine if the horizontal size is automatically computed or fixed because manually specified.
  8543. * Use the actualSize property to get the final/real size of the primitive
  8544. * @returns true if the horizontal size is automatically computed, false if it were manually specified.
  8545. */
  8546. get: function () {
  8547. var size = this._size;
  8548. return size == null || size.width == null;
  8549. },
  8550. enumerable: true,
  8551. configurable: true
  8552. });
  8553. Object.defineProperty(Prim2DBase.prototype, "isVerticalSizeAuto", {
  8554. /**
  8555. * Determine if the vertical size is automatically computed or fixed because manually specified.
  8556. * Use the actualSize property to get the final/real size of the primitive
  8557. * @returns true if the vertical size is automatically computed, false if it were manually specified.
  8558. */
  8559. get: function () {
  8560. var size = this._size;
  8561. return size == null || size.height == null;
  8562. },
  8563. enumerable: true,
  8564. configurable: true
  8565. });
  8566. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  8567. /**
  8568. * Return true if this prim has an auto size which is set by the children's global bounding box
  8569. */
  8570. get: function () {
  8571. return (this._size == null) && (this._children.length > 0);
  8572. },
  8573. enumerable: true,
  8574. configurable: true
  8575. });
  8576. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  8577. /**
  8578. * Determine if the position is automatically computed or fixed because manually specified.
  8579. * Use the actualPosition property to get the final/real position of the primitive
  8580. * @returns true if the position is automatically computed, false if it were manually specified.
  8581. */
  8582. get: function () {
  8583. return this._position == null;
  8584. },
  8585. enumerable: true,
  8586. configurable: true
  8587. });
  8588. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  8589. /**
  8590. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  8591. */
  8592. get: function () {
  8593. return this._pointerEventObservable;
  8594. },
  8595. enumerable: true,
  8596. configurable: true
  8597. });
  8598. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  8599. get: function () {
  8600. if (!this._actualZOrderChangedObservable) {
  8601. this._actualZOrderChangedObservable = new BABYLON.Observable();
  8602. }
  8603. return this._actualZOrderChangedObservable;
  8604. },
  8605. enumerable: true,
  8606. configurable: true
  8607. });
  8608. Object.defineProperty(Prim2DBase.prototype, "displayDebugAreas", {
  8609. get: function () {
  8610. return this._displayDebugAreas;
  8611. },
  8612. set: function (value) {
  8613. if (this._displayDebugAreas === value) {
  8614. return;
  8615. }
  8616. if (value === false) {
  8617. this._debugAreaGroup.dispose();
  8618. this._debugAreaGroup = null;
  8619. }
  8620. else {
  8621. var layoutFill = "#F0808040"; // Red - Layout area
  8622. var layoutBorder = "#F08080FF";
  8623. var marginFill = "#F0F04040"; // Yellow - Margin area
  8624. var marginBorder = "#F0F040FF";
  8625. var paddingFill = "#F040F040"; // Magenta - Padding Area
  8626. var paddingBorder = "#F040F0FF";
  8627. var contentFill = "#40F0F040"; // Cyan - Content area
  8628. var contentBorder = "#40F0F0FF";
  8629. var s = new BABYLON.Size(10, 10);
  8630. var p = BABYLON.Vector2.Zero();
  8631. this._debugAreaGroup = new BABYLON.Group2D({
  8632. parent: (this.parent != null) ? this.parent : this, id: "###DEBUG AREA GROUP###", children: [
  8633. new BABYLON.Group2D({
  8634. id: "###Layout Area###", position: p, size: s, children: [
  8635. new BABYLON.Rectangle2D({ id: "###Layout Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: layoutBorder }),
  8636. new BABYLON.Rectangle2D({ id: "###Layout Top###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  8637. new BABYLON.Rectangle2D({ id: "###Layout Left###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  8638. new BABYLON.Rectangle2D({ id: "###Layout Right###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  8639. new BABYLON.Rectangle2D({ id: "###Layout Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill })
  8640. ]
  8641. }),
  8642. new BABYLON.Group2D({
  8643. id: "###Margin Area###", position: p, size: s, children: [
  8644. new BABYLON.Rectangle2D({ id: "###Margin Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: marginBorder }),
  8645. new BABYLON.Rectangle2D({ id: "###Margin Top###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  8646. new BABYLON.Rectangle2D({ id: "###Margin Left###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  8647. new BABYLON.Rectangle2D({ id: "###Margin Right###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  8648. new BABYLON.Rectangle2D({ id: "###Margin Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill })
  8649. ]
  8650. }),
  8651. new BABYLON.Group2D({
  8652. id: "###Padding Area###", position: p, size: s, children: [
  8653. new BABYLON.Rectangle2D({ id: "###Padding Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: paddingBorder }),
  8654. new BABYLON.Rectangle2D({ id: "###Padding Top###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  8655. new BABYLON.Rectangle2D({ id: "###Padding Left###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  8656. new BABYLON.Rectangle2D({ id: "###Padding Right###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  8657. new BABYLON.Rectangle2D({ id: "###Padding Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill })
  8658. ]
  8659. }),
  8660. new BABYLON.Group2D({
  8661. id: "###Content Area###", position: p, size: s, children: [
  8662. new BABYLON.Rectangle2D({ id: "###Content Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: contentBorder }),
  8663. new BABYLON.Rectangle2D({ id: "###Content Top###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  8664. new BABYLON.Rectangle2D({ id: "###Content Left###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  8665. new BABYLON.Rectangle2D({ id: "###Content Right###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  8666. new BABYLON.Rectangle2D({ id: "###Content Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill })
  8667. ]
  8668. })
  8669. ]
  8670. });
  8671. this._debugAreaGroup._setFlags(BABYLON.SmartPropertyPrim.flagNoPartOfLayout);
  8672. this._updateDebugArea();
  8673. }
  8674. this._displayDebugAreas = value;
  8675. },
  8676. enumerable: true,
  8677. configurable: true
  8678. });
  8679. Prim2DBase.prototype._updateDebugArea = function () {
  8680. if (Prim2DBase_1._updatingDebugArea === true) {
  8681. return;
  8682. }
  8683. Prim2DBase_1._updatingDebugArea = true;
  8684. var areaNames = ["Layout", "Margin", "Padding", "Content"];
  8685. var areaZones = ["Area", "Frame", "Top", "Left", "Right", "Bottom"];
  8686. var prims = new Array(4);
  8687. // Get all the primitives used to display the areas
  8688. for (var i = 0; i < 4; i++) {
  8689. prims[i] = new Array(6);
  8690. for (var j = 0; j < 6; j++) {
  8691. prims[i][j] = this._debugAreaGroup.findById("###" + areaNames[i] + " " + areaZones[j] + "###");
  8692. if (j > 1) {
  8693. prims[i][j].levelVisible = false;
  8694. }
  8695. }
  8696. }
  8697. // Update the visibility status of layout/margin/padding
  8698. var hasLayout = this._layoutAreaPos != null;
  8699. var hasPos = (this.actualPosition.x !== 0) || (this.actualPosition.y !== 0);
  8700. var hasMargin = this._hasMargin;
  8701. var hasPadding = this._hasPadding;
  8702. prims[0][0].levelVisible = hasLayout;
  8703. prims[1][0].levelVisible = hasMargin;
  8704. prims[2][0].levelVisible = hasPadding;
  8705. prims[3][0].levelVisible = true;
  8706. // Current offset
  8707. var curOffset = BABYLON.Vector2.Zero();
  8708. // Store the area info of the layout area
  8709. var curAreaIndex = 0;
  8710. // Store data about each area
  8711. var areaInfo = new Array(4);
  8712. var storeAreaInfo = function (pos, size) {
  8713. var min = pos.clone();
  8714. var max = pos.clone();
  8715. if (size.width > 0) {
  8716. max.x += size.width;
  8717. }
  8718. if (size.height > 0) {
  8719. max.y += size.height;
  8720. }
  8721. areaInfo[curAreaIndex++] = { off: pos, size: size, min: min, max: max };
  8722. };
  8723. var isCanvas = this instanceof BABYLON.Canvas2D;
  8724. var marginH = this._marginOffset.x + this._marginOffset.z;
  8725. var marginV = this._marginOffset.y + this._marginOffset.w;
  8726. var actualSize = this.actualSize.multiplyByFloats(isCanvas ? 1 : this.scaleX, isCanvas ? 1 : this.scaleY);
  8727. var w = hasLayout ? (this.layoutAreaPos.x + this.layoutArea.width) : (marginH + actualSize.width);
  8728. var h = hasLayout ? (this.layoutAreaPos.y + this.layoutArea.height) : (marginV + actualSize.height);
  8729. var pos = (!hasLayout && !hasMargin && !hasPadding && hasPos) ? this.actualPosition : BABYLON.Vector2.Zero();
  8730. storeAreaInfo(pos, new BABYLON.Size(w, h));
  8731. // Compute the layout related data
  8732. if (hasLayout) {
  8733. var layoutOffset = this.layoutAreaPos.clone();
  8734. storeAreaInfo(layoutOffset, (hasMargin || hasPadding) ? this.layoutArea.clone() : actualSize.clone());
  8735. curOffset = layoutOffset.clone();
  8736. }
  8737. // Compute margin data
  8738. if (hasMargin) {
  8739. var marginOffset = curOffset.clone();
  8740. marginOffset.x += this._marginOffset.x;
  8741. marginOffset.y += this._marginOffset.y;
  8742. var marginArea = actualSize;
  8743. storeAreaInfo(marginOffset, marginArea);
  8744. curOffset = marginOffset.clone();
  8745. }
  8746. if (hasPadding) {
  8747. var contentOffset = curOffset.clone();
  8748. contentOffset.x += this._paddingOffset.x;
  8749. contentOffset.y += this._paddingOffset.y;
  8750. var contentArea = this.contentArea;
  8751. storeAreaInfo(contentOffset, contentArea);
  8752. curOffset = curOffset.add(contentOffset);
  8753. }
  8754. // Helper function that set the pos and size of a given prim
  8755. var setArea = function (i, j, pos, size) {
  8756. prims[i][j].position = pos;
  8757. prims[i][j].size = size;
  8758. };
  8759. var setFullRect = function (i, pos, size) {
  8760. var plist = prims[i];
  8761. plist[2].levelVisible = true;
  8762. plist[3].levelVisible = false;
  8763. plist[4].levelVisible = false;
  8764. plist[5].levelVisible = false;
  8765. setArea(i, 1, pos, size);
  8766. setArea(i, 2, pos, size);
  8767. };
  8768. var setQuadRect = function (i, areaIndex) {
  8769. var plist = prims[i];
  8770. plist[2].levelVisible = true;
  8771. plist[3].levelVisible = true;
  8772. plist[4].levelVisible = true;
  8773. plist[5].levelVisible = true;
  8774. var ca = areaInfo[areaIndex];
  8775. var na = areaInfo[areaIndex + 1];
  8776. var tp = new BABYLON.Vector2(ca.min.x, na.max.y);
  8777. var ts = new BABYLON.Size(ca.size.width, ca.max.y - tp.y);
  8778. var lp = new BABYLON.Vector2(ca.min.x, na.min.y);
  8779. var ls = new BABYLON.Size(na.min.x - ca.min.x, na.max.y - na.min.y);
  8780. var rp = new BABYLON.Vector2(na.max.x, na.min.y);
  8781. var rs = new BABYLON.Size(ca.max.x - na.max.x, na.max.y - na.min.y);
  8782. var bp = new BABYLON.Vector2(ca.min.x, ca.min.y);
  8783. var bs = new BABYLON.Size(ca.size.width, na.min.y - ca.min.y);
  8784. // Frame
  8785. plist[1].position = ca.off;
  8786. plist[1].size = ca.size;
  8787. // Top rect
  8788. plist[2].position = tp;
  8789. plist[2].size = ts;
  8790. // Left rect
  8791. plist[3].position = lp;
  8792. plist[3].size = ls;
  8793. // Right rect
  8794. plist[4].position = rp;
  8795. plist[4].size = rs;
  8796. // Bottom rect
  8797. plist[5].position = bp;
  8798. plist[5].size = bs;
  8799. };
  8800. var areaCount = curAreaIndex;
  8801. curAreaIndex = 0;
  8802. // Available zones
  8803. var availableZones = [false, hasLayout, hasMargin, hasPadding, true];
  8804. for (var k = 1; k < 5; k++) {
  8805. if (availableZones[k]) {
  8806. var ai = areaInfo[curAreaIndex];
  8807. setArea(k - 1, 0, BABYLON.Vector2.Zero(), ai.size);
  8808. // setArea(k-1, 1, Vector2.Zero(), ai.size);
  8809. if (k === 4) {
  8810. setFullRect(k - 1, ai.off, ai.size);
  8811. }
  8812. else {
  8813. setQuadRect(k - 1, curAreaIndex);
  8814. }
  8815. ++curAreaIndex;
  8816. }
  8817. }
  8818. Prim2DBase_1._updatingDebugArea = false;
  8819. };
  8820. Prim2DBase.prototype.findById = function (id) {
  8821. if (this._id === id) {
  8822. return this;
  8823. }
  8824. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8825. var child = _a[_i];
  8826. var r = child.findById(id);
  8827. if (r != null) {
  8828. return r;
  8829. }
  8830. }
  8831. };
  8832. Prim2DBase.prototype.onZOrderChanged = function () {
  8833. };
  8834. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  8835. return false;
  8836. };
  8837. /**
  8838. * Capture all the Events of the given PointerId for this primitive.
  8839. * Don't forget to call releasePointerEventsCapture when done.
  8840. * @param pointerId the Id of the pointer to capture the events from.
  8841. */
  8842. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  8843. return this.owner._setPointerCapture(pointerId, this);
  8844. };
  8845. /**
  8846. * Release a captured pointer made with setPointerEventCapture.
  8847. * @param pointerId the Id of the pointer to release the capture from.
  8848. */
  8849. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  8850. return this.owner._releasePointerCapture(pointerId, this);
  8851. };
  8852. /**
  8853. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  8854. * @param intersectInfo contains the settings of the intersection to perform, to setup before calling this method as well as the result, available after a call to this method.
  8855. */
  8856. Prim2DBase.prototype.intersect = function (intersectInfo) {
  8857. if (!intersectInfo) {
  8858. return false;
  8859. }
  8860. // If this is null it means this method is call for the first level, initialize stuffs
  8861. var firstLevel = !intersectInfo._globalPickPosition;
  8862. if (firstLevel) {
  8863. // Compute the pickPosition in global space and use it to find the local position for each level down, always relative from the world to get the maximum accuracy (and speed). The other way would have been to compute in local every level down relative to its parent's local, which wouldn't be as accurate (even if javascript number is 80bits accurate).
  8864. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  8865. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  8866. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  8867. intersectInfo.intersectedPrimitives = new Array();
  8868. intersectInfo.topMostIntersectedPrimitive = null;
  8869. }
  8870. if (!Prim2DBase_1._bypassGroup2DExclusion && this instanceof BABYLON.Group2D && this.isCachedGroup && !this.isRenderableGroup) {
  8871. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  8872. intersectInfo._exit(firstLevel);
  8873. return false;
  8874. }
  8875. if (!intersectInfo.intersectHidden && !this.isVisible) {
  8876. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  8877. intersectInfo._exit(firstLevel);
  8878. return false;
  8879. }
  8880. var id = this.id;
  8881. if (id != null && id.indexOf("__cachedSpriteOfGroup__") === 0) {
  8882. try {
  8883. Prim2DBase_1._bypassGroup2DExclusion = true;
  8884. var ownerGroup = this.getExternalData("__cachedGroup__");
  8885. return ownerGroup.intersect(intersectInfo);
  8886. }
  8887. finally {
  8888. Prim2DBase_1._bypassGroup2DExclusion = false;
  8889. }
  8890. }
  8891. // If we're testing a cachedGroup, we must reject pointer outside its levelBoundingInfo because children primitives could be partially clipped outside so we must not accept them as intersected when it's the case (because they're not visually visible).
  8892. var isIntersectionTest = false;
  8893. if (this instanceof BABYLON.Group2D) {
  8894. var g = this;
  8895. isIntersectionTest = g.isCachedGroup;
  8896. }
  8897. if (isIntersectionTest && !this.levelBoundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  8898. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  8899. intersectInfo._exit(firstLevel);
  8900. return false;
  8901. }
  8902. // Fast rejection test with boundingInfo
  8903. var boundingIntersected = true;
  8904. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  8905. if (this.isContainer) {
  8906. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  8907. intersectInfo._exit(firstLevel);
  8908. return false;
  8909. }
  8910. boundingIntersected = false;
  8911. }
  8912. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  8913. var levelIntersectRes = false;
  8914. if (this.isPickable) {
  8915. levelIntersectRes = boundingIntersected && this.levelIntersect(intersectInfo);
  8916. if (levelIntersectRes) {
  8917. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  8918. intersectInfo.intersectedPrimitives.push(pii);
  8919. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  8920. intersectInfo.topMostIntersectedPrimitive = pii;
  8921. }
  8922. // If we must stop at the first intersection, we're done, quit!
  8923. if (intersectInfo.findFirstOnly) {
  8924. intersectInfo._exit(firstLevel);
  8925. return true;
  8926. }
  8927. }
  8928. }
  8929. // Recurse to children if needed
  8930. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  8931. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8932. var curChild = _a[_i];
  8933. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  8934. if ((!curChild.isPickable && curChild.isContainer) || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  8935. continue;
  8936. }
  8937. // Must compute the localPickLocation for the children level
  8938. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  8939. // If we got an intersection with the child and we only need to find the first one, quit!
  8940. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  8941. intersectInfo._exit(firstLevel);
  8942. return true;
  8943. }
  8944. }
  8945. }
  8946. intersectInfo._exit(firstLevel);
  8947. return intersectInfo.isIntersected;
  8948. };
  8949. Prim2DBase.prototype.intersectOtherPrim = function (other) {
  8950. var setA = this.triList;
  8951. var setB = other.triList;
  8952. return BABYLON.Tri2DArray.doesIntersect(setA, setB, other.globalTransform.multiply(this.globalTransform.clone().invert()));
  8953. };
  8954. Object.defineProperty(Prim2DBase.prototype, "triList", {
  8955. get: function () {
  8956. if (this._primTriArrayDirty) {
  8957. this.updateTriArray();
  8958. this._primTriArrayDirty = false;
  8959. }
  8960. return this._primTriArray;
  8961. },
  8962. enumerable: true,
  8963. configurable: true
  8964. });
  8965. // This is the worst implementation, if the top level primitive doesn't override this method we will just store a quad that defines the bounding rect of the prim
  8966. Prim2DBase.prototype.updateTriArray = function () {
  8967. if (this._primTriArray == null) {
  8968. this._primTriArray = new BABYLON.Tri2DArray(2);
  8969. }
  8970. else {
  8971. this._primTriArray.clear(2);
  8972. }
  8973. var size = this.actualSize;
  8974. var lb = new BABYLON.Vector2(0, 0);
  8975. var rt = new BABYLON.Vector2(size.width, size.height);
  8976. var lt = new BABYLON.Vector2(0, size.height);
  8977. var rb = new BABYLON.Vector2(size.width, 0);
  8978. this._primTriArray.storeTriangle(0, lb, lt, rt);
  8979. this._primTriArray.storeTriangle(1, lb, rt, rb);
  8980. };
  8981. /**
  8982. * Move a child object into a new position regarding its siblings to change its rendering order.
  8983. * You can also use the shortcut methods to move top/bottom: moveChildToTop, moveChildToBottom, moveToTop, moveToBottom.
  8984. * @param child the object to move
  8985. * @param previous the object which will be before "child", if child has to be the first among sibling, set "previous" to null.
  8986. */
  8987. Prim2DBase.prototype.moveChild = function (child, previous) {
  8988. if (child.parent !== this) {
  8989. return false;
  8990. }
  8991. var childIndex = this._children.indexOf(child);
  8992. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  8993. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  8994. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  8995. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  8996. }
  8997. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  8998. return true;
  8999. };
  9000. /**
  9001. * Move the given child so it's displayed on the top of all its siblings
  9002. * @param child the primitive to move to the top
  9003. */
  9004. Prim2DBase.prototype.moveChildToTop = function (child) {
  9005. return this.moveChild(child, this._children[this._children.length - 1]);
  9006. };
  9007. /**
  9008. * Move the given child so it's displayed on the bottom of all its siblings
  9009. * @param child the primitive to move to the top
  9010. */
  9011. Prim2DBase.prototype.moveChildToBottom = function (child) {
  9012. return this.moveChild(child, null);
  9013. };
  9014. /**
  9015. * Move this primitive to be at the top among all its sibling
  9016. */
  9017. Prim2DBase.prototype.moveToTop = function () {
  9018. if (this.parent == null) {
  9019. return false;
  9020. }
  9021. return this.parent.moveChildToTop(this);
  9022. };
  9023. /**
  9024. * Move this primitive to be at the bottom among all its sibling
  9025. */
  9026. Prim2DBase.prototype.moveToBottom = function () {
  9027. if (this.parent == null) {
  9028. return false;
  9029. }
  9030. return this.parent.moveChildToBottom(this);
  9031. };
  9032. Prim2DBase.prototype.addChild = function (child) {
  9033. child._parent = this;
  9034. this._boundingBoxDirty();
  9035. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  9036. if (flat) {
  9037. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  9038. child._setZOrder(this._zOrder, true);
  9039. child._zMax = this._zOrder;
  9040. }
  9041. else {
  9042. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  9043. }
  9044. var length = this._children.push(child);
  9045. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  9046. };
  9047. /**
  9048. * Dispose the primitive, remove it from its parent.
  9049. */
  9050. Prim2DBase.prototype.dispose = function () {
  9051. if (!_super.prototype.dispose.call(this)) {
  9052. return false;
  9053. }
  9054. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagCollisionActor)) {
  9055. this.owner._primitiveCollisionManager._removeActor(this);
  9056. this._actorInfo = null;
  9057. }
  9058. if (this._pointerEventObservable) {
  9059. this._pointerEventObservable.clear();
  9060. this._pointerEventObservable = null;
  9061. }
  9062. if (this._actionManager) {
  9063. this._actionManager.dispose();
  9064. this._actionManager = null;
  9065. }
  9066. this.owner.scene.stopAnimation(this);
  9067. // If there's a parent, remove this object from its parent list
  9068. if (this._parent) {
  9069. if (this instanceof BABYLON.Group2D) {
  9070. var g = this;
  9071. if (g.isRenderableGroup) {
  9072. var parentRenderable = this.parent.traverseUp(function (p) { return (p instanceof BABYLON.Group2D && p.isRenderableGroup); });
  9073. if (parentRenderable != null) {
  9074. var l = parentRenderable._renderableData._childrenRenderableGroups;
  9075. var i_1 = l.indexOf(g);
  9076. if (i_1 !== -1) {
  9077. l.splice(i_1, 1);
  9078. }
  9079. }
  9080. }
  9081. }
  9082. var i = this._parent._children.indexOf(this);
  9083. if (i !== undefined) {
  9084. this._parent._children.splice(i, 1);
  9085. }
  9086. this._parent = null;
  9087. }
  9088. // Recurse dispose to children
  9089. if (this._children) {
  9090. while (this._children.length > 0) {
  9091. this._children[this._children.length - 1].dispose();
  9092. }
  9093. }
  9094. return true;
  9095. };
  9096. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  9097. if (this._renderGroup && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
  9098. this._renderGroup._addPrimToDirtyList(this);
  9099. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  9100. }
  9101. };
  9102. Prim2DBase.prototype._needPrepare = function () {
  9103. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty | BABYLON.SmartPropertyPrim.flagModelUpdate | BABYLON.SmartPropertyPrim.flagNeedRefresh) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  9104. };
  9105. Prim2DBase.prototype._prepareRender = function (context) {
  9106. var globalTransformStep = this.owner._globalTransformStep;
  9107. if (this._prepareProcessStep < globalTransformStep) {
  9108. this._prepareRenderPre(context);
  9109. this._prepareRenderPost(context);
  9110. this._prepareProcessStep = globalTransformStep;
  9111. }
  9112. };
  9113. Prim2DBase.prototype._prepareRenderPre = function (context) {
  9114. };
  9115. Prim2DBase.prototype._prepareRenderPost = function (context) {
  9116. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  9117. if (this instanceof BABYLON.Group2D) {
  9118. var self = this;
  9119. if (self.isRenderableGroup) {
  9120. return;
  9121. }
  9122. }
  9123. // Check if we need to recurse the prepare to children primitives
  9124. // - must have children
  9125. // - the global transform of this level have changed, or
  9126. // - the visible state of primitive has changed
  9127. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  9128. this.checkPropertiesDirty(Prim2DBase_1.isVisibleProperty.flagId))) {
  9129. this._children.forEach(function (c) {
  9130. // As usual stop the recursion if we meet a renderable group
  9131. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  9132. c._prepareRender(context);
  9133. }
  9134. });
  9135. }
  9136. // Finally reset the dirty flags as we've processed everything
  9137. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  9138. this._instanceDirtyFlags = 0;
  9139. };
  9140. Prim2DBase.prototype._canvasPreInit = function (settings) {
  9141. };
  9142. Prim2DBase.CheckParent = function (parent) {
  9143. //if (!Prim2DBase._isCanvasInit && !parent) {
  9144. // throw new Error("A Primitive needs a valid Parent, it can be any kind of Primitives based types, even the Canvas (with the exception that only Group2D can be direct child of a Canvas if the cache strategy used is TOPLEVELGROUPS)");
  9145. //}
  9146. };
  9147. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  9148. for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
  9149. var cur = list_1[_i];
  9150. cur.updateCachedStates(recurse);
  9151. }
  9152. };
  9153. Prim2DBase.prototype._parentLayoutDirty = function () {
  9154. if (!this._parent || this._parent.isDisposed) {
  9155. return;
  9156. }
  9157. this._parent._setLayoutDirty();
  9158. };
  9159. Prim2DBase.prototype._setLayoutDirty = function () {
  9160. this.onPrimBecomesDirty();
  9161. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  9162. };
  9163. Prim2DBase.prototype._checkPositionChange = function () {
  9164. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  9165. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  9166. return false;
  9167. }
  9168. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  9169. if (this instanceof BABYLON.Group2D && this.trackedNode == null) {
  9170. console.log("You can't set the position/x/y of " + this.id + " properties while positioning engine is used (margin, margin alignment and/or padding are set");
  9171. return false;
  9172. }
  9173. }
  9174. return true;
  9175. };
  9176. Prim2DBase.prototype._positioningDirty = function () {
  9177. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  9178. return;
  9179. }
  9180. this.onPrimBecomesDirty();
  9181. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  9182. };
  9183. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  9184. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9185. var child = _a[_i];
  9186. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  9187. child._updateRenderMode();
  9188. child.onPrimBecomesDirty();
  9189. child._spreadActualOpacityChanged();
  9190. }
  9191. };
  9192. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  9193. this._layoutEngine = engine;
  9194. };
  9195. Prim2DBase.prototype._updateLocalTransform = function () {
  9196. var tflags = Prim2DBase_1.actualPositionProperty.flagId | Prim2DBase_1.rotationProperty.flagId | Prim2DBase_1.scaleProperty.flagId | Prim2DBase_1.scaleXProperty.flagId | Prim2DBase_1.scaleYProperty.flagId | Prim2DBase_1.originProperty.flagId;
  9197. if (this.checkPropertiesDirty(tflags) || this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLocalTransformDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  9198. if (this.owner) {
  9199. this.owner.addupdateLocalTransformCounter(1);
  9200. }
  9201. // Check for positioning update
  9202. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  9203. this._updatePositioning();
  9204. }
  9205. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  9206. var local;
  9207. var pos = this._position ? this.position : (this.layoutAreaPos || Prim2DBase_1._v0);
  9208. var scale = new BABYLON.Vector3(this._scale.x, this._scale.y, 1);
  9209. var postScale = this._postScale;
  9210. var canvasScale = Prim2DBase_1._iv3;
  9211. var hasCanvasScale = false;
  9212. if (this._parent instanceof BABYLON.Canvas2D) {
  9213. hasCanvasScale = true;
  9214. canvasScale = this._parent._canvasLevelScale || Prim2DBase_1._iv3;
  9215. }
  9216. var globalScale = scale.multiplyByFloats(postScale.x * canvasScale.x, postScale.y * canvasScale.y, 1);
  9217. if ((this._origin.x === 0 && this._origin.y === 0) || this._hasMargin) {
  9218. // ###MATRIX PART###
  9219. {
  9220. local = BABYLON.Matrix.Compose(globalScale, rot, new BABYLON.Vector3(pos.x + this._marginOffset.x, pos.y + this._marginOffset.y, 0));
  9221. this._localTransform = local;
  9222. this._localLayoutTransform = BABYLON.Matrix.Compose(globalScale, rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  9223. }
  9224. }
  9225. else {
  9226. // ###MATRIX PART###
  9227. {
  9228. // -Origin offset
  9229. var t0 = Prim2DBase_1._t0;
  9230. var t1 = Prim2DBase_1._t1;
  9231. var t2 = Prim2DBase_1._t2;
  9232. var as = Prim2DBase_1._ts0;
  9233. as.copyFrom(this.actualSize);
  9234. as.width /= postScale.x;
  9235. as.height /= postScale.y;
  9236. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, t0);
  9237. // -Origin * rotation
  9238. rot.toRotationMatrix(t1);
  9239. t0.multiplyToRef(t1, t2);
  9240. // -Origin * rotation * scale
  9241. BABYLON.Matrix.ScalingToRef(this._scale.x, this._scale.y, 1, t0);
  9242. t2.multiplyToRef(t0, t1);
  9243. // -Origin * rotation * scale * Origin
  9244. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x), (as.height * this._origin.y), 0, t2);
  9245. t1.multiplyToRef(t2, t0);
  9246. // -Origin * rotation * scale * Origin * postScale
  9247. BABYLON.Matrix.ScalingToRef(postScale.x, postScale.y, 1, t1);
  9248. t0.multiplyToRef(t1, t2);
  9249. // -Origin * rotation * scale * Origin * postScale * Position
  9250. BABYLON.Matrix.TranslationToRef(pos.x + this._marginOffset.x, pos.y + this._marginOffset.y, 0, t0);
  9251. t2.multiplyToRef(t0, this._localTransform);
  9252. if (hasCanvasScale) {
  9253. BABYLON.Matrix.ScalingToRef(canvasScale.x, canvasScale.y, canvasScale.z, Prim2DBase_1._t1);
  9254. this._localTransform.multiplyToRef(Prim2DBase_1._t1, this._localTransform);
  9255. }
  9256. this._localLayoutTransform = BABYLON.Matrix.Compose(globalScale, rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  9257. }
  9258. }
  9259. this.clearPropertiesDirty(tflags);
  9260. this._setFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  9261. this._clearFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty);
  9262. return true;
  9263. }
  9264. return false;
  9265. };
  9266. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  9267. if (this.isDisposed) {
  9268. BABYLON.C2DLogging.setPostMessage(function () { return "disposed"; });
  9269. return;
  9270. }
  9271. var ownerProcessStep = this.owner._globalTransformProcessStep;
  9272. if (this._updateCachesProcessStep === ownerProcessStep) {
  9273. return;
  9274. }
  9275. this._updateCachesProcessStep = ownerProcessStep;
  9276. this.owner.addUpdateCachedStateCounter(1);
  9277. // Check if the parent is synced
  9278. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  9279. this._parent.updateCachedStates(false);
  9280. }
  9281. // Update Z-Order if needed
  9282. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  9283. this._updateZOrder();
  9284. }
  9285. // Update actualSize only if there' not positioning to recompute and the size changed
  9286. // Otherwise positioning will take care of it.
  9287. var sizeDirty = this.checkPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
  9288. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  9289. var size = this.size;
  9290. this.onPropertyChanged("actualSize", size, size, Prim2DBase_1.actualSizeProperty.flagId);
  9291. this.clearPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
  9292. }
  9293. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  9294. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  9295. // Check for layout update
  9296. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  9297. this.owner.addUpdateLayoutCounter(1);
  9298. this._layoutEngine.updateLayout(this);
  9299. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  9300. }
  9301. var autoContentChanged = false;
  9302. if (this.isSizeAuto) {
  9303. if (!this._lastAutoSizeArea) {
  9304. autoContentChanged = this.actualSize !== null;
  9305. }
  9306. else {
  9307. autoContentChanged = (!this._lastAutoSizeArea.equals(this.actualSize));
  9308. }
  9309. }
  9310. // Check for positioning update
  9311. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  9312. this._updatePositioning();
  9313. if (sizeDirty) {
  9314. this.clearPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
  9315. }
  9316. positioningComputed = true;
  9317. }
  9318. if (positioningComputed && this._parent) {
  9319. this._parentContentArea.copyFrom(this._parent.contentArea);
  9320. }
  9321. // Check if we must update this prim
  9322. if (!this._globalTransform || (this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || (this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty))) {
  9323. this.owner.addUpdateGlobalTransformCounter(1);
  9324. var curVisibleState = this.isVisible;
  9325. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  9326. // Detect a change of visibility
  9327. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  9328. // Get/compute the localTransform
  9329. var localDirty = this._updateLocalTransform();
  9330. var parentPaddingChanged = false;
  9331. var parentPaddingOffset = Prim2DBase_1._v0;
  9332. if (this._parent) {
  9333. parentPaddingOffset = new BABYLON.Vector2(this._parent._paddingOffset.x, this._parent._paddingOffset.y);
  9334. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  9335. }
  9336. // Check if there are changes in the parent that will force us to update the global matrix
  9337. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  9338. // Check if we have to update the globalTransform
  9339. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged || this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty)) {
  9340. //###MATRIX PART###
  9341. {
  9342. var globalTransform = this._parent ? this._parent._globalTransform : null;
  9343. var localTransform = void 0;
  9344. Prim2DBase_1._transMtx.copyFrom(this._localTransform);
  9345. Prim2DBase_1._transMtx.m[12] += parentPaddingOffset.x;
  9346. Prim2DBase_1._transMtx.m[13] += parentPaddingOffset.y;
  9347. localTransform = Prim2DBase_1._transMtx;
  9348. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  9349. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  9350. }
  9351. this._levelBoundingInfo.dirtyWorldAABB();
  9352. this._boundingInfo.dirtyWorldAABB();
  9353. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  9354. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  9355. this._clearFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  9356. }
  9357. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  9358. }
  9359. if (recurse) {
  9360. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9361. var child = _a[_i];
  9362. // Stop the recursion if we meet a renderable group
  9363. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  9364. }
  9365. }
  9366. };
  9367. Prim2DBase.prototype._updatePositioning = function () {
  9368. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  9369. BABYLON.C2DLogging.setPostMessage(function () { return "Not using positioning engine"; });
  9370. // Just in case, if may happen and if we don't clear some computation will keep going on forever
  9371. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  9372. return;
  9373. }
  9374. var success = true;
  9375. // Check if re-entrance is occurring
  9376. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagComputingPositioning) /* || (hasMargin && !this._layoutArea)*/) {
  9377. if (!this._actualSize) {
  9378. this._actualSize = this.size.clone() || BABYLON.Size.Zero();
  9379. this._contentArea.copyFrom(this._actualSize);
  9380. }
  9381. if (!this._actualPosition) {
  9382. this._actualPosition = BABYLON.Vector2.Zero();
  9383. }
  9384. BABYLON.C2DLogging.setPostMessage(function () { return "Re entrance detected"; });
  9385. return;
  9386. }
  9387. if (this.owner) {
  9388. this.owner.addUpdatePositioningCounter(1);
  9389. }
  9390. // Set the flag to avoid re-entrance
  9391. this._setFlags(BABYLON.SmartPropertyPrim.flagComputingPositioning);
  9392. try {
  9393. var isSizeAuto = this.isSizeAuto;
  9394. var isVSizeAuto = this.isVerticalSizeAuto;
  9395. var isHSizeAuto = this.isHorizontalSizeAuto;
  9396. var ma = this._marginAlignment ? this._marginAlignment.clone() : new PrimitiveAlignment();
  9397. var levelScale = this._scale;
  9398. var primSize = this.size;
  9399. // If the primitive has no size and is autoSized without margin, then set a Stretch/Stretch margin alignment for the primitive to take all the available space
  9400. if (!this._hasMarginAlignment && (isSizeAuto && (primSize === Prim2DBase_1.nullSize || (primSize === this._internalSize && primSize.width === 0 && primSize.height === 0)))) {
  9401. if (isSizeAuto || this.actualSize.width == null) {
  9402. ma.horizontal = PrimitiveAlignment.AlignStretch;
  9403. }
  9404. if (isSizeAuto || this.actualSize.height == null) {
  9405. ma.vertical = PrimitiveAlignment.AlignStretch;
  9406. }
  9407. }
  9408. var transformedBSize = Prim2DBase_1._size3;
  9409. var bSize = Prim2DBase_1._size4;
  9410. var bi = this.boundingInfo;
  9411. var tbi = Prim2DBase_1._tbi;
  9412. bi.transformToRef(BABYLON.Matrix.RotationZ(this.rotation), tbi);
  9413. tbi.sizeToRef(transformedBSize);
  9414. bi.sizeToRef(bSize);
  9415. bi.extent.subtractToRef(bi.center, Prim2DBase_1._pv1);
  9416. tbi.center.subtractToRef(tbi.extent, Prim2DBase_1._pv2);
  9417. var transbi = Prim2DBase_1._pv2.add(Prim2DBase_1._pv1);
  9418. var setSize = false;
  9419. var hasMargin = (this._margin !== null && !this._margin.isDefault) || (ma !== null && !ma.isDefault);
  9420. var primNewSize = Prim2DBase_1._size;
  9421. var hasH = false;
  9422. var hasV = false;
  9423. var paddingApplied = false;
  9424. var hasPadding = this._hasPadding;
  9425. // Compute the size
  9426. // The size is the size of the prim or the computed one if there's a marginAlignment of Stretch
  9427. if (hasMargin) {
  9428. var layoutArea = this.layoutArea;
  9429. if (layoutArea /*&& layoutArea.width >= size.width */ && ma.horizontal === PrimitiveAlignment.AlignStretch) {
  9430. this.margin.computeWithAlignment(layoutArea, primSize, ma, levelScale, this._marginOffset, primNewSize, false, PrimitiveThickness.ComputeH);
  9431. hasH = true;
  9432. setSize = true;
  9433. }
  9434. if (layoutArea /*&& layoutArea.height >= size.height */ && ma.vertical === PrimitiveAlignment.AlignStretch) {
  9435. this.margin.computeWithAlignment(layoutArea, primSize, ma, levelScale, this._marginOffset, primNewSize, false, PrimitiveThickness.ComputeV);
  9436. hasV = true;
  9437. setSize = true;
  9438. }
  9439. }
  9440. if (!hasH) {
  9441. // If the Horizontal size is Auto, we have to compute it from its content and padding
  9442. if (isHSizeAuto) {
  9443. primNewSize.width = bSize.width;
  9444. setSize = true;
  9445. }
  9446. else {
  9447. primNewSize.width = primSize.width;
  9448. }
  9449. }
  9450. if (!hasV) {
  9451. // If the Vertical size is Auto, we have to compute it from its content and padding
  9452. if (isVSizeAuto) {
  9453. primNewSize.height = bSize.height;
  9454. setSize = true;
  9455. }
  9456. else {
  9457. primNewSize.height = primSize.height;
  9458. }
  9459. }
  9460. if (!isVSizeAuto || !isHSizeAuto) {
  9461. Prim2DBase_1._curContentArea.copyFrom(this._contentArea);
  9462. if (hasPadding) {
  9463. var area = Prim2DBase_1._icArea;
  9464. var zone = Prim2DBase_1._icZone;
  9465. this._getInitialContentAreaToRef(primNewSize, zone, area);
  9466. area.width = Math.max(0, area.width);
  9467. area.height = Math.max(0, area.height);
  9468. this.padding.compute(area, this._paddingOffset, Prim2DBase_1._size2);
  9469. if (!isHSizeAuto) {
  9470. this._paddingOffset.x += zone.x;
  9471. this._paddingOffset.z -= zone.z;
  9472. this._contentArea.width = Prim2DBase_1._size2.width;
  9473. }
  9474. if (!isVSizeAuto) {
  9475. this._paddingOffset.y += zone.y;
  9476. this._paddingOffset.w -= zone.w;
  9477. this._contentArea.height = Prim2DBase_1._size2.height;
  9478. }
  9479. }
  9480. else {
  9481. this._contentArea.copyFrom(primNewSize);
  9482. }
  9483. if (!Prim2DBase_1._curContentArea.equals(this._contentArea)) {
  9484. this._setLayoutDirty();
  9485. }
  9486. paddingApplied = true;
  9487. }
  9488. // Finally we apply margin to determine the position
  9489. if (hasMargin) {
  9490. var layoutArea = this.layoutArea;
  9491. var mo = this._marginOffset;
  9492. var margin = this.margin;
  9493. // We compute margin only if the layoutArea is as big as the contentSize, sometime this code is triggered when the layoutArea is
  9494. // not yet set and computing alignment would result into a bad size.
  9495. // So we make sure with compute alignment only if the layoutArea is good
  9496. if (layoutArea && layoutArea.width >= transformedBSize.width && layoutArea.height >= transformedBSize.height) {
  9497. margin.computeWithAlignment(layoutArea, transformedBSize, ma, levelScale, mo, Prim2DBase_1._size2);
  9498. }
  9499. else {
  9500. mo.copyFromFloats(0, 0, 0, 0);
  9501. }
  9502. var tbi_1 = Prim2DBase_1._tpsBB;
  9503. tbi_1.copyFrom(bi);
  9504. var minmax = Prim2DBase_1._bMinMax;
  9505. tbi_1.minMaxToRef(minmax);
  9506. minmax.z += margin.leftPixels + margin.rightPixels;
  9507. minmax.w += margin.topPixels + margin.bottomPixels;
  9508. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(minmax.x, minmax.z, minmax.y, minmax.w, tbi_1);
  9509. // Check if the layoutBoundingInfo changed
  9510. var changed = false;
  9511. if (!this._layoutBoundingInfo) {
  9512. this._layoutBoundingInfo = tbi_1.clone();
  9513. changed = true;
  9514. }
  9515. else if (!this._layoutBoundingInfo.equals(tbi_1)) {
  9516. this._layoutBoundingInfo.copyFrom(tbi_1);
  9517. changed = true;
  9518. }
  9519. if (changed) {
  9520. var p = this._parent;
  9521. while (p) {
  9522. if (p.isSizedByContent) {
  9523. p._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  9524. p.onPrimitivePropertyDirty(Prim2DBase_1.actualSizeProperty.flagId);
  9525. }
  9526. else {
  9527. break;
  9528. }
  9529. p = p._parent;
  9530. }
  9531. this.onPrimitivePropertyDirty(Prim2DBase_1.actualSizeProperty.flagId);
  9532. }
  9533. }
  9534. var lap = this.layoutAreaPos;
  9535. this._marginOffset.x -= transbi.x * levelScale.x;
  9536. this._marginOffset.y -= transbi.y * levelScale.y;
  9537. this.actualPosition = new BABYLON.Vector2(this._marginOffset.x + (lap ? lap.x : 0), this._marginOffset.y + (lap ? lap.y : 0));
  9538. // if (setSize) {
  9539. this.actualSize = primNewSize.clone();
  9540. // }
  9541. this._setFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty);
  9542. if (isSizeAuto) {
  9543. this._lastAutoSizeArea = this.actualSize;
  9544. }
  9545. if (this.displayDebugAreas) {
  9546. this._updateDebugArea();
  9547. }
  9548. }
  9549. finally {
  9550. BABYLON.C2DLogging.setPostMessage(function () { return "Succeeded"; });
  9551. this._clearFlags(BABYLON.SmartPropertyPrim.flagComputingPositioning);
  9552. // Remove dirty flag
  9553. if (success) {
  9554. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  9555. }
  9556. }
  9557. };
  9558. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  9559. /**
  9560. * Get the content are of this primitive, this area is computed the primitive size and using the padding property.
  9561. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  9562. */
  9563. get: function () {
  9564. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  9565. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  9566. this._updatePositioning();
  9567. }
  9568. return this._contentArea;
  9569. }
  9570. else {
  9571. return this.size;
  9572. }
  9573. },
  9574. enumerable: true,
  9575. configurable: true
  9576. });
  9577. Prim2DBase.prototype._patchHierarchy = function (owner) {
  9578. if (this._owner == null) {
  9579. this._owner = owner;
  9580. this.onSetOwner();
  9581. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  9582. }
  9583. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  9584. if (this._renderGroup != null) {
  9585. return;
  9586. }
  9587. if (this instanceof BABYLON.Group2D) {
  9588. var group = this;
  9589. group.detectGroupStates();
  9590. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  9591. group.owner._registerTrackedNode(this);
  9592. }
  9593. }
  9594. this._renderGroup = this.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  9595. if (this._parent) {
  9596. this._parentLayoutDirty();
  9597. }
  9598. // Make sure the prim is in the dirtyList if it should be
  9599. if (this._renderGroup && this.isDirty) {
  9600. var list = this._renderGroup._renderableData._primDirtyList;
  9601. var i = list.indexOf(this);
  9602. if (i === -1) {
  9603. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  9604. list.push(this);
  9605. }
  9606. }
  9607. // Recurse
  9608. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9609. var child = _a[_i];
  9610. child._hierarchyDepth = this._hierarchyDepth + 1;
  9611. child._patchHierarchy(owner);
  9612. }
  9613. };
  9614. Prim2DBase.prototype.onSetOwner = function () {
  9615. };
  9616. Prim2DBase.prototype._updateZOrder = function () {
  9617. var prevLinPos = this._primLinearPosition;
  9618. var startI = 0;
  9619. var startZ = this._zOrder;
  9620. // We must start rebuilding Z-Order from the Prim before the first one that changed, because we know its Z-Order is correct, so are its children, but it's better to recompute everything from this point instead of finding the last valid children
  9621. var childrenCount = this._children.length;
  9622. if (this._firstZDirtyIndex > 0) {
  9623. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  9624. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  9625. prevLinPos = prevPrim._primLinearPosition;
  9626. startI = this._firstZDirtyIndex - 1;
  9627. startZ = prevPrim._zOrder;
  9628. }
  9629. }
  9630. var startPos = prevLinPos;
  9631. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  9632. Prim2DBase_1._totalCount = 0;
  9633. for (var i = startI; i < childrenCount; i++) {
  9634. var child = this._children[i];
  9635. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  9636. }
  9637. // Compute the new Z-Order for all the primitives
  9638. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  9639. var zDelta = (this._zMax - startZ) / (Prim2DBase_1._totalCount * (Prim2DBase_1._zRebuildReentrency ? 1 : 1.2));
  9640. // If the computed delta is less than the smallest allowed by the depth buffer, we rebuild the Z-Order from the very beginning of the primitive's children (that is, the first) to redistribute uniformly the Z.
  9641. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  9642. // Check for re-entrance, if the flag is true we already attempted a rebuild but couldn't get a better zDelta, go up in the hierarchy to rebuilt one level up, hoping to get this time a decent delta, otherwise, recurse until we got it or when no parent is reached, which would mean the canvas would have more than 16 millions of primitives...
  9643. if (Prim2DBase_1._zRebuildReentrency) {
  9644. var p = this._parent;
  9645. if (p == null) {
  9646. // Can't find a good Z delta and we're in the canvas, which mean we're dealing with too many objects (which should never happen, but well...)
  9647. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  9648. Prim2DBase_1._zRebuildReentrency = false;
  9649. return;
  9650. }
  9651. p._firstZDirtyIndex = 0;
  9652. return p._updateZOrder();
  9653. }
  9654. Prim2DBase_1._zRebuildReentrency = true;
  9655. this._firstZDirtyIndex = 0;
  9656. this._updateZOrder();
  9657. Prim2DBase_1._zRebuildReentrency = false;
  9658. }
  9659. for (var i = startI; i < childrenCount; i++) {
  9660. var child = this._children[i];
  9661. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  9662. }
  9663. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  9664. for (var _i = 0, _a = Prim2DBase_1._zOrderChangedNotifList; _i < _a.length; _i++) {
  9665. var p = _a[_i];
  9666. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  9667. }
  9668. Prim2DBase_1._zOrderChangedNotifList.splice(0);
  9669. this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  9670. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  9671. };
  9672. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  9673. if (this.isManualZOrder) {
  9674. return prevLinPos;
  9675. }
  9676. this._primLinearPosition = ++prevLinPos;
  9677. Prim2DBase_1._totalCount++;
  9678. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  9679. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  9680. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9681. var child = _a[_i];
  9682. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  9683. }
  9684. }
  9685. return prevLinPos;
  9686. };
  9687. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  9688. if (this.isManualZOrder) {
  9689. return null;
  9690. }
  9691. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  9692. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  9693. this._setZOrder(newZ, false);
  9694. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  9695. this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  9696. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  9697. }
  9698. var curZ = newZ;
  9699. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  9700. if (isFlat) {
  9701. if (this._children.length > 0) {
  9702. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  9703. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9704. var child = _a[_i];
  9705. child._updatePrimitiveFlatZOrder(this._zOrder);
  9706. }
  9707. }
  9708. }
  9709. else {
  9710. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  9711. var child = _c[_b];
  9712. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  9713. if (r != null) {
  9714. curZ = r;
  9715. }
  9716. }
  9717. }
  9718. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  9719. return curZ;
  9720. };
  9721. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  9722. if (this.isManualZOrder) {
  9723. return;
  9724. }
  9725. this._setZOrder(newZ, false);
  9726. this._zMax = newZ;
  9727. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  9728. this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  9729. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  9730. }
  9731. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9732. var child = _a[_i];
  9733. child._updatePrimitiveFlatZOrder(newZ);
  9734. }
  9735. };
  9736. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  9737. if (newZ !== this._zOrder) {
  9738. this._zOrder = newZ;
  9739. this.onPrimBecomesDirty();
  9740. this.onZOrderChanged();
  9741. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  9742. if (directEmit) {
  9743. this._actualZOrderChangedObservable.notifyObservers(newZ);
  9744. }
  9745. else {
  9746. Prim2DBase_1._zOrderChangedNotifList.push(this);
  9747. }
  9748. }
  9749. }
  9750. };
  9751. Prim2DBase.prototype._updateRenderMode = function () {
  9752. };
  9753. /**
  9754. * This method is used to alter the contentArea of the Primitive before margin is applied.
  9755. * In most of the case you won't need to override this method, but it can prove some usefulness, check the Rectangle2D class for a concrete application.
  9756. * @param primSize the current size of the primitive
  9757. * @param initialContentPosition the position of the initial content area to compute, a valid object is passed, you have to set its properties. PLEASE ROUND the values, we're talking about pixels and fraction of them is not a good thing! x, y, z, w area left, bottom, right, top
  9758. * @param initialContentArea the size of the initial content area to compute, a valid object is passed, you have to set its properties. PLEASE ROUND the values, we're talking about pixels and fraction of them is not a good thing!
  9759. */
  9760. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  9761. initialContentArea.copyFrom(primSize);
  9762. initialContentPosition.x = initialContentPosition.y = initialContentPosition.z = initialContentPosition.w = 0;
  9763. };
  9764. /**
  9765. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  9766. * Check the Rectangle2D implementation for a concrete application.
  9767. * @param primSize the current size of the primitive
  9768. * @param newPrimSize the new size of the primitive. PLEASE ROUND THE values, we're talking about pixels and fraction of them are not our friends!
  9769. */
  9770. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, paddingOffset, newPrimSize) {
  9771. newPrimSize.copyFrom(primSize);
  9772. };
  9773. Object.defineProperty(Prim2DBase.prototype, "layoutData", {
  9774. /**
  9775. * Get/set the layout data to use for this primitive.
  9776. */
  9777. get: function () {
  9778. return this._layoutData;
  9779. },
  9780. set: function (value) {
  9781. if (this._layoutData === value) {
  9782. return;
  9783. }
  9784. this._layoutData = value;
  9785. },
  9786. enumerable: true,
  9787. configurable: true
  9788. });
  9789. return Prim2DBase;
  9790. }(BABYLON.SmartPropertyPrim));
  9791. Prim2DBase.PRIM2DBASE_PROPCOUNT = 25;
  9792. Prim2DBase._bigInt = Math.pow(2, 30);
  9793. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  9794. Prim2DBase._nullSize = BABYLON.Size.Zero();
  9795. Prim2DBase.boundinbBoxReentrency = -1;
  9796. Prim2DBase.nullSize = BABYLON.Size.Zero();
  9797. Prim2DBase._bMinMax = BABYLON.Vector4.Zero();
  9798. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  9799. Prim2DBase._bSize = BABYLON.Size.Zero();
  9800. Prim2DBase._tpsBB = new BABYLON.BoundingInfo2D();
  9801. Prim2DBase._tpsBB2 = new BABYLON.BoundingInfo2D();
  9802. Prim2DBase._updatingDebugArea = false;
  9803. Prim2DBase._bypassGroup2DExclusion = false;
  9804. Prim2DBase._isCanvasInit = false;
  9805. Prim2DBase._t0 = new BABYLON.Matrix();
  9806. Prim2DBase._t1 = new BABYLON.Matrix();
  9807. Prim2DBase._t2 = new BABYLON.Matrix();
  9808. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  9809. Prim2DBase._v30 = BABYLON.Vector3.Zero(); // Must stay with the value 0,0,0
  9810. Prim2DBase._iv3 = new BABYLON.Vector3(1, 1, 1); // Must stay identity vector
  9811. Prim2DBase._ts0 = BABYLON.Size.Zero();
  9812. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  9813. Prim2DBase._transTT = BABYLON.Transform2D.Zero();
  9814. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  9815. Prim2DBase._icZone = BABYLON.Vector4.Zero();
  9816. Prim2DBase._icArea = BABYLON.Size.Zero();
  9817. Prim2DBase._size = BABYLON.Size.Zero();
  9818. Prim2DBase._size2 = BABYLON.Size.Zero();
  9819. Prim2DBase._size3 = BABYLON.Size.Zero();
  9820. Prim2DBase._size4 = BABYLON.Size.Zero();
  9821. Prim2DBase._pv0 = BABYLON.Vector2.Zero();
  9822. Prim2DBase._curContentArea = BABYLON.Size.Zero();
  9823. Prim2DBase._piv = new BABYLON.Vector2(1, 1);
  9824. Prim2DBase._tbi = new BABYLON.BoundingInfo2D();
  9825. Prim2DBase._pv1 = BABYLON.Vector2.Zero();
  9826. Prim2DBase._pv2 = BABYLON.Vector2.Zero();
  9827. Prim2DBase._zOrderChangedNotifList = new Array();
  9828. Prim2DBase._zRebuildReentrency = false;
  9829. Prim2DBase._totalCount = 0;
  9830. __decorate([
  9831. BABYLON.logProp(null, false, false, false),
  9832. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase_1.actualPositionProperty = pi; }, false, false, true)
  9833. ], Prim2DBase.prototype, "actualPosition", null);
  9834. __decorate([
  9835. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 1, function (pi) { return Prim2DBase_1.actualXProperty = pi; }, false, false, true)
  9836. ], Prim2DBase.prototype, "actualX", null);
  9837. __decorate([
  9838. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 2, function (pi) { return Prim2DBase_1.actualYProperty = pi; }, false, false, true)
  9839. ], Prim2DBase.prototype, "actualY", null);
  9840. __decorate([
  9841. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 3, function (pi) { return Prim2DBase_1.positionProperty = pi; }, false, false, true)
  9842. ], Prim2DBase.prototype, "position", null);
  9843. __decorate([
  9844. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 4, function (pi) { return Prim2DBase_1.xProperty = pi; }, false, false, true)
  9845. ], Prim2DBase.prototype, "x", null);
  9846. __decorate([
  9847. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 5, function (pi) { return Prim2DBase_1.yProperty = pi; }, false, false, true)
  9848. ], Prim2DBase.prototype, "y", null);
  9849. __decorate([
  9850. BABYLON.logProp(),
  9851. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 6, function (pi) { return Prim2DBase_1.sizeProperty = pi; }, false, true)
  9852. ], Prim2DBase.prototype, "size", null);
  9853. __decorate([
  9854. BABYLON.logMethod()
  9855. ], Prim2DBase.prototype, "internalGetSize", null);
  9856. __decorate([
  9857. BABYLON.logMethod()
  9858. ], Prim2DBase.prototype, "internalSetSize", null);
  9859. __decorate([
  9860. BABYLON.logProp(),
  9861. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 7, function (pi) { return Prim2DBase_1.widthProperty = pi; }, false, true)
  9862. ], Prim2DBase.prototype, "width", null);
  9863. __decorate([
  9864. BABYLON.logProp(),
  9865. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 8, function (pi) { return Prim2DBase_1.heightProperty = pi; }, false, true)
  9866. ], Prim2DBase.prototype, "height", null);
  9867. __decorate([
  9868. BABYLON.logProp(),
  9869. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 9, function (pi) { return Prim2DBase_1.rotationProperty = pi; }, false, true)
  9870. ], Prim2DBase.prototype, "rotation", null);
  9871. __decorate([
  9872. BABYLON.logProp(),
  9873. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 10, function (pi) { return Prim2DBase_1.scaleProperty = pi; }, false, true)
  9874. ], Prim2DBase.prototype, "scale", null);
  9875. __decorate([
  9876. BABYLON.logProp(),
  9877. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 11, function (pi) { return Prim2DBase_1.actualSizeProperty = pi; }, false, true)
  9878. ], Prim2DBase.prototype, "actualSize", null);
  9879. __decorate([
  9880. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 12, function (pi) { return Prim2DBase_1.actualWidthProperty = pi; }, false, true)
  9881. ], Prim2DBase.prototype, "actualWidth", null);
  9882. __decorate([
  9883. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 13, function (pi) { return Prim2DBase_1.actualHeightProperty = pi; }, false, true)
  9884. ], Prim2DBase.prototype, "actualHeight", null);
  9885. __decorate([
  9886. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 14, function (pi) { return Prim2DBase_1.originProperty = pi; }, false, true)
  9887. ], Prim2DBase.prototype, "origin", null);
  9888. __decorate([
  9889. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 15, function (pi) { return Prim2DBase_1.levelVisibleProperty = pi; })
  9890. ], Prim2DBase.prototype, "levelVisible", null);
  9891. __decorate([
  9892. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 16, function (pi) { return Prim2DBase_1.isVisibleProperty = pi; })
  9893. ], Prim2DBase.prototype, "isVisible", null);
  9894. __decorate([
  9895. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 17, function (pi) { return Prim2DBase_1.zOrderProperty = pi; })
  9896. ], Prim2DBase.prototype, "zOrder", null);
  9897. __decorate([
  9898. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 18, function (pi) { return Prim2DBase_1.marginProperty = pi; })
  9899. ], Prim2DBase.prototype, "margin", null);
  9900. __decorate([
  9901. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 19, function (pi) { return Prim2DBase_1.paddingProperty = pi; })
  9902. ], Prim2DBase.prototype, "padding", null);
  9903. __decorate([
  9904. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 20, function (pi) { return Prim2DBase_1.marginAlignmentProperty = pi; })
  9905. ], Prim2DBase.prototype, "marginAlignment", null);
  9906. __decorate([
  9907. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 21, function (pi) { return Prim2DBase_1.opacityProperty = pi; })
  9908. ], Prim2DBase.prototype, "opacity", null);
  9909. __decorate([
  9910. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 22, function (pi) { return Prim2DBase_1.scaleXProperty = pi; }, false, true)
  9911. ], Prim2DBase.prototype, "scaleX", null);
  9912. __decorate([
  9913. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 23, function (pi) { return Prim2DBase_1.scaleYProperty = pi; }, false, true)
  9914. ], Prim2DBase.prototype, "scaleY", null);
  9915. __decorate([
  9916. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 24, function (pi) { return Prim2DBase_1.actualScaleProperty = pi; }, false, true)
  9917. ], Prim2DBase.prototype, "actualScale", null);
  9918. __decorate([
  9919. BABYLON.logProp("", true)
  9920. ], Prim2DBase.prototype, "boundingInfo", null);
  9921. __decorate([
  9922. BABYLON.logProp("", true)
  9923. ], Prim2DBase.prototype, "layoutBoundingInfo", null);
  9924. __decorate([
  9925. BABYLON.logMethod("", true)
  9926. ], Prim2DBase.prototype, "_setLayoutDirty", null);
  9927. __decorate([
  9928. BABYLON.logMethod("", true)
  9929. ], Prim2DBase.prototype, "_positioningDirty", null);
  9930. __decorate([
  9931. BABYLON.logMethod()
  9932. ], Prim2DBase.prototype, "updateCachedStates", null);
  9933. __decorate([
  9934. BABYLON.logMethod()
  9935. ], Prim2DBase.prototype, "_updatePositioning", null);
  9936. Prim2DBase = Prim2DBase_1 = __decorate([
  9937. BABYLON.className("Prim2DBase", "BABYLON")
  9938. ], Prim2DBase);
  9939. BABYLON.Prim2DBase = Prim2DBase;
  9940. var PrimitiveAlignment_1, PrimitiveThickness_1, Prim2DBase_1;
  9941. })(BABYLON || (BABYLON = {}));
  9942. //# sourceMappingURL=babylon.prim2dBase.js.map
  9943. var __extends = (this && this.__extends) || function (d, b) {
  9944. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9945. function __() { this.constructor = d; }
  9946. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  9947. };
  9948. var BABYLON;
  9949. (function (BABYLON) {
  9950. var GroupInstanceInfo = (function () {
  9951. function GroupInstanceInfo(owner, mrc, partCount) {
  9952. this._partCount = partCount;
  9953. this.owner = owner;
  9954. this.modelRenderCache = mrc;
  9955. this.modelRenderCache.addRef();
  9956. this.partIndexFromId = new BABYLON.StringDictionary();
  9957. this._usedShaderCategories = new Array(partCount);
  9958. this._strides = new Array(partCount);
  9959. this._opaqueData = null;
  9960. this._alphaTestData = null;
  9961. this._transparentData = null;
  9962. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  9963. }
  9964. GroupInstanceInfo.prototype.dispose = function () {
  9965. if (this._isDisposed) {
  9966. return false;
  9967. }
  9968. if (this.modelRenderCache) {
  9969. this.modelRenderCache.dispose();
  9970. this.modelRenderCache = null;
  9971. }
  9972. var engine = this.owner.owner.engine;
  9973. if (this._opaqueData) {
  9974. this._opaqueData.forEach(function (d) { return d.dispose(engine); });
  9975. this._opaqueData = null;
  9976. }
  9977. if (this._alphaTestData) {
  9978. this._alphaTestData.forEach(function (d) { return d.dispose(engine); });
  9979. this._alphaTestData = null;
  9980. }
  9981. if (this._transparentData) {
  9982. this._transparentData.forEach(function (d) { return d.dispose(engine); });
  9983. this._transparentData = null;
  9984. }
  9985. this.partIndexFromId = null;
  9986. this._isDisposed = true;
  9987. return true;
  9988. };
  9989. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  9990. get: function () {
  9991. return this._opaqueData != null;
  9992. },
  9993. enumerable: true,
  9994. configurable: true
  9995. });
  9996. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  9997. get: function () {
  9998. return this._alphaTestData != null;
  9999. },
  10000. enumerable: true,
  10001. configurable: true
  10002. });
  10003. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  10004. get: function () {
  10005. return this._transparentData != null;
  10006. },
  10007. enumerable: true,
  10008. configurable: true
  10009. });
  10010. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  10011. get: function () {
  10012. if (!this._opaqueData) {
  10013. this._opaqueData = new Array(this._partCount);
  10014. for (var i = 0; i < this._partCount; i++) {
  10015. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  10016. }
  10017. }
  10018. return this._opaqueData;
  10019. },
  10020. enumerable: true,
  10021. configurable: true
  10022. });
  10023. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  10024. get: function () {
  10025. if (!this._alphaTestData) {
  10026. this._alphaTestData = new Array(this._partCount);
  10027. for (var i = 0; i < this._partCount; i++) {
  10028. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  10029. }
  10030. }
  10031. return this._alphaTestData;
  10032. },
  10033. enumerable: true,
  10034. configurable: true
  10035. });
  10036. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  10037. get: function () {
  10038. if (!this._transparentData) {
  10039. this._transparentData = new Array(this._partCount);
  10040. for (var i = 0; i < this._partCount; i++) {
  10041. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  10042. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  10043. }
  10044. }
  10045. return this._transparentData;
  10046. },
  10047. enumerable: true,
  10048. configurable: true
  10049. });
  10050. GroupInstanceInfo.prototype.sortTransparentData = function () {
  10051. if (!this.transparentOrderDirty) {
  10052. return;
  10053. }
  10054. for (var i = 0; i < this._transparentData.length; i++) {
  10055. var td = this._transparentData[i];
  10056. td._partData.sort();
  10057. }
  10058. this.transparentOrderDirty = false;
  10059. };
  10060. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  10061. get: function () {
  10062. return this._usedShaderCategories;
  10063. },
  10064. enumerable: true,
  10065. configurable: true
  10066. });
  10067. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  10068. get: function () {
  10069. return this._strides;
  10070. },
  10071. enumerable: true,
  10072. configurable: true
  10073. });
  10074. return GroupInstanceInfo;
  10075. }());
  10076. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  10077. var TransparentSegment = (function () {
  10078. function TransparentSegment() {
  10079. this.groupInsanceInfo = null;
  10080. this.startZ = 0;
  10081. this.endZ = 0;
  10082. this.startDataIndex = BABYLON.Prim2DBase._bigInt;
  10083. this.endDataIndex = 0;
  10084. this.partBuffers = null;
  10085. }
  10086. TransparentSegment.prototype.dispose = function (engine) {
  10087. if (this.partBuffers) {
  10088. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  10089. this.partBuffers.splice(0);
  10090. this.partBuffers = null;
  10091. }
  10092. };
  10093. return TransparentSegment;
  10094. }());
  10095. BABYLON.TransparentSegment = TransparentSegment;
  10096. var GroupInfoPartData = (function () {
  10097. function GroupInfoPartData(stride) {
  10098. this._partData = null;
  10099. this._partBuffer = null;
  10100. this._partBufferSize = 0;
  10101. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  10102. this._isDisposed = false;
  10103. }
  10104. GroupInfoPartData.prototype.dispose = function (engine) {
  10105. if (this._isDisposed) {
  10106. return false;
  10107. }
  10108. if (this._partBuffer) {
  10109. engine._releaseBuffer(this._partBuffer);
  10110. this._partBuffer = null;
  10111. }
  10112. this._partData = null;
  10113. this._isDisposed = true;
  10114. };
  10115. return GroupInfoPartData;
  10116. }());
  10117. BABYLON.GroupInfoPartData = GroupInfoPartData;
  10118. var TransparentGroupInfoPartData = (function (_super) {
  10119. __extends(TransparentGroupInfoPartData, _super);
  10120. function TransparentGroupInfoPartData(stride, zoff) {
  10121. var _this = _super.call(this, stride) || this;
  10122. _this._partData.compareValueOffset = zoff;
  10123. _this._partData.sortingAscending = false;
  10124. return _this;
  10125. }
  10126. return TransparentGroupInfoPartData;
  10127. }(GroupInfoPartData));
  10128. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  10129. var ModelRenderCache = (function () {
  10130. function ModelRenderCache(engine, modelKey) {
  10131. this._engine = engine;
  10132. this._modelKey = modelKey;
  10133. this._nextKey = 1;
  10134. this._refCounter = 1;
  10135. this._partData = null;
  10136. }
  10137. ModelRenderCache.prototype.dispose = function () {
  10138. if (--this._refCounter !== 0) {
  10139. return false;
  10140. }
  10141. // Remove the Model Render Cache from the global dictionary
  10142. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  10143. if (edata) {
  10144. edata.DisposeModelRenderCache(this);
  10145. }
  10146. return true;
  10147. };
  10148. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  10149. get: function () {
  10150. return this._refCounter <= 0;
  10151. },
  10152. enumerable: true,
  10153. configurable: true
  10154. });
  10155. ModelRenderCache.prototype.addRef = function () {
  10156. return ++this._refCounter;
  10157. };
  10158. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  10159. get: function () {
  10160. return this._modelKey;
  10161. },
  10162. enumerable: true,
  10163. configurable: true
  10164. });
  10165. ModelRenderCache.prototype.updateModelRenderCache = function (prim) {
  10166. return false;
  10167. };
  10168. /**
  10169. * Render the model instances
  10170. * @param instanceInfo
  10171. * @param context
  10172. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  10173. */
  10174. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  10175. return true;
  10176. };
  10177. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  10178. for (var i = 0; i < this._partData.length; i++) {
  10179. if (this._partData[i]._partId === partId) {
  10180. return i;
  10181. }
  10182. }
  10183. return null;
  10184. };
  10185. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  10186. var i = this.getPartIndexFromId(partId);
  10187. if (i === null) {
  10188. return null;
  10189. }
  10190. var ci = this._partsClassInfo[i];
  10191. var categories = this._partData[i]._partUsedCategories;
  10192. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  10193. return res;
  10194. };
  10195. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  10196. var pd = this._partData[partIndex];
  10197. var offset = (pd._partDataStride / 4) * elementCount;
  10198. var pci = this._partsClassInfo[partIndex];
  10199. var self = this;
  10200. pci.fullContent.forEach(function (k, v) {
  10201. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  10202. switch (v.dataType) {
  10203. case 4 /* float */:
  10204. {
  10205. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  10206. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  10207. break;
  10208. }
  10209. case 0 /* Vector2 */:
  10210. {
  10211. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  10212. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  10213. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  10214. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  10215. break;
  10216. }
  10217. case 5 /* Color3 */:
  10218. case 1 /* Vector3 */:
  10219. {
  10220. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  10221. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  10222. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  10223. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  10224. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  10225. break;
  10226. }
  10227. case 6 /* Color4 */:
  10228. case 2 /* Vector4 */:
  10229. {
  10230. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  10231. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  10232. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  10233. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  10234. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  10235. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  10236. break;
  10237. }
  10238. default:
  10239. }
  10240. }
  10241. });
  10242. };
  10243. return ModelRenderCache;
  10244. }());
  10245. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  10246. // let i = this.getPartIndexFromId(partId);
  10247. // if (i === null) {
  10248. // return null;
  10249. // }
  10250. // let pci = this._partsClassInfo[i];
  10251. // pci.fullContent.forEach((k, v) => {
  10252. // if (uniforms.indexOf(v.attributeName) !== -1) {
  10253. // v.uniformLocation = effect.getUniform(v.attributeName);
  10254. // }
  10255. // });
  10256. //}
  10257. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  10258. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  10259. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  10260. BABYLON.ModelRenderCache = ModelRenderCache;
  10261. var ModelRenderCachePartData = (function () {
  10262. function ModelRenderCachePartData() {
  10263. }
  10264. return ModelRenderCachePartData;
  10265. }());
  10266. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  10267. })(BABYLON || (BABYLON = {}));
  10268. //# sourceMappingURL=babylon.modelRenderCache.js.map
  10269. var __extends = (this && this.__extends) || function (d, b) {
  10270. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10271. function __() { this.constructor = d; }
  10272. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  10273. };
  10274. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  10275. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  10276. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  10277. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  10278. return c > 3 && r && Object.defineProperty(target, key, r), r;
  10279. };
  10280. var BABYLON;
  10281. (function (BABYLON) {
  10282. var InstanceClassInfo = (function () {
  10283. function InstanceClassInfo(base) {
  10284. this._baseInfo = base;
  10285. this._nextOffset = new BABYLON.StringDictionary();
  10286. this._attributes = new Array();
  10287. }
  10288. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  10289. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  10290. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  10291. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  10292. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  10293. if (push) {
  10294. this._attributes.push(propInfo);
  10295. }
  10296. };
  10297. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  10298. var catInline = ";" + categories.join(";") + ";";
  10299. var res = new Array();
  10300. var curInfo = this;
  10301. while (curInfo) {
  10302. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  10303. var attrib = _a[_i];
  10304. // Only map if there's no category assigned to the instance data or if there's a category and it's in the given list
  10305. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  10306. var index = effect.getAttributeLocationByName(attrib.attributeName);
  10307. if (index === -1) {
  10308. throw new Error("Attribute " + attrib.attributeName + " was not found in Effect: " + effect.name + ". It's certainly no longer used in the Effect's Shaders");
  10309. }
  10310. var iai = new BABYLON.InstancingAttributeInfo();
  10311. iai.index = index;
  10312. iai.attributeSize = attrib.size / 4; // attrib.size is in byte and we need to store in "component" (i.e float is 1, vec3 is 3)
  10313. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  10314. iai.attributeName = attrib.attributeName;
  10315. res.push(iai);
  10316. }
  10317. }
  10318. curInfo = curInfo._baseInfo;
  10319. }
  10320. return res;
  10321. };
  10322. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  10323. var res = new Array();
  10324. var curInfo = this;
  10325. while (curInfo) {
  10326. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  10327. var attrib = _a[_i];
  10328. // Only map if there's no category assigned to the instance data or if there's a category and it's in the given list
  10329. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  10330. res.push(attrib.attributeName);
  10331. }
  10332. }
  10333. curInfo = curInfo._baseInfo;
  10334. }
  10335. return res;
  10336. };
  10337. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  10338. var curOffset = 0;
  10339. var curBase = this._baseInfo;
  10340. while (curBase) {
  10341. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  10342. curBase = curBase._baseInfo;
  10343. }
  10344. return curOffset;
  10345. };
  10346. return InstanceClassInfo;
  10347. }());
  10348. BABYLON.InstanceClassInfo = InstanceClassInfo;
  10349. var InstancePropInfo = (function () {
  10350. function InstancePropInfo() {
  10351. this.attributeName = null;
  10352. this.category = null;
  10353. this.size = null;
  10354. this.instanceOffset = new BABYLON.StringDictionary();
  10355. this.dataType = 0;
  10356. this.curCategory = "";
  10357. this.curCategoryOffset = 0;
  10358. }
  10359. InstancePropInfo.prototype.setSize = function (val) {
  10360. if (val instanceof BABYLON.Vector2) {
  10361. this.size = 8;
  10362. this.dataType = 0 /* Vector2 */;
  10363. return;
  10364. }
  10365. if (val instanceof BABYLON.Vector3) {
  10366. this.size = 12;
  10367. this.dataType = 1 /* Vector3 */;
  10368. return;
  10369. }
  10370. if (val instanceof BABYLON.Vector4) {
  10371. this.size = 16;
  10372. this.dataType = 2 /* Vector4 */;
  10373. return;
  10374. }
  10375. if (val instanceof BABYLON.Matrix) {
  10376. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  10377. }
  10378. if (typeof (val) === "number") {
  10379. this.size = 4;
  10380. this.dataType = 4 /* float */;
  10381. return;
  10382. }
  10383. if (val instanceof BABYLON.Color3) {
  10384. this.size = 12;
  10385. this.dataType = 5 /* Color3 */;
  10386. return;
  10387. }
  10388. if (val instanceof BABYLON.Color4) {
  10389. this.size = 16;
  10390. this.dataType = 6 /* Color4 */;
  10391. return;
  10392. }
  10393. if (val instanceof BABYLON.Size) {
  10394. this.size = 8;
  10395. this.dataType = 7 /* Size */;
  10396. return;
  10397. }
  10398. return;
  10399. };
  10400. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  10401. switch (this.dataType) {
  10402. case 0 /* Vector2 */:
  10403. {
  10404. var v = val;
  10405. array[offset + 0] = v.x;
  10406. array[offset + 1] = v.y;
  10407. break;
  10408. }
  10409. case 1 /* Vector3 */:
  10410. {
  10411. var v = val;
  10412. array[offset + 0] = v.x;
  10413. array[offset + 1] = v.y;
  10414. array[offset + 2] = v.z;
  10415. break;
  10416. }
  10417. case 2 /* Vector4 */:
  10418. {
  10419. var v = val;
  10420. array[offset + 0] = v.x;
  10421. array[offset + 1] = v.y;
  10422. array[offset + 2] = v.z;
  10423. array[offset + 3] = v.w;
  10424. break;
  10425. }
  10426. case 5 /* Color3 */:
  10427. {
  10428. var v = val;
  10429. array[offset + 0] = v.r;
  10430. array[offset + 1] = v.g;
  10431. array[offset + 2] = v.b;
  10432. break;
  10433. }
  10434. case 6 /* Color4 */:
  10435. {
  10436. var v = val;
  10437. array[offset + 0] = v.r;
  10438. array[offset + 1] = v.g;
  10439. array[offset + 2] = v.b;
  10440. array[offset + 3] = v.a;
  10441. break;
  10442. }
  10443. case 4 /* float */:
  10444. {
  10445. var v = val;
  10446. array[offset] = v;
  10447. break;
  10448. }
  10449. case 3 /* Matrix */:
  10450. {
  10451. var v = val;
  10452. for (var i = 0; i < 16; i++) {
  10453. array[offset + i] = v.m[i];
  10454. }
  10455. break;
  10456. }
  10457. case 7 /* Size */:
  10458. {
  10459. var s = val;
  10460. array[offset + 0] = s.width;
  10461. array[offset + 1] = s.height;
  10462. break;
  10463. }
  10464. }
  10465. };
  10466. return InstancePropInfo;
  10467. }());
  10468. BABYLON.InstancePropInfo = InstancePropInfo;
  10469. function instanceData(category, shaderAttributeName) {
  10470. return function (target, propName, descriptor) {
  10471. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  10472. var node = dic.getLevelOf(target);
  10473. var instanceDataName = propName;
  10474. shaderAttributeName = shaderAttributeName || instanceDataName;
  10475. var info = node.levelContent.get(instanceDataName);
  10476. if (info) {
  10477. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  10478. }
  10479. info = new InstancePropInfo();
  10480. info.attributeName = shaderAttributeName;
  10481. info.category = category || null;
  10482. if (info.category) {
  10483. info.delimitedCategory = ";" + info.category + ";";
  10484. }
  10485. node.levelContent.add(instanceDataName, info);
  10486. descriptor.get = function () {
  10487. return null;
  10488. };
  10489. descriptor.set = function (val) {
  10490. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  10491. // Quit if it's the case, otherwise we could overwrite data somewhere...
  10492. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  10493. return;
  10494. }
  10495. var catOffset;
  10496. if (info.curCategory === InstanceClassInfo._CurCategories) {
  10497. catOffset = info.curCategoryOffset;
  10498. }
  10499. else {
  10500. if (!info.size) {
  10501. info.setSize(val);
  10502. node.classContent.mapProperty(info, true);
  10503. }
  10504. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  10505. node.classContent.mapProperty(info, false);
  10506. }
  10507. catOffset = info.instanceOffset.get(InstanceClassInfo._CurCategories);
  10508. info.curCategory = InstanceClassInfo._CurCategories;
  10509. info.curCategoryOffset = catOffset;
  10510. }
  10511. var obj = this;
  10512. if (obj.dataBuffer && obj.dataElements) {
  10513. var offset = obj.dataElements[obj.curElement].offset + catOffset;
  10514. info.writeData(obj.dataBuffer.buffer, offset, val);
  10515. }
  10516. };
  10517. };
  10518. }
  10519. BABYLON.instanceData = instanceData;
  10520. var InstanceDataBase = (function () {
  10521. function InstanceDataBase(partId, dataElementCount) {
  10522. this.id = partId;
  10523. this.curElement = 0;
  10524. this._dataElementCount = dataElementCount;
  10525. this.renderMode = 0;
  10526. this.arrayLengthChanged = false;
  10527. }
  10528. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  10529. get: function () {
  10530. return null;
  10531. },
  10532. set: function (value) {
  10533. },
  10534. enumerable: true,
  10535. configurable: true
  10536. });
  10537. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  10538. get: function () {
  10539. return null;
  10540. },
  10541. set: function (value) {
  10542. },
  10543. enumerable: true,
  10544. configurable: true
  10545. });
  10546. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  10547. get: function () {
  10548. return null;
  10549. },
  10550. set: function (value) {
  10551. },
  10552. enumerable: true,
  10553. configurable: true
  10554. });
  10555. Object.defineProperty(InstanceDataBase.prototype, "renderingInfo", {
  10556. // The vector3 is: rendering width, height and 1 if the primitive must be aligned to pixel or 0 otherwise
  10557. get: function () {
  10558. return null;
  10559. },
  10560. set: function (val) {
  10561. },
  10562. enumerable: true,
  10563. configurable: true
  10564. });
  10565. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  10566. get: function () {
  10567. return null;
  10568. },
  10569. set: function (value) {
  10570. },
  10571. enumerable: true,
  10572. configurable: true
  10573. });
  10574. InstanceDataBase.prototype.getClassTreeInfo = function () {
  10575. if (!this.typeInfo) {
  10576. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  10577. }
  10578. return this.typeInfo;
  10579. };
  10580. InstanceDataBase.prototype.allocElements = function () {
  10581. if (!this.dataBuffer || this.dataElements) {
  10582. return;
  10583. }
  10584. var res = new Array(this.dataElementCount);
  10585. for (var i = 0; i < this.dataElementCount; i++) {
  10586. res[i] = this.dataBuffer.allocElement();
  10587. }
  10588. this.dataElements = res;
  10589. };
  10590. InstanceDataBase.prototype.freeElements = function () {
  10591. if (!this.dataElements) {
  10592. return;
  10593. }
  10594. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  10595. var ei = _a[_i];
  10596. this.dataBuffer.freeElement(ei);
  10597. }
  10598. this.dataElements = null;
  10599. };
  10600. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  10601. get: function () {
  10602. return this._dataElementCount;
  10603. },
  10604. set: function (value) {
  10605. if (value === this._dataElementCount) {
  10606. return;
  10607. }
  10608. this.arrayLengthChanged = true;
  10609. this.freeElements();
  10610. this._dataElementCount = value;
  10611. this.allocElements();
  10612. },
  10613. enumerable: true,
  10614. configurable: true
  10615. });
  10616. return InstanceDataBase;
  10617. }());
  10618. __decorate([
  10619. instanceData()
  10620. ], InstanceDataBase.prototype, "zBias", null);
  10621. __decorate([
  10622. instanceData()
  10623. ], InstanceDataBase.prototype, "transformX", null);
  10624. __decorate([
  10625. instanceData()
  10626. ], InstanceDataBase.prototype, "transformY", null);
  10627. __decorate([
  10628. instanceData()
  10629. ], InstanceDataBase.prototype, "renderingInfo", null);
  10630. __decorate([
  10631. instanceData()
  10632. ], InstanceDataBase.prototype, "opacity", null);
  10633. BABYLON.InstanceDataBase = InstanceDataBase;
  10634. var RenderablePrim2D = RenderablePrim2D_1 = (function (_super) {
  10635. __extends(RenderablePrim2D, _super);
  10636. function RenderablePrim2D(settings) {
  10637. var _this = _super.call(this, settings) || this;
  10638. _this._transparentPrimitiveInfo = null;
  10639. return _this;
  10640. }
  10641. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  10642. get: function () {
  10643. return this._useTextureAlpha() || this._isPrimAlphaTest();
  10644. },
  10645. enumerable: true,
  10646. configurable: true
  10647. });
  10648. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  10649. get: function () {
  10650. return (this.actualOpacity < 1) || this._shouldUseAlphaFromTexture() || this._isPrimTransparent();
  10651. },
  10652. enumerable: true,
  10653. configurable: true
  10654. });
  10655. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  10656. get: function () {
  10657. return this._renderMode;
  10658. },
  10659. enumerable: true,
  10660. configurable: true
  10661. });
  10662. /**
  10663. * Dispose the primitive and its resources, remove it from its parent
  10664. */
  10665. RenderablePrim2D.prototype.dispose = function () {
  10666. if (!_super.prototype.dispose.call(this)) {
  10667. return false;
  10668. }
  10669. if (this.renderGroup) {
  10670. this.renderGroup._setCacheGroupDirty();
  10671. }
  10672. if (this._transparentPrimitiveInfo) {
  10673. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  10674. this._transparentPrimitiveInfo = null;
  10675. }
  10676. if (this._instanceDataParts) {
  10677. this._cleanupInstanceDataParts();
  10678. }
  10679. if (this._modelRenderCache) {
  10680. this._modelRenderCache.dispose();
  10681. this._modelRenderCache = null;
  10682. }
  10683. if (this._instanceDataParts) {
  10684. this._instanceDataParts.forEach(function (p) {
  10685. p.freeElements();
  10686. });
  10687. this._instanceDataParts = null;
  10688. }
  10689. return true;
  10690. };
  10691. RenderablePrim2D.prototype._cleanupInstanceDataParts = function () {
  10692. var gii = null;
  10693. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  10694. var part = _a[_i];
  10695. part.freeElements();
  10696. gii = part.groupInstanceInfo;
  10697. }
  10698. if (gii) {
  10699. var usedCount = 0;
  10700. if (gii.hasOpaqueData) {
  10701. var od = gii.opaqueData[0];
  10702. usedCount += od._partData.usedElementCount;
  10703. gii.opaqueDirty = true;
  10704. }
  10705. if (gii.hasAlphaTestData) {
  10706. var atd = gii.alphaTestData[0];
  10707. usedCount += atd._partData.usedElementCount;
  10708. gii.alphaTestDirty = true;
  10709. }
  10710. if (gii.hasTransparentData) {
  10711. var td = gii.transparentData[0];
  10712. usedCount += td._partData.usedElementCount;
  10713. gii.transparentDirty = true;
  10714. }
  10715. if (usedCount === 0 && gii.modelRenderCache != null) {
  10716. this.renderGroup._renderableData._renderGroupInstancesInfo.remove(gii.modelRenderCache.modelKey);
  10717. gii.dispose();
  10718. }
  10719. if (this._modelRenderCache) {
  10720. this._modelRenderCache.dispose();
  10721. this._modelRenderCache = null;
  10722. }
  10723. }
  10724. this._instanceDataParts = null;
  10725. };
  10726. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  10727. _super.prototype._prepareRenderPre.call(this, context);
  10728. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  10729. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._instanceDataParts) {
  10730. this._cleanupInstanceDataParts();
  10731. }
  10732. // Need to create the model?
  10733. var setupModelRenderCache = false;
  10734. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  10735. setupModelRenderCache = this._createModelRenderCache();
  10736. }
  10737. var gii = null;
  10738. var newInstance = false;
  10739. // Need to create the instance data parts?
  10740. if (!this._instanceDataParts) {
  10741. // Yes, flag it for later, more processing will have to be done
  10742. newInstance = true;
  10743. gii = this._createModelDataParts();
  10744. }
  10745. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  10746. if (setupModelRenderCache) {
  10747. this.setupModelRenderCache(this._modelRenderCache);
  10748. }
  10749. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelUpdate)) {
  10750. if (this._modelRenderCache.updateModelRenderCache(this)) {
  10751. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelUpdate);
  10752. }
  10753. }
  10754. // At this stage we have everything correctly initialized, ModelRenderCache is setup, Model Instance data are good too, they have allocated elements in the Instanced DynamicFloatArray.
  10755. // The last thing to do is check if the instanced related data must be updated because a InstanceLevel property had changed or the primitive visibility changed.
  10756. if (this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagNeedRefresh) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep) || this._mustUpdateInstance()) {
  10757. this._updateInstanceDataParts(gii);
  10758. }
  10759. };
  10760. RenderablePrim2D.prototype._createModelRenderCache = function () {
  10761. var _this = this;
  10762. var setupModelRenderCache = false;
  10763. if (this._modelRenderCache) {
  10764. this._modelRenderCache.dispose();
  10765. }
  10766. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  10767. var mrc = _this.createModelRenderCache(key);
  10768. setupModelRenderCache = true;
  10769. return mrc;
  10770. });
  10771. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  10772. // if this is still false it means the MRC already exists, so we add a reference to it
  10773. if (!setupModelRenderCache) {
  10774. this._modelRenderCache.addRef();
  10775. }
  10776. return setupModelRenderCache;
  10777. };
  10778. RenderablePrim2D.prototype._createModelDataParts = function () {
  10779. var _this = this;
  10780. // Create the instance data parts of the primitive and store them
  10781. var parts = this.createInstanceDataParts();
  10782. this._instanceDataParts = parts;
  10783. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  10784. if (!this._modelRenderCache._partData) {
  10785. this._setupModelRenderCache(parts);
  10786. }
  10787. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  10788. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  10789. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  10790. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  10791. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  10792. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  10793. var part = _this._instanceDataParts[j];
  10794. res.partIndexFromId.add(part.id.toString(), j);
  10795. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  10796. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  10797. }
  10798. return res;
  10799. });
  10800. // Get the GroupInfoDataPart corresponding to the render category of the part
  10801. var rm = 0;
  10802. var gipd = null;
  10803. if (this.isTransparent) {
  10804. gipd = gii.transparentData;
  10805. rm = BABYLON.Render2DContext.RenderModeTransparent;
  10806. }
  10807. else if (this.isAlphaTest) {
  10808. gipd = gii.alphaTestData;
  10809. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  10810. }
  10811. else {
  10812. gipd = gii.opaqueData;
  10813. rm = BABYLON.Render2DContext.RenderModeOpaque;
  10814. }
  10815. // For each instance data part of the primitive, allocate the instanced element it needs for render
  10816. for (var i = 0; i < parts.length; i++) {
  10817. var part = parts[i];
  10818. part.dataBuffer = gipd[i]._partData;
  10819. part.allocElements();
  10820. part.renderMode = rm;
  10821. part.groupInstanceInfo = gii;
  10822. }
  10823. return gii;
  10824. };
  10825. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  10826. var ctiArray = new Array();
  10827. this._modelRenderCache._partData = new Array();
  10828. for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
  10829. var dataPart = parts_1[_i];
  10830. var pd = new BABYLON.ModelRenderCachePartData();
  10831. this._modelRenderCache._partData.push(pd);
  10832. var cat = this.getUsedShaderCategories(dataPart);
  10833. var cti = dataPart.getClassTreeInfo();
  10834. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  10835. var curVisible = this.isVisible;
  10836. this.isVisible = true;
  10837. // We manually trigger refreshInstanceData for the only sake of evaluating each instance property size and offset in the instance data, this can only be made at runtime. Once it's done we have all the information to create the instance data buffer.
  10838. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  10839. var joinCat = ";" + cat.join(";") + ";";
  10840. pd._partJoinedUsedCategories = joinCat;
  10841. InstanceClassInfo._CurCategories = joinCat;
  10842. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  10843. if (!this.refreshInstanceDataPart(dataPart)) {
  10844. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  10845. }
  10846. this.afterRefreshForLayoutConstruction(dataPart, obj);
  10847. this.isVisible = curVisible;
  10848. var size = 0;
  10849. cti.fullContent.forEach(function (k, v) {
  10850. if (!v.category || cat.indexOf(v.category) !== -1) {
  10851. if (v.attributeName === "zBias") {
  10852. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  10853. }
  10854. if (!v.size) {
  10855. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  10856. }
  10857. else {
  10858. size += v.size;
  10859. }
  10860. }
  10861. });
  10862. pd._partDataStride = size;
  10863. pd._partUsedCategories = cat;
  10864. pd._partId = dataPart.id;
  10865. ctiArray.push(cti);
  10866. }
  10867. this._modelRenderCache._partsClassInfo = ctiArray;
  10868. };
  10869. RenderablePrim2D.prototype.onZOrderChanged = function () {
  10870. if (this.isTransparent && this._transparentPrimitiveInfo) {
  10871. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  10872. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  10873. // Flag the transparentData dirty has will have to sort it again
  10874. gii.transparentOrderDirty = true;
  10875. }
  10876. };
  10877. RenderablePrim2D.prototype._mustUpdateInstance = function () {
  10878. return false;
  10879. };
  10880. RenderablePrim2D.prototype._useTextureAlpha = function () {
  10881. return false;
  10882. };
  10883. RenderablePrim2D.prototype._shouldUseAlphaFromTexture = function () {
  10884. return false;
  10885. };
  10886. RenderablePrim2D.prototype._isPrimAlphaTest = function () {
  10887. return false;
  10888. };
  10889. RenderablePrim2D.prototype._isPrimTransparent = function () {
  10890. return false;
  10891. };
  10892. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  10893. // Fetch the GroupInstanceInfo if we don't already have it
  10894. var rd = this.renderGroup._renderableData;
  10895. if (!gii) {
  10896. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  10897. }
  10898. var isTransparent = this.isTransparent;
  10899. var isAlphaTest = this.isAlphaTest;
  10900. var wereTransparent = false;
  10901. // Check a render mode change
  10902. var rmChanged = false;
  10903. if (this._instanceDataParts.length > 0) {
  10904. var firstPart = this._instanceDataParts[0];
  10905. var partRM = firstPart.renderMode;
  10906. var curRM = this.renderMode;
  10907. if (partRM !== curRM) {
  10908. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  10909. rmChanged = true;
  10910. var gipd = void 0;
  10911. switch (curRM) {
  10912. case BABYLON.Render2DContext.RenderModeTransparent:
  10913. gipd = gii.transparentData;
  10914. break;
  10915. case BABYLON.Render2DContext.RenderModeAlphaTest:
  10916. gipd = gii.alphaTestData;
  10917. break;
  10918. default:
  10919. gipd = gii.opaqueData;
  10920. }
  10921. for (var i = 0; i < this._instanceDataParts.length; i++) {
  10922. var part = this._instanceDataParts[i];
  10923. part.freeElements();
  10924. part.dataBuffer = gipd[i]._partData;
  10925. part.renderMode = curRM;
  10926. }
  10927. }
  10928. }
  10929. // Handle changes related to ZOffset
  10930. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  10931. if (isTransparent || wereTransparent) {
  10932. // Handle visibility change, which is also triggered when the primitive just got created
  10933. if (visChanged || rmChanged) {
  10934. if (this.isVisible && !wereTransparent) {
  10935. if (!this._transparentPrimitiveInfo) {
  10936. // Add the primitive to the list of transparent ones in the group that render is
  10937. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  10938. }
  10939. }
  10940. else {
  10941. if (this._transparentPrimitiveInfo) {
  10942. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  10943. this._transparentPrimitiveInfo = null;
  10944. }
  10945. }
  10946. gii.transparentOrderDirty = true;
  10947. }
  10948. }
  10949. var rebuildTrans = false;
  10950. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  10951. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  10952. var part = _a[_i];
  10953. var justAllocated = false;
  10954. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  10955. if (!part.dataElements && (visChanged || rmChanged || this.isVisible)) {
  10956. part.allocElements();
  10957. justAllocated = true;
  10958. }
  10959. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  10960. // Will return false if the instance should not be rendered (not visible or other any reasons)
  10961. part.arrayLengthChanged = false;
  10962. if (!this.refreshInstanceDataPart(part)) {
  10963. // Free the data element
  10964. if (part.dataElements) {
  10965. part.freeElements();
  10966. }
  10967. // The refresh couldn't succeed, push the primitive to be dirty again for the next render
  10968. if (this.isVisible) {
  10969. rd._primNewDirtyList.push(this);
  10970. }
  10971. }
  10972. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  10973. }
  10974. this._instanceDirtyFlags = 0;
  10975. // Make the appropriate data dirty
  10976. if (isTransparent) {
  10977. gii.transparentDirty = true;
  10978. if (rebuildTrans) {
  10979. rd._transparentListChanged = true;
  10980. }
  10981. }
  10982. else if (isAlphaTest) {
  10983. gii.alphaTestDirty = true;
  10984. }
  10985. else {
  10986. gii.opaqueDirty = true;
  10987. }
  10988. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  10989. };
  10990. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  10991. var minOff = BABYLON.Prim2DBase._bigInt;
  10992. var maxOff = 0;
  10993. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  10994. var part = _a[_i];
  10995. if (part && part.dataElements) {
  10996. part.dataBuffer.pack();
  10997. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  10998. var el = _c[_b];
  10999. minOff = Math.min(minOff, el.offset);
  11000. maxOff = Math.max(maxOff, el.offset);
  11001. }
  11002. ts.startDataIndex = Math.min(ts.startDataIndex, minOff / part.dataBuffer.stride);
  11003. ts.endDataIndex = Math.max(ts.endDataIndex, (maxOff / part.dataBuffer.stride) + 1); // +1 for exclusive
  11004. }
  11005. }
  11006. };
  11007. // This internal method is mainly used for transparency processing
  11008. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  11009. var length = this._instanceDataParts.length;
  11010. for (var i = 0; i < length; i++) {
  11011. var part = this._instanceDataParts[i];
  11012. if (part) {
  11013. var stride = part.dataBuffer.stride;
  11014. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  11015. // check if it's the last in the DFA
  11016. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  11017. return null;
  11018. }
  11019. // Return the Z of the next primitive that lies in the DFA
  11020. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  11021. }
  11022. }
  11023. return null;
  11024. };
  11025. // This internal method is mainly used for transparency processing
  11026. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  11027. var length = this._instanceDataParts.length;
  11028. for (var i = 0; i < length; i++) {
  11029. var part = this._instanceDataParts[i];
  11030. if (part) {
  11031. var stride = part.dataBuffer.stride;
  11032. var firstElementOffset = part.dataElements[0].offset;
  11033. // check if it's the first in the DFA
  11034. if (firstElementOffset === 0) {
  11035. return null;
  11036. }
  11037. // Return the Z of the previous primitive that lies in the DFA
  11038. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  11039. }
  11040. }
  11041. return null;
  11042. };
  11043. /**
  11044. * Get the info for a given effect based on the dataPart metadata
  11045. * @param dataPartId partId in part list to get the info
  11046. * @param vertexBufferAttributes vertex buffer attributes to manually add
  11047. * @param uniforms uniforms to manually add
  11048. * @param useInstanced specified if Instanced Array should be used, if null the engine caps will be used (so true if WebGL supports it, false otherwise), but you have the possibility to override the engine capability. However, if you manually set true but the engine does not support Instanced Array, this method will return null
  11049. */
  11050. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, uniforms, useInstanced) {
  11051. if (uniforms === void 0) { uniforms = null; }
  11052. if (useInstanced === void 0) { useInstanced = null; }
  11053. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  11054. if (!dataPart) {
  11055. return null;
  11056. }
  11057. var instancedArray = this.owner.supportInstancedArray;
  11058. if (useInstanced != null) {
  11059. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  11060. if (useInstanced && instancedArray === false) {
  11061. return null;
  11062. }
  11063. // Use the caller's setting
  11064. instancedArray = useInstanced;
  11065. }
  11066. var cti = dataPart.getClassTreeInfo();
  11067. var categories = this.getUsedShaderCategories(dataPart);
  11068. var att = cti.classContent.getShaderAttributes(categories);
  11069. var defines = "";
  11070. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  11071. if (instancedArray) {
  11072. defines += "#define Instanced\n";
  11073. }
  11074. return {
  11075. attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes,
  11076. uniforms: instancedArray ? (uniforms != null ? uniforms : []) : ((uniforms != null) ? att.concat(uniforms) : (att != null ? att : [])),
  11077. defines: defines
  11078. };
  11079. };
  11080. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  11081. get: function () {
  11082. return this._modelRenderCache;
  11083. },
  11084. enumerable: true,
  11085. configurable: true
  11086. });
  11087. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  11088. return null;
  11089. };
  11090. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  11091. };
  11092. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  11093. return null;
  11094. };
  11095. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  11096. return [];
  11097. };
  11098. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  11099. };
  11100. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  11101. };
  11102. RenderablePrim2D.prototype.applyActualScaleOnTransform = function () {
  11103. return true;
  11104. };
  11105. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  11106. if (!this.isVisible) {
  11107. return false;
  11108. }
  11109. part.isVisible = this.isVisible;
  11110. // Which means, if there's only one data element, we're update it from this method, otherwise it is the responsibility of the derived class to call updateInstanceDataPart as many times as needed, properly (look at Text2D's implementation for more information)
  11111. if (part.dataElementCount === 1) {
  11112. part.curElement = 0;
  11113. this.updateInstanceDataPart(part);
  11114. }
  11115. return true;
  11116. };
  11117. /**
  11118. * Update the instanceDataBase level properties of a part
  11119. * @param part the part to update
  11120. * @param positionOffset to use in multi part per primitive (e.g. the Text2D has N parts for N letter to display), this give the offset to apply (e.g. the position of the letter from the bottom/left corner of the text).
  11121. */
  11122. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  11123. if (positionOffset === void 0) { positionOffset = null; }
  11124. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform); // Compute the transformation into the renderGroup's space
  11125. var scl = RenderablePrim2D_1._s;
  11126. var rot = RenderablePrim2D_1._r;
  11127. var trn = RenderablePrim2D_1._t;
  11128. t.decompose(scl, rot, trn);
  11129. var pas = this.actualScale;
  11130. var canvasScale = this.owner._canvasLevelScale;
  11131. scl.x = pas.x * canvasScale.x * this._postScale.x;
  11132. scl.y = pas.y * canvasScale.y * this._postScale.y;
  11133. scl.z = 1;
  11134. t = BABYLON.Matrix.Compose(this.applyActualScaleOnTransform() ? scl : RenderablePrim2D_1._iV3, rot, trn);
  11135. var size = this.renderGroup.viewportSize;
  11136. var zBias = this.actualZOffset;
  11137. var offX = 0;
  11138. var offY = 0;
  11139. // If there's an offset, apply the global transformation matrix on it to get a global offset
  11140. if (positionOffset) {
  11141. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  11142. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  11143. }
  11144. // Have to convert the coordinates to clip space which is ranged between [-1;1] on X and Y axis, with 0,0 being the left/bottom corner
  11145. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  11146. // So for X:
  11147. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  11148. // - tx.w = (value * 2 / width) - 1: w stores the translation in renderGroup coordinates so (value * 2 / width) to switch to a clip space translation value. - 1 is to offset the overall [0;2] to [-1;1].
  11149. // At last we don't forget to apply the actualScale of the Render Group to tx[0] and ty[1] to propagate scaling correctly
  11150. var w = size.width;
  11151. var h = size.height;
  11152. var invZBias = 1 / zBias;
  11153. var tx = new BABYLON.Vector4(t.m[0] * 2 / w, t.m[4] * 2 / w, 0, ((t.m[12] + offX) * 2 / w) - 1);
  11154. var ty = new BABYLON.Vector4(t.m[1] * 2 / h, t.m[5] * 2 / h, 0, ((t.m[13] + offY) * 2 / h) - 1);
  11155. part.renderingInfo = new BABYLON.Vector3(w, h, this.alignToPixel ? 1 : 0);
  11156. part.transformX = tx;
  11157. part.transformY = ty;
  11158. part.opacity = this.actualOpacity;
  11159. // Stores zBias and it's inverse value because that's needed to compute the clip space W coordinate (which is 1/Z, so 1/zBias)
  11160. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  11161. };
  11162. RenderablePrim2D.prototype._updateRenderMode = function () {
  11163. if (this.isTransparent) {
  11164. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  11165. }
  11166. else if (this.isAlphaTest) {
  11167. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  11168. }
  11169. else {
  11170. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  11171. }
  11172. };
  11173. return RenderablePrim2D;
  11174. }(BABYLON.Prim2DBase));
  11175. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  11176. RenderablePrim2D._toz = BABYLON.Size.Zero();
  11177. RenderablePrim2D._uV = new BABYLON.Vector2(1, 1);
  11178. RenderablePrim2D._s = BABYLON.Vector3.Zero();
  11179. RenderablePrim2D._r = BABYLON.Quaternion.Identity();
  11180. RenderablePrim2D._t = BABYLON.Vector3.Zero();
  11181. RenderablePrim2D._iV3 = new BABYLON.Vector3(1, 1, 1); // Must stay identity vector3
  11182. __decorate([
  11183. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D_1.isAlphaTestProperty = pi; })
  11184. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  11185. __decorate([
  11186. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D_1.isTransparentProperty = pi; })
  11187. ], RenderablePrim2D.prototype, "isTransparent", null);
  11188. RenderablePrim2D = RenderablePrim2D_1 = __decorate([
  11189. BABYLON.className("RenderablePrim2D", "BABYLON")
  11190. ], RenderablePrim2D);
  11191. BABYLON.RenderablePrim2D = RenderablePrim2D;
  11192. var RenderablePrim2D_1;
  11193. })(BABYLON || (BABYLON = {}));
  11194. //# sourceMappingURL=babylon.renderablePrim2d.js.map
  11195. var __extends = (this && this.__extends) || function (d, b) {
  11196. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11197. function __() { this.constructor = d; }
  11198. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  11199. };
  11200. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  11201. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  11202. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  11203. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  11204. return c > 3 && r && Object.defineProperty(target, key, r), r;
  11205. };
  11206. var BABYLON;
  11207. (function (BABYLON) {
  11208. var Shape2D = Shape2D_1 = (function (_super) {
  11209. __extends(Shape2D, _super);
  11210. function Shape2D(settings) {
  11211. var _this = _super.call(this, settings) || this;
  11212. if (!settings) {
  11213. settings = {};
  11214. }
  11215. var borderBrush = null;
  11216. if (settings.border) {
  11217. if (typeof (settings.border) === "string") {
  11218. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  11219. }
  11220. else {
  11221. borderBrush = settings.border;
  11222. }
  11223. }
  11224. var fillBrush = null;
  11225. if (settings.fill) {
  11226. if (typeof (settings.fill) === "string") {
  11227. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  11228. }
  11229. else {
  11230. fillBrush = settings.fill;
  11231. }
  11232. }
  11233. _this._isTransparent = false;
  11234. _this._oldTransparent = false;
  11235. _this.border = borderBrush;
  11236. _this.fill = fillBrush;
  11237. _this._updateTransparencyStatus();
  11238. _this.borderThickness = settings.borderThickness;
  11239. return _this;
  11240. }
  11241. Object.defineProperty(Shape2D.prototype, "border", {
  11242. get: function () {
  11243. return this._border;
  11244. },
  11245. set: function (value) {
  11246. this._border = value;
  11247. this._updateTransparencyStatus();
  11248. },
  11249. enumerable: true,
  11250. configurable: true
  11251. });
  11252. Object.defineProperty(Shape2D.prototype, "fill", {
  11253. /**
  11254. * Get/set the brush to render the Fill part of the Primitive
  11255. */
  11256. get: function () {
  11257. return this._fill;
  11258. },
  11259. set: function (value) {
  11260. this._fill = value;
  11261. this._updateTransparencyStatus();
  11262. },
  11263. enumerable: true,
  11264. configurable: true
  11265. });
  11266. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  11267. get: function () {
  11268. return this._borderThickness;
  11269. },
  11270. set: function (value) {
  11271. this._borderThickness = value;
  11272. },
  11273. enumerable: true,
  11274. configurable: true
  11275. });
  11276. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  11277. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  11278. // Fill Part
  11279. if (dataPart.id === Shape2D_1.SHAPE2D_FILLPARTID) {
  11280. var fill = this.fill;
  11281. if (fill instanceof BABYLON.SolidColorBrush2D) {
  11282. cat.push(Shape2D_1.SHAPE2D_CATEGORY_FILLSOLID);
  11283. }
  11284. if (fill instanceof BABYLON.GradientColorBrush2D) {
  11285. cat.push(Shape2D_1.SHAPE2D_CATEGORY_FILLGRADIENT);
  11286. }
  11287. }
  11288. // Border Part
  11289. if (dataPart.id === Shape2D_1.SHAPE2D_BORDERPARTID) {
  11290. cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDER);
  11291. var border = this.border;
  11292. if (border instanceof BABYLON.SolidColorBrush2D) {
  11293. cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDERSOLID);
  11294. }
  11295. if (border instanceof BABYLON.GradientColorBrush2D) {
  11296. cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDERGRADIENT);
  11297. }
  11298. }
  11299. return cat;
  11300. };
  11301. Shape2D.prototype.applyActualScaleOnTransform = function () {
  11302. return false;
  11303. };
  11304. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  11305. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  11306. return false;
  11307. }
  11308. // Fill Part
  11309. if (part.id === Shape2D_1.SHAPE2D_FILLPARTID) {
  11310. var d = part;
  11311. if (this.fill) {
  11312. var fill = this.fill;
  11313. if (fill instanceof BABYLON.SolidColorBrush2D) {
  11314. d.fillSolidColor = fill.color;
  11315. }
  11316. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  11317. d.fillGradientColor1 = fill.color1;
  11318. d.fillGradientColor2 = fill.color2;
  11319. var t = BABYLON.Matrix.Compose(new BABYLON.Vector3(fill.scale, fill.scale, fill.scale), BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), fill.rotation), new BABYLON.Vector3(fill.translation.x, fill.translation.y, 0));
  11320. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  11321. d.fillGradientTY = ty;
  11322. }
  11323. }
  11324. }
  11325. else if (part.id === Shape2D_1.SHAPE2D_BORDERPARTID) {
  11326. var d = part;
  11327. if (this.border) {
  11328. d.borderThickness = this.borderThickness;
  11329. var border = this.border;
  11330. if (border instanceof BABYLON.SolidColorBrush2D) {
  11331. d.borderSolidColor = border.color;
  11332. }
  11333. else if (border instanceof BABYLON.GradientColorBrush2D) {
  11334. d.borderGradientColor1 = border.color1;
  11335. d.borderGradientColor2 = border.color2;
  11336. var t = BABYLON.Matrix.Compose(new BABYLON.Vector3(border.scale, border.scale, border.scale), BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), border.rotation), new BABYLON.Vector3(border.translation.x, border.translation.y, 0));
  11337. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  11338. d.borderGradientTY = ty;
  11339. }
  11340. }
  11341. }
  11342. return true;
  11343. };
  11344. Shape2D.prototype._updateTransparencyStatus = function () {
  11345. this._isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  11346. if (this._isTransparent !== this._oldTransparent) {
  11347. this._oldTransparent = this._isTransparent;
  11348. this._updateRenderMode();
  11349. }
  11350. };
  11351. Shape2D.prototype._mustUpdateInstance = function () {
  11352. var res = this._oldTransparent !== this._isTransparent;
  11353. if (res) {
  11354. this._updateRenderMode();
  11355. this._oldTransparent = this._isTransparent;
  11356. }
  11357. return res;
  11358. };
  11359. Shape2D.prototype._isPrimTransparent = function () {
  11360. return this._isTransparent;
  11361. };
  11362. return Shape2D;
  11363. }(BABYLON.RenderablePrim2D));
  11364. Shape2D.SHAPE2D_BORDERPARTID = 1;
  11365. Shape2D.SHAPE2D_FILLPARTID = 2;
  11366. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  11367. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  11368. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  11369. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  11370. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  11371. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  11372. __decorate([
  11373. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D_1.borderProperty = pi; }, true)
  11374. ], Shape2D.prototype, "border", null);
  11375. __decorate([
  11376. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D_1.fillProperty = pi; }, true)
  11377. ], Shape2D.prototype, "fill", null);
  11378. __decorate([
  11379. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D_1.borderThicknessProperty = pi; })
  11380. ], Shape2D.prototype, "borderThickness", null);
  11381. Shape2D = Shape2D_1 = __decorate([
  11382. BABYLON.className("Shape2D", "BABYLON")
  11383. ], Shape2D);
  11384. BABYLON.Shape2D = Shape2D;
  11385. var Shape2DInstanceData = (function (_super) {
  11386. __extends(Shape2DInstanceData, _super);
  11387. function Shape2DInstanceData() {
  11388. return _super.apply(this, arguments) || this;
  11389. }
  11390. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  11391. // FILL ATTRIBUTES
  11392. get: function () {
  11393. return null;
  11394. },
  11395. set: function (value) {
  11396. },
  11397. enumerable: true,
  11398. configurable: true
  11399. });
  11400. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  11401. get: function () {
  11402. return null;
  11403. },
  11404. set: function (value) {
  11405. },
  11406. enumerable: true,
  11407. configurable: true
  11408. });
  11409. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  11410. get: function () {
  11411. return null;
  11412. },
  11413. set: function (value) {
  11414. },
  11415. enumerable: true,
  11416. configurable: true
  11417. });
  11418. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  11419. get: function () {
  11420. return null;
  11421. },
  11422. set: function (value) {
  11423. },
  11424. enumerable: true,
  11425. configurable: true
  11426. });
  11427. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  11428. // BORDER ATTRIBUTES
  11429. get: function () {
  11430. return null;
  11431. },
  11432. set: function (value) {
  11433. },
  11434. enumerable: true,
  11435. configurable: true
  11436. });
  11437. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  11438. get: function () {
  11439. return null;
  11440. },
  11441. set: function (value) {
  11442. },
  11443. enumerable: true,
  11444. configurable: true
  11445. });
  11446. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  11447. get: function () {
  11448. return null;
  11449. },
  11450. set: function (value) {
  11451. },
  11452. enumerable: true,
  11453. configurable: true
  11454. });
  11455. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  11456. get: function () {
  11457. return null;
  11458. },
  11459. set: function (value) {
  11460. },
  11461. enumerable: true,
  11462. configurable: true
  11463. });
  11464. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  11465. get: function () {
  11466. return null;
  11467. },
  11468. set: function (value) {
  11469. },
  11470. enumerable: true,
  11471. configurable: true
  11472. });
  11473. return Shape2DInstanceData;
  11474. }(BABYLON.InstanceDataBase));
  11475. __decorate([
  11476. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  11477. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  11478. __decorate([
  11479. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  11480. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  11481. __decorate([
  11482. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  11483. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  11484. __decorate([
  11485. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  11486. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  11487. __decorate([
  11488. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  11489. ], Shape2DInstanceData.prototype, "borderThickness", null);
  11490. __decorate([
  11491. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  11492. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  11493. __decorate([
  11494. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  11495. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  11496. __decorate([
  11497. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  11498. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  11499. __decorate([
  11500. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  11501. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  11502. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  11503. var Shape2D_1;
  11504. })(BABYLON || (BABYLON = {}));
  11505. //# sourceMappingURL=babylon.shape2d.js.map
  11506. var __extends = (this && this.__extends) || function (d, b) {
  11507. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11508. function __() { this.constructor = d; }
  11509. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  11510. };
  11511. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  11512. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  11513. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  11514. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  11515. return c > 3 && r && Object.defineProperty(target, key, r), r;
  11516. };
  11517. var BABYLON;
  11518. (function (BABYLON) {
  11519. var Group2D = Group2D_1 = (function (_super) {
  11520. __extends(Group2D, _super);
  11521. /**
  11522. * Create an Logical or Renderable Group.
  11523. * @param settings a combination of settings, possible ones are
  11524. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  11525. * - children: an array of direct children
  11526. * - id a text identifier, for information purpose
  11527. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  11528. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  11529. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  11530. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  11531. * - trackNode: if you want the ScreenSpaceCanvas to track the position of a given Scene Node, use this setting to specify the Node to track
  11532. * - trackNodeOffset: if you use trackNode you may want to specify a 3D Offset to apply to shift the Canvas
  11533. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  11534. * - zOrder: override the zOrder with the specified value
  11535. * - origin: define the normalized origin point location, default [0.5;0.5]
  11536. * - size: the size of the group. Alternatively the width and height properties can be set. If null the size will be computed from its content, default is null.
  11537. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  11538. * - layoutEngine: either an instance of a layout engine based class (StackPanel.Vertical, StackPanel.Horizontal) or a string ('canvas' for Canvas layout, 'StackPanel' or 'HorizontalStackPanel' for horizontal Stack Panel layout, 'VerticalStackPanel' for vertical Stack Panel layout).
  11539. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  11540. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  11541. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  11542. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  11543. * - levelCollision: this primitive is an actor of the Collision Manager and only this level will be used for collision (i.e. not the children). Use deepCollision if you want collision detection on the primitives and its children.
  11544. * - deepCollision: this primitive is an actor of the Collision Manager, this level AND ALSO its children will be used for collision (note: you don't need to set the children as level/deepCollision).
  11545. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  11546. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11547. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11548. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11549. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11550. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  11551. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  11552. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  11553. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  11554. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11555. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11556. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11557. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11558. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  11559. */
  11560. function Group2D(settings) {
  11561. var _this;
  11562. if (settings == null) {
  11563. settings = {};
  11564. }
  11565. if (settings.origin == null) {
  11566. settings.origin = new BABYLON.Vector2(0, 0);
  11567. }
  11568. _this = _super.call(this, settings) || this;
  11569. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  11570. _this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  11571. _this._trackedNodeOffset = (settings.trackNodeOffset == null) ? null : settings.trackNodeOffset;
  11572. if (_this._trackedNode && _this.owner) {
  11573. _this.owner._registerTrackedNode(_this);
  11574. }
  11575. _this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D_1.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  11576. var rd = _this._renderableData;
  11577. if (rd) {
  11578. rd._noResizeOnScale = (_this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  11579. }
  11580. _this.size = size;
  11581. _this._viewportPosition = BABYLON.Vector2.Zero();
  11582. _this._viewportSize = BABYLON.Size.Zero();
  11583. return _this;
  11584. }
  11585. Group2D._createCachedCanvasGroup = function (owner) {
  11586. var g = new Group2D_1({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true, isPickable: false, dontInheritParentScale: true });
  11587. return g;
  11588. };
  11589. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  11590. this._bindCacheTarget();
  11591. if (vertexData) {
  11592. var uv = vertexData.uvs;
  11593. var nodeuv = this._renderableData._cacheNodeUVs;
  11594. for (var i = 0; i < 4; i++) {
  11595. uv[i * 2 + 0] = nodeuv[i].x;
  11596. uv[i * 2 + 1] = nodeuv[i].y;
  11597. }
  11598. }
  11599. if (material) {
  11600. material.diffuseTexture = this._renderableData._cacheTexture;
  11601. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  11602. }
  11603. this._renderableData._cacheTexture.hasAlpha = true;
  11604. this._unbindCacheTarget();
  11605. };
  11606. Object.defineProperty(Group2D.prototype, "cachedRect", {
  11607. /**
  11608. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  11609. * If the `noWorldSpaceNode` options was used at the creation of a WorldSpaceCanvas, the rendering of the canvas must be made by the caller, so typically you want to bind the cacheTexture property to some material/mesh and you MUST use the Group2D.cachedUVs property to get the UV coordinates to use for your quad that will display the Canvas and NOT the PackedRect.UVs property which are incorrect because the allocated surface may be bigger (due to over-provisioning or shrinking without deallocating) than what the Group is actually using.
  11610. */
  11611. get: function () {
  11612. if (!this._renderableData) {
  11613. return null;
  11614. }
  11615. return this._renderableData._cacheNode;
  11616. },
  11617. enumerable: true,
  11618. configurable: true
  11619. });
  11620. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  11621. /**
  11622. * The UVs into the MapTexture that map the cached group
  11623. */
  11624. get: function () {
  11625. if (!this._renderableData) {
  11626. return null;
  11627. }
  11628. return this._renderableData._cacheNodeUVs;
  11629. },
  11630. enumerable: true,
  11631. configurable: true
  11632. });
  11633. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  11634. get: function () {
  11635. if (!this._renderableData) {
  11636. return null;
  11637. }
  11638. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  11639. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  11640. }
  11641. return this._renderableData._cacheNodeUVsChangedObservable;
  11642. },
  11643. enumerable: true,
  11644. configurable: true
  11645. });
  11646. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  11647. /**
  11648. * Access the texture that maintains a cached version of the Group2D.
  11649. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  11650. */
  11651. get: function () {
  11652. if (!this._renderableData) {
  11653. return null;
  11654. }
  11655. return this._renderableData._cacheTexture;
  11656. },
  11657. enumerable: true,
  11658. configurable: true
  11659. });
  11660. /**
  11661. * Call this method to remove this Group and its children from the Canvas
  11662. */
  11663. Group2D.prototype.dispose = function () {
  11664. if (!_super.prototype.dispose.call(this)) {
  11665. return false;
  11666. }
  11667. if (this._trackedNode != null) {
  11668. this.owner._unregisterTrackedNode(this);
  11669. this._trackedNode = null;
  11670. }
  11671. if (this._renderableData) {
  11672. this._renderableData.dispose(this.owner);
  11673. this._renderableData = null;
  11674. }
  11675. return true;
  11676. };
  11677. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  11678. /**
  11679. * @returns Returns true if the Group render content, false if it's a logical group only
  11680. */
  11681. get: function () {
  11682. return this._isRenderableGroup;
  11683. },
  11684. enumerable: true,
  11685. configurable: true
  11686. });
  11687. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  11688. /**
  11689. * @returns only meaningful for isRenderableGroup, will be true if the content of the Group is cached into a texture, false if it's rendered every time
  11690. */
  11691. get: function () {
  11692. return this._isCachedGroup;
  11693. },
  11694. enumerable: true,
  11695. configurable: true
  11696. });
  11697. Object.defineProperty(Group2D.prototype, "size", {
  11698. get: function () {
  11699. return this.internalGetSize();
  11700. },
  11701. /**
  11702. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  11703. * BEWARE: if the Group is a RenderableGroup and its content is cache the texture will be resized each time the group is getting bigger. For performance reason the opposite won't be true: the texture won't shrink if the group does.
  11704. */
  11705. set: function (val) {
  11706. this.internalSetSize(val);
  11707. },
  11708. enumerable: true,
  11709. configurable: true
  11710. });
  11711. Object.defineProperty(Group2D.prototype, "viewportSize", {
  11712. get: function () {
  11713. return this._viewportSize;
  11714. },
  11715. enumerable: true,
  11716. configurable: true
  11717. });
  11718. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  11719. /**
  11720. * Get/set the Cache Behavior, used in case the Canvas Cache Strategy is set to CACHESTRATEGY_ALLGROUPS. Can be either GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP, GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE or GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY. See their documentation for more information.
  11721. * GROUPCACHEBEHAVIOR_NORESIZEONSCALE can also be set if you set it at creation time.
  11722. * It is critical to understand than you HAVE TO play with this behavior in order to achieve a good performance/memory ratio. Caching all groups would certainly be the worst strategy of all.
  11723. */
  11724. get: function () {
  11725. return this._cacheBehavior;
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. Group2D.prototype._addPrimToDirtyList = function (prim) {
  11731. this._renderableData._primDirtyList.push(prim);
  11732. };
  11733. Group2D.prototype._renderCachedCanvas = function () {
  11734. this.owner._addGroupRenderCount(1);
  11735. this.updateCachedStates(true);
  11736. var context = new BABYLON.PrepareRender2DContext();
  11737. this._prepareGroupRender(context);
  11738. this._groupRender();
  11739. };
  11740. Object.defineProperty(Group2D.prototype, "trackedNode", {
  11741. /**
  11742. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  11743. */
  11744. get: function () {
  11745. return this._trackedNode;
  11746. },
  11747. set: function (val) {
  11748. if (val != null) {
  11749. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  11750. this.owner._registerTrackedNode(this);
  11751. }
  11752. this._trackedNode = val;
  11753. }
  11754. else {
  11755. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  11756. this.owner._unregisterTrackedNode(this);
  11757. }
  11758. this._trackedNode = null;
  11759. }
  11760. },
  11761. enumerable: true,
  11762. configurable: true
  11763. });
  11764. Object.defineProperty(Group2D.prototype, "trackedNodeOffset", {
  11765. /**
  11766. * Get/set the offset of the tracked node in the tracked node's local space.
  11767. */
  11768. get: function () {
  11769. return this._trackedNodeOffset;
  11770. },
  11771. set: function (val) {
  11772. if (!this._trackedNodeOffset) {
  11773. this._trackedNodeOffset = val.clone();
  11774. }
  11775. else {
  11776. this._trackedNodeOffset.copyFrom(val);
  11777. }
  11778. },
  11779. enumerable: true,
  11780. configurable: true
  11781. });
  11782. Group2D.prototype.levelIntersect = function (intersectInfo) {
  11783. // If we've made it so far it means the boundingInfo intersection test succeed, the Group2D is shaped the same, so we always return true
  11784. return true;
  11785. };
  11786. Group2D.prototype.updateLevelBoundingInfo = function () {
  11787. var size;
  11788. // If the size is set by the user, the boundingInfo is computed from this value
  11789. if (this.size) {
  11790. size = this.size;
  11791. }
  11792. else {
  11793. size = new BABYLON.Size(0, 0);
  11794. }
  11795. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  11796. return true;
  11797. };
  11798. // Method called only on renderable groups to prepare the rendering
  11799. Group2D.prototype._prepareGroupRender = function (context) {
  11800. var sortedDirtyList = null;
  11801. // Update the Global Transformation and visibility status of the changed primitives
  11802. var rd = this._renderableData;
  11803. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  11804. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  11805. this.updateCachedStatesOf(sortedDirtyList, true);
  11806. }
  11807. var s = this.actualSize;
  11808. var a = this.actualScale;
  11809. var hwsl = 1 / this.owner.engine.getHardwareScalingLevel();
  11810. var sw = Math.ceil(s.width * a.x * hwsl);
  11811. var sh = Math.ceil(s.height * a.y * hwsl);
  11812. // The dimension must be overridden when using the designSize feature, the ratio is maintain to compute a uniform scale, which is mandatory but if the designSize's ratio is different from the rendering surface's ratio, content will be clipped in some cases.
  11813. // So we set the width/height to the rendering's one because that's what we want for the viewport!
  11814. if ((this instanceof BABYLON.Canvas2D || this.id === "__cachedCanvasGroup__") && this.owner.designSize != null) {
  11815. sw = this.owner.engine.getRenderWidth();
  11816. sh = this.owner.engine.getRenderHeight();
  11817. }
  11818. // Setup the size of the rendering viewport
  11819. // In non cache mode, we're rendering directly to the rendering canvas, in this case we have to detect if the canvas size changed since the previous iteration, if it's the case all primitives must be prepared again because their transformation must be recompute
  11820. if (!this._isCachedGroup) {
  11821. // Compute the WebGL viewport's location/size
  11822. var t = this._globalTransform.getTranslation();
  11823. var rs = this.owner._renderingSize.multiplyByFloats(hwsl, hwsl);
  11824. sh = Math.min(sh, rs.height - t.y);
  11825. sw = Math.min(sw, rs.width - t.x);
  11826. var x = t.x;
  11827. var y = t.y;
  11828. // The viewport where we're rendering must be the size of the canvas if this one fit in the rendering screen or clipped to the screen dimensions if needed
  11829. this._viewportPosition.x = x;
  11830. this._viewportPosition.y = y;
  11831. }
  11832. // For a cachedGroup we also check of the group's actualSize is changing, if it's the case then the rendering zone will be change so we also have to dirty all primitives to prepare them again.
  11833. if (this._viewportSize.width !== sw || this._viewportSize.height !== sh) {
  11834. context.forceRefreshPrimitive = true;
  11835. this._viewportSize.width = sw;
  11836. this._viewportSize.height = sh;
  11837. }
  11838. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  11839. // If the group is cached, set the dirty flag to true because of the incoming changes
  11840. this._cacheGroupDirty = this._isCachedGroup;
  11841. rd._primNewDirtyList.splice(0);
  11842. // If it's a force refresh, prepare all the children
  11843. if (context.forceRefreshPrimitive) {
  11844. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11845. var p = _a[_i];
  11846. p._prepareRender(context);
  11847. }
  11848. }
  11849. else {
  11850. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  11851. // the hierarchyDepth in order to prepare primitives from top to bottom
  11852. if (!sortedDirtyList) {
  11853. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  11854. }
  11855. sortedDirtyList.forEach(function (p) {
  11856. // We need to check if prepare is needed because even if the primitive is in the dirtyList, its parent primitive may also have been modified, then prepared, then recurse on its children primitives (this one for instance) if the changes where impacting them.
  11857. // For instance: a Rect's position change, the position of its children primitives will also change so a prepare will be call on them. If a child was in the dirtyList we will avoid a second prepare by making this check.
  11858. if (!p.isDisposed && p._needPrepare()) {
  11859. p._prepareRender(context);
  11860. }
  11861. });
  11862. }
  11863. // Everything is updated, clear the dirty list
  11864. rd._primDirtyList.forEach(function (p) {
  11865. if (rd._primNewDirtyList.indexOf(p) === -1) {
  11866. p._resetPropertiesDirty();
  11867. }
  11868. else {
  11869. p._setFlags(BABYLON.SmartPropertyPrim.flagNeedRefresh);
  11870. }
  11871. });
  11872. rd._primDirtyList.splice(0);
  11873. rd._primDirtyList = rd._primDirtyList.concat(rd._primNewDirtyList);
  11874. }
  11875. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  11876. rd._childrenRenderableGroups.forEach(function (g) {
  11877. g._prepareGroupRender(context);
  11878. });
  11879. };
  11880. Group2D.prototype._groupRender = function () {
  11881. var _this = this;
  11882. var engine = this.owner.engine;
  11883. var failedCount = 0;
  11884. // First recurse to children render group to render them (in their cache or on screen)
  11885. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  11886. var childGroup = _a[_i];
  11887. childGroup._groupRender();
  11888. }
  11889. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  11890. if (!this.isCachedGroup || this._cacheGroupDirty) {
  11891. this.owner._addGroupRenderCount(1);
  11892. if (this.isCachedGroup) {
  11893. this._bindCacheTarget();
  11894. }
  11895. else {
  11896. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  11897. }
  11898. var curAlphaTest = engine.getAlphaTesting() === true;
  11899. var curDepthWrite = engine.getDepthWrite() === true;
  11900. // ===================================================================
  11901. // First pass, update the InstancedArray and render Opaque primitives
  11902. // Disable Alpha Testing, Enable Depth Write
  11903. engine.setAlphaTesting(false);
  11904. engine.setDepthWrite(true);
  11905. // For each different model of primitive to render
  11906. var context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  11907. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  11908. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  11909. var renderCount = _this._prepareContext(engine, context_1, v);
  11910. // If null is returned, there's no opaque data to render
  11911. if (renderCount === null) {
  11912. return;
  11913. }
  11914. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  11915. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  11916. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  11917. var renderFailed = !v.modelRenderCache.render(v, context_1);
  11918. // Update dirty flag/related
  11919. v.opaqueDirty = renderFailed;
  11920. failedCount += renderFailed ? 1 : 0;
  11921. }
  11922. });
  11923. // =======================================================================
  11924. // Second pass, update the InstancedArray and render AlphaTest primitives
  11925. // Enable Alpha Testing, Enable Depth Write
  11926. engine.setAlphaTesting(true);
  11927. engine.setDepthWrite(true);
  11928. // For each different model of primitive to render
  11929. context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  11930. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  11931. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  11932. var renderCount = _this._prepareContext(engine, context_1, v);
  11933. // If null is returned, there's no opaque data to render
  11934. if (renderCount === null) {
  11935. return;
  11936. }
  11937. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  11938. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  11939. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  11940. var renderFailed = !v.modelRenderCache.render(v, context_1);
  11941. // Update dirty flag/related
  11942. v.opaqueDirty = renderFailed;
  11943. failedCount += renderFailed ? 1 : 0;
  11944. }
  11945. });
  11946. // =======================================================================
  11947. // Third pass, transparent primitive rendering
  11948. // Enable Alpha Testing, Disable Depth Write
  11949. engine.setAlphaTesting(true);
  11950. engine.setDepthWrite(false);
  11951. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  11952. if (this._renderableData._transparentListChanged) {
  11953. this._updateTransparentData();
  11954. }
  11955. // From this point on we have up to date data to render, so let's go
  11956. failedCount += this._renderTransparentData();
  11957. // =======================================================================
  11958. // Unbind target/restore viewport setting, clear dirty flag, and quit
  11959. // The group's content is no longer dirty
  11960. this._cacheGroupDirty = failedCount !== 0;
  11961. if (this.isCachedGroup) {
  11962. this._unbindCacheTarget();
  11963. }
  11964. else {
  11965. if (curVP) {
  11966. engine.setViewport(curVP);
  11967. }
  11968. }
  11969. // Restore saved states
  11970. engine.setAlphaTesting(curAlphaTest);
  11971. engine.setDepthWrite(curDepthWrite);
  11972. }
  11973. };
  11974. Group2D.prototype._setCacheGroupDirty = function () {
  11975. this._cacheGroupDirty = true;
  11976. };
  11977. Group2D.prototype._updateTransparentData = function () {
  11978. this.owner._addUpdateTransparentDataCount(1);
  11979. var rd = this._renderableData;
  11980. // Sort all the primitive from their depth, max (bottom) to min (top)
  11981. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  11982. var checkAndAddPrimInSegment = function (seg, tpiI) {
  11983. var tpi = rd._transparentPrimitives[tpiI];
  11984. // Fast rejection: if gii are different
  11985. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  11986. return false;
  11987. }
  11988. //let tpiZ = tpi._primitive.actualZOffset;
  11989. // We've made it so far, the tpi can be part of the segment, add it
  11990. tpi._transparentSegment = seg;
  11991. tpi._primitive._updateTransparentSegmentIndices(seg);
  11992. return true;
  11993. };
  11994. // Free the existing TransparentSegments
  11995. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  11996. var ts = _a[_i];
  11997. ts.dispose(this.owner.engine);
  11998. }
  11999. rd._transparentSegments.splice(0);
  12000. var prevSeg = null;
  12001. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  12002. var tpi = rd._transparentPrimitives[tpiI];
  12003. // Check if the Data in which the primitive is stored is not sorted properly
  12004. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  12005. tpi._groupInstanceInfo.sortTransparentData();
  12006. }
  12007. // Reset the segment, we have to create/rebuild it
  12008. tpi._transparentSegment = null;
  12009. // If there's a previous valid segment, check if this prim can be part of it
  12010. if (prevSeg) {
  12011. checkAndAddPrimInSegment(prevSeg, tpiI);
  12012. }
  12013. // If we couldn't insert in the adjacent segments, he have to create one
  12014. if (!tpi._transparentSegment) {
  12015. var ts = new BABYLON.TransparentSegment();
  12016. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  12017. var prim = tpi._primitive;
  12018. ts.startZ = prim.actualZOffset;
  12019. prim._updateTransparentSegmentIndices(ts);
  12020. ts.endZ = ts.startZ;
  12021. tpi._transparentSegment = ts;
  12022. rd._transparentSegments.push(ts);
  12023. }
  12024. // Update prevSeg
  12025. prevSeg = tpi._transparentSegment;
  12026. }
  12027. //rd._firstChangedPrim = null;
  12028. rd._transparentListChanged = false;
  12029. };
  12030. Group2D.prototype._renderTransparentData = function () {
  12031. var failedCount = 0;
  12032. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  12033. var rd = this._renderableData;
  12034. var useInstanced = this.owner.supportInstancedArray;
  12035. var length = rd._transparentSegments.length;
  12036. for (var i = 0; i < length; i++) {
  12037. context.instancedBuffers = null;
  12038. var ts = rd._transparentSegments[i];
  12039. var gii = ts.groupInsanceInfo;
  12040. var mrc = gii.modelRenderCache;
  12041. var engine = this.owner.engine;
  12042. var count = ts.endDataIndex - ts.startDataIndex;
  12043. // Use Instanced Array if it's supported and if there's at least minPartCountToUseInstancedArray prims to draw.
  12044. // We don't want to create an Instanced Buffer for less that minPartCountToUseInstancedArray prims
  12045. if (useInstanced && count >= this.owner.minPartCountToUseInstancedArray) {
  12046. if (!ts.partBuffers) {
  12047. var buffers = new Array();
  12048. for (var j = 0; j < gii.transparentData.length; j++) {
  12049. var gitd = gii.transparentData[j];
  12050. var dfa = gitd._partData;
  12051. var data = dfa.pack();
  12052. var stride = dfa.stride;
  12053. var neededSize = count * stride * 4;
  12054. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  12055. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  12056. engine.updateArrayBuffer(segData);
  12057. buffers.push(buffer);
  12058. }
  12059. ts.partBuffers = buffers;
  12060. }
  12061. else if (gii.transparentDirty) {
  12062. for (var j = 0; j < gii.transparentData.length; j++) {
  12063. var gitd = gii.transparentData[j];
  12064. var dfa = gitd._partData;
  12065. var data = dfa.pack();
  12066. var stride = dfa.stride;
  12067. var buffer = ts.partBuffers[j];
  12068. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  12069. engine.bindArrayBuffer(buffer);
  12070. engine.updateArrayBuffer(segData);
  12071. }
  12072. }
  12073. context.useInstancing = true;
  12074. context.instancesCount = count;
  12075. context.instancedBuffers = ts.partBuffers;
  12076. context.groupInfoPartData = gii.transparentData;
  12077. var renderFailed = !mrc.render(gii, context);
  12078. failedCount += renderFailed ? 1 : 0;
  12079. }
  12080. else {
  12081. context.useInstancing = false;
  12082. context.partDataStartIndex = ts.startDataIndex;
  12083. context.partDataEndIndex = ts.endDataIndex;
  12084. context.groupInfoPartData = gii.transparentData;
  12085. var renderFailed = !mrc.render(gii, context);
  12086. failedCount += renderFailed ? 1 : 0;
  12087. }
  12088. }
  12089. return failedCount;
  12090. };
  12091. Group2D.prototype._prepareContext = function (engine, context, gii) {
  12092. var gipd = null;
  12093. var setDirty;
  12094. var getDirty;
  12095. // Render Mode specifics
  12096. switch (context.renderMode) {
  12097. case BABYLON.Render2DContext.RenderModeOpaque:
  12098. {
  12099. if (!gii.hasOpaqueData) {
  12100. return null;
  12101. }
  12102. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  12103. getDirty = function () { return gii.opaqueDirty; };
  12104. context.groupInfoPartData = gii.opaqueData;
  12105. gipd = gii.opaqueData;
  12106. break;
  12107. }
  12108. case BABYLON.Render2DContext.RenderModeAlphaTest:
  12109. {
  12110. if (!gii.hasAlphaTestData) {
  12111. return null;
  12112. }
  12113. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  12114. getDirty = function () { return gii.alphaTestDirty; };
  12115. context.groupInfoPartData = gii.alphaTestData;
  12116. gipd = gii.alphaTestData;
  12117. break;
  12118. }
  12119. default:
  12120. throw new Error("_prepareContext is only for opaque or alphaTest");
  12121. }
  12122. var renderCount = 0;
  12123. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  12124. // Skip it if instanced arrays are not supported
  12125. if (this.owner.supportInstancedArray) {
  12126. // Flag for instancing
  12127. context.useInstancing = true;
  12128. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  12129. for (var i = 0; i < gipd.length; i++) {
  12130. var pid = gipd[i];
  12131. // If the instances of the model was changed, pack the data
  12132. var array = pid._partData;
  12133. var instanceData_1 = array.pack();
  12134. renderCount += array.usedElementCount;
  12135. // Compute the size the instance buffer should have
  12136. var neededSize = array.usedElementCount * array.stride * 4;
  12137. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  12138. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  12139. if (pid._partBuffer) {
  12140. engine.deleteInstancesBuffer(pid._partBuffer);
  12141. }
  12142. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  12143. pid._partBufferSize = neededSize;
  12144. setDirty(false);
  12145. // Update the WebGL buffer to match the new content of the instances data
  12146. engine.updateArrayBuffer(instanceData_1);
  12147. }
  12148. else if (getDirty()) {
  12149. // Update the WebGL buffer to match the new content of the instances data
  12150. engine.bindArrayBuffer(pid._partBuffer);
  12151. engine.updateArrayBuffer(instanceData_1);
  12152. }
  12153. }
  12154. setDirty(false);
  12155. }
  12156. else {
  12157. context.partDataStartIndex = 0;
  12158. // Find the first valid object to get the count
  12159. if (context.groupInfoPartData.length > 0) {
  12160. var i = 0;
  12161. while (!context.groupInfoPartData[i]) {
  12162. i++;
  12163. }
  12164. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  12165. }
  12166. }
  12167. return renderCount;
  12168. };
  12169. Group2D.prototype._setRenderingScale = function (scale) {
  12170. if (this._renderableData._renderingScale === scale) {
  12171. return;
  12172. }
  12173. this._renderableData._renderingScale = scale;
  12174. };
  12175. Group2D.prototype._bindCacheTarget = function () {
  12176. var curWidth;
  12177. var curHeight;
  12178. var rd = this._renderableData;
  12179. var rs = rd._renderingScale;
  12180. var noResizeScale = rd._noResizeOnScale;
  12181. var isCanvas = this.parent == null;
  12182. var scale;
  12183. if (noResizeScale) {
  12184. scale = isCanvas ? Group2D_1._uV : this.parent.actualScale;
  12185. }
  12186. else {
  12187. scale = this.actualScale;
  12188. }
  12189. if (isCanvas && this.owner.cachingStrategy === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS && this.owner.isScreenSpace) {
  12190. if (this.owner.designSize || this.owner.fitRenderingDevice) {
  12191. Group2D_1._s.width = this.owner.engine.getRenderWidth();
  12192. Group2D_1._s.height = this.owner.engine.getRenderHeight();
  12193. }
  12194. else {
  12195. Group2D_1._s.copyFrom(this.owner.size);
  12196. }
  12197. }
  12198. else {
  12199. Group2D_1._s.width = Math.ceil(this.actualSize.width * scale.x * rs);
  12200. Group2D_1._s.height = Math.ceil(this.actualSize.height * scale.y * rs);
  12201. }
  12202. var sizeChanged = !Group2D_1._s.equals(rd._cacheSize);
  12203. if (rd._cacheNode) {
  12204. var size = rd._cacheNode.contentSize;
  12205. // Check if we have to deallocate because the size is too small
  12206. if ((size.width < Group2D_1._s.width) || (size.height < Group2D_1._s.height)) {
  12207. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  12208. // For World space: no over-provisioning
  12209. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  12210. curWidth = Math.floor(Group2D_1._s.width * overprovisioning);
  12211. curHeight = Math.floor(Group2D_1._s.height * overprovisioning);
  12212. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  12213. rd._cacheTexture.freeRect(rd._cacheNode);
  12214. rd._cacheNode = null;
  12215. }
  12216. }
  12217. if (!rd._cacheNode) {
  12218. // Check if we have to allocate a rendering zone in the global cache texture
  12219. var res = this.owner._allocateGroupCache(this, this.parent && this.parent.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  12220. rd._cacheNode = res.node;
  12221. rd._cacheTexture = res.texture;
  12222. if (rd._cacheRenderSprite) {
  12223. rd._cacheRenderSprite.dispose();
  12224. }
  12225. rd._cacheRenderSprite = res.sprite;
  12226. sizeChanged = true;
  12227. }
  12228. if (sizeChanged) {
  12229. rd._cacheSize.copyFrom(Group2D_1._s);
  12230. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  12231. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  12232. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  12233. }
  12234. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  12235. }
  12236. var n = rd._cacheNode;
  12237. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D_1._s, true);
  12238. };
  12239. Group2D.prototype._unbindCacheTarget = function () {
  12240. if (this._renderableData._cacheTexture) {
  12241. this._renderableData._cacheTexture.unbindTexture();
  12242. }
  12243. };
  12244. Group2D.prototype._spreadActualScaleDirty = function () {
  12245. if (this._renderableData && this._renderableData._cacheRenderSprite) {
  12246. this.handleGroupChanged(BABYLON.Prim2DBase.actualScaleProperty);
  12247. }
  12248. _super.prototype._spreadActualScaleDirty.call(this);
  12249. };
  12250. Group2D.prototype.handleGroupChanged = function (prop) {
  12251. // This method is only for cachedGroup
  12252. var rd = this._renderableData;
  12253. if (!rd) {
  12254. return;
  12255. }
  12256. var cachedSprite = rd._cacheRenderSprite;
  12257. if (!this.isCachedGroup || !cachedSprite) {
  12258. return;
  12259. }
  12260. // For now we only support these property changes
  12261. // TODO: add more! :)
  12262. switch (prop.id) {
  12263. case BABYLON.Prim2DBase.actualPositionProperty.id:
  12264. cachedSprite.actualPosition = this.actualPosition.clone();
  12265. if (cachedSprite.position != null) {
  12266. cachedSprite.position = cachedSprite.actualPosition.clone();
  12267. }
  12268. break;
  12269. case BABYLON.Prim2DBase.rotationProperty.id:
  12270. cachedSprite.rotation = this.rotation;
  12271. break;
  12272. case BABYLON.Prim2DBase.scaleProperty.id:
  12273. cachedSprite.scale = this.scale;
  12274. break;
  12275. case BABYLON.Prim2DBase.originProperty.id:
  12276. cachedSprite.origin = this.origin.clone();
  12277. break;
  12278. case Group2D_1.actualSizeProperty.id:
  12279. cachedSprite.size = this.actualSize.clone();
  12280. break;
  12281. }
  12282. };
  12283. Group2D.prototype.detectGroupStates = function () {
  12284. var isCanvas = this instanceof BABYLON.Canvas2D;
  12285. var canvasStrat = this.owner.cachingStrategy;
  12286. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  12287. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  12288. this._isRenderableGroup = isCanvas;
  12289. this._isCachedGroup = false;
  12290. }
  12291. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  12292. if (isCanvas) {
  12293. this._isRenderableGroup = true;
  12294. this._isCachedGroup = true;
  12295. }
  12296. else {
  12297. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  12298. this._isCachedGroup = false;
  12299. }
  12300. }
  12301. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  12302. if (isCanvas) {
  12303. this._isRenderableGroup = true;
  12304. this._isCachedGroup = false;
  12305. }
  12306. else {
  12307. if (this.hierarchyDepth === 1) {
  12308. this._isRenderableGroup = true;
  12309. this._isCachedGroup = true;
  12310. }
  12311. else {
  12312. this._isRenderableGroup = false;
  12313. this._isCachedGroup = false;
  12314. }
  12315. }
  12316. }
  12317. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  12318. if (isCanvas) {
  12319. this._isRenderableGroup = true;
  12320. this._isCachedGroup = false;
  12321. }
  12322. else {
  12323. var gcb = this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_OPTIONMASK;
  12324. if ((gcb === Group2D_1.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D_1.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  12325. this._isRenderableGroup = gcb === Group2D_1.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  12326. this._isCachedGroup = false;
  12327. }
  12328. if (gcb === Group2D_1.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  12329. this._isRenderableGroup = true;
  12330. this._isCachedGroup = true;
  12331. }
  12332. }
  12333. }
  12334. if (this._isRenderableGroup) {
  12335. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  12336. if (!this._renderableData) {
  12337. this._renderableData = new RenderableGroupData();
  12338. }
  12339. }
  12340. // If the group is tagged as renderable we add it to the renderable tree
  12341. if (this._isCachedGroup) {
  12342. this._renderableData._noResizeOnScale = (this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  12343. var cur = this.parent;
  12344. while (cur) {
  12345. if (cur instanceof Group2D_1 && cur._isRenderableGroup) {
  12346. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  12347. cur._renderableData._childrenRenderableGroups.push(this);
  12348. }
  12349. break;
  12350. }
  12351. cur = cur.parent;
  12352. }
  12353. }
  12354. };
  12355. Object.defineProperty(Group2D.prototype, "_cachedTexture", {
  12356. get: function () {
  12357. if (this._renderableData) {
  12358. return this._renderableData._cacheTexture;
  12359. }
  12360. return null;
  12361. },
  12362. enumerable: true,
  12363. configurable: true
  12364. });
  12365. return Group2D;
  12366. }(BABYLON.Prim2DBase));
  12367. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  12368. /**
  12369. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  12370. */
  12371. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  12372. /**
  12373. * When used, this group's content won't be cached, no matter which strategy used.
  12374. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  12375. */
  12376. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  12377. /**
  12378. * When used, the group's content will be cached in the nearest cached parent group/canvas
  12379. */
  12380. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  12381. /**
  12382. * You can specify this behavior to any cached Group2D to indicate that you don't want the cached content to be resized when the Group's actualScale is changing. It will draw the content stretched or shrink which is faster than a resize. This setting is obviously for performance consideration, don't use it if you want the best rendering quality
  12383. */
  12384. Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE = 0x100;
  12385. Group2D.GROUPCACHEBEHAVIOR_OPTIONMASK = 0xFF;
  12386. Group2D._uV = new BABYLON.Vector2(1, 1);
  12387. Group2D._s = BABYLON.Size.Zero();
  12388. Group2D._unS = new BABYLON.Vector2(1, 1);
  12389. __decorate([
  12390. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D_1.sizeProperty = pi; }, false, true)
  12391. ], Group2D.prototype, "size", null);
  12392. Group2D = Group2D_1 = __decorate([
  12393. BABYLON.className("Group2D", "BABYLON")
  12394. ], Group2D);
  12395. BABYLON.Group2D = Group2D;
  12396. var RenderableGroupData = (function () {
  12397. function RenderableGroupData() {
  12398. this._primDirtyList = new Array();
  12399. this._primNewDirtyList = new Array();
  12400. this._childrenRenderableGroups = new Array();
  12401. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  12402. this._transparentPrimitives = new Array();
  12403. this._transparentSegments = new Array();
  12404. this._transparentListChanged = false;
  12405. this._cacheNode = null;
  12406. this._cacheTexture = null;
  12407. this._cacheRenderSprite = null;
  12408. this._renderingScale = 1;
  12409. this._cacheNodeUVs = null;
  12410. this._cacheNodeUVsChangedObservable = null;
  12411. this._cacheSize = BABYLON.Size.Zero();
  12412. this._useMipMap = false;
  12413. this._anisotropicLevel = 1;
  12414. this._noResizeOnScale = false;
  12415. }
  12416. RenderableGroupData.prototype.dispose = function (owner) {
  12417. var engine = owner.engine;
  12418. if (this._cacheRenderSprite) {
  12419. this._cacheRenderSprite.dispose();
  12420. this._cacheRenderSprite = null;
  12421. }
  12422. if (this._cacheTexture && this._cacheNode) {
  12423. this._cacheTexture.freeRect(this._cacheNode);
  12424. this._cacheTexture = null;
  12425. this._cacheNode = null;
  12426. }
  12427. if (this._primDirtyList) {
  12428. this._primDirtyList.splice(0);
  12429. this._primDirtyList = null;
  12430. }
  12431. if (this._renderGroupInstancesInfo) {
  12432. this._renderGroupInstancesInfo.forEach(function (k, v) {
  12433. v.dispose();
  12434. });
  12435. this._renderGroupInstancesInfo = null;
  12436. }
  12437. if (this._cacheNodeUVsChangedObservable) {
  12438. this._cacheNodeUVsChangedObservable.clear();
  12439. this._cacheNodeUVsChangedObservable = null;
  12440. }
  12441. if (this._transparentSegments) {
  12442. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  12443. var ts = _a[_i];
  12444. ts.dispose(engine);
  12445. }
  12446. this._transparentSegments.splice(0);
  12447. this._transparentSegments = null;
  12448. }
  12449. };
  12450. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  12451. var tpi = new TransparentPrimitiveInfo();
  12452. tpi._primitive = prim;
  12453. tpi._groupInstanceInfo = gii;
  12454. tpi._transparentSegment = null;
  12455. this._transparentPrimitives.push(tpi);
  12456. this._transparentListChanged = true;
  12457. return tpi;
  12458. };
  12459. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  12460. var index = this._transparentPrimitives.indexOf(tpi);
  12461. if (index !== -1) {
  12462. this._transparentPrimitives.splice(index, 1);
  12463. this._transparentListChanged = true;
  12464. }
  12465. };
  12466. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  12467. this._transparentListChanged = true;
  12468. //this.updateSmallestZChangedPrim(tpi);
  12469. };
  12470. return RenderableGroupData;
  12471. }());
  12472. BABYLON.RenderableGroupData = RenderableGroupData;
  12473. var TransparentPrimitiveInfo = (function () {
  12474. function TransparentPrimitiveInfo() {
  12475. }
  12476. return TransparentPrimitiveInfo;
  12477. }());
  12478. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  12479. var Group2D_1;
  12480. })(BABYLON || (BABYLON = {}));
  12481. //# sourceMappingURL=babylon.group2d.js.map
  12482. var __extends = (this && this.__extends) || function (d, b) {
  12483. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12484. function __() { this.constructor = d; }
  12485. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  12486. };
  12487. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  12488. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  12489. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  12490. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  12491. return c > 3 && r && Object.defineProperty(target, key, r), r;
  12492. };
  12493. var BABYLON;
  12494. (function (BABYLON) {
  12495. var WireFrame2DRenderCache = (function (_super) {
  12496. __extends(WireFrame2DRenderCache, _super);
  12497. function WireFrame2DRenderCache() {
  12498. var _this = _super.apply(this, arguments) || this;
  12499. _this.effectsReady = false;
  12500. _this.vb = null;
  12501. _this.vtxCount = 0;
  12502. _this.instancingAttributes = null;
  12503. _this.effect = null;
  12504. _this.effectInstanced = null;
  12505. return _this;
  12506. }
  12507. WireFrame2DRenderCache.prototype.render = function (instanceInfo, context) {
  12508. // Do nothing if the shader is still loading/preparing
  12509. if (!this.effectsReady) {
  12510. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  12511. return false;
  12512. }
  12513. this.effectsReady = true;
  12514. }
  12515. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  12516. var canvas = instanceInfo.owner.owner;
  12517. var engine = canvas.engine;
  12518. var cur = engine.getAlphaMode();
  12519. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  12520. engine.enableEffect(effect);
  12521. engine.bindBuffersDirectly(this.vb, null, [2, 4], 24, effect);
  12522. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  12523. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  12524. }
  12525. var pid = context.groupInfoPartData[0];
  12526. if (context.useInstancing) {
  12527. if (!this.instancingAttributes) {
  12528. this.instancingAttributes = this.loadInstancingAttributes(WireFrame2D.WIREFRAME2D_MAINPARTID, effect);
  12529. }
  12530. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  12531. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  12532. canvas._addDrawCallCount(1, context.renderMode);
  12533. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  12534. engine.drawUnIndexed(false, 0, this.vtxCount, count);
  12535. // engine.draw(true, 0, 6, count);
  12536. engine.unbindInstanceAttributes();
  12537. }
  12538. else {
  12539. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  12540. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  12541. this.setupUniforms(effect, 0, pid._partData, i);
  12542. engine.drawUnIndexed(false, 0, this.vtxCount);
  12543. }
  12544. }
  12545. engine.setAlphaMode(cur, true);
  12546. return true;
  12547. };
  12548. WireFrame2DRenderCache.prototype.updateModelRenderCache = function (prim) {
  12549. var w = prim;
  12550. w._updateVertexBuffer(this);
  12551. return true;
  12552. };
  12553. WireFrame2DRenderCache.prototype.dispose = function () {
  12554. if (!_super.prototype.dispose.call(this)) {
  12555. return false;
  12556. }
  12557. if (this.vb) {
  12558. this._engine._releaseBuffer(this.vb);
  12559. this.vb = null;
  12560. }
  12561. this.effect = null;
  12562. this.effectInstanced = null;
  12563. return true;
  12564. };
  12565. return WireFrame2DRenderCache;
  12566. }(BABYLON.ModelRenderCache));
  12567. BABYLON.WireFrame2DRenderCache = WireFrame2DRenderCache;
  12568. var WireFrameVertex2D = (function () {
  12569. function WireFrameVertex2D(p, c) {
  12570. if (c === void 0) { c = null; }
  12571. this.fromVector2(p);
  12572. if (c != null) {
  12573. this.fromColor4(c);
  12574. }
  12575. else {
  12576. this.r = this.g = this.b = this.a = 1;
  12577. }
  12578. }
  12579. WireFrameVertex2D.prototype.fromVector2 = function (p) {
  12580. this.x = p.x;
  12581. this.y = p.y;
  12582. };
  12583. WireFrameVertex2D.prototype.fromColor3 = function (c) {
  12584. this.r = c.r;
  12585. this.g = c.g;
  12586. this.b = c.b;
  12587. this.a = 1;
  12588. };
  12589. WireFrameVertex2D.prototype.fromColor4 = function (c) {
  12590. this.r = c.r;
  12591. this.g = c.g;
  12592. this.b = c.b;
  12593. this.a = c.a;
  12594. };
  12595. return WireFrameVertex2D;
  12596. }());
  12597. WireFrameVertex2D = __decorate([
  12598. BABYLON.className("WireFrameVertex2D", "BABYLON")
  12599. ], WireFrameVertex2D);
  12600. BABYLON.WireFrameVertex2D = WireFrameVertex2D;
  12601. var WireFrameGroup2D = (function () {
  12602. /**
  12603. * Construct a WireFrameGroup2D object
  12604. * @param id a unique ID among the Groups added to a given WireFrame2D primitive, if you don't specify an id, a random one will be generated. The id is immutable.
  12605. * @param defaultColor specify the default color that will be used when a vertex is pushed, white will be used if not specified.
  12606. */
  12607. function WireFrameGroup2D(id, defaultColor) {
  12608. if (id === void 0) { id = null; }
  12609. if (defaultColor === void 0) { defaultColor = null; }
  12610. this._id = (id == null) ? BABYLON.Tools.RandomId() : id;
  12611. this._uid = BABYLON.Tools.RandomId();
  12612. this._defaultColor = (defaultColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : defaultColor;
  12613. this._buildingStrip = false;
  12614. this._vertices = new Array();
  12615. }
  12616. Object.defineProperty(WireFrameGroup2D.prototype, "uid", {
  12617. get: function () {
  12618. return this._uid;
  12619. },
  12620. enumerable: true,
  12621. configurable: true
  12622. });
  12623. Object.defineProperty(WireFrameGroup2D.prototype, "id", {
  12624. /**
  12625. * Retrieve the ID of the group
  12626. */
  12627. get: function () {
  12628. return this._id;
  12629. },
  12630. enumerable: true,
  12631. configurable: true
  12632. });
  12633. /**
  12634. * Push a vertex in the array of vertices.
  12635. * If you're previously called startLineStrip, the vertex will be pushed twice in order to describe the end of a line and the start of a new one.
  12636. * @param p Position of the vertex
  12637. * @param c Color of the vertex, if null the default color of the group will be used
  12638. */
  12639. WireFrameGroup2D.prototype.pushVertex = function (p, c) {
  12640. if (c === void 0) { c = null; }
  12641. var v = new WireFrameVertex2D(p, (c == null) ? this._defaultColor : c);
  12642. this._vertices.push(v);
  12643. if (this._buildingStrip) {
  12644. var v2 = new WireFrameVertex2D(p, (c == null) ? this._defaultColor : c);
  12645. this._vertices.push(v2);
  12646. }
  12647. };
  12648. /**
  12649. * Start to store a Line Strip. The given vertex will be pushed in the array. The you have to call pushVertex to add subsequent vertices describing the strip and don't forget to call endLineStrip to close the strip!!!
  12650. * @param p Position of the vertex
  12651. * @param c Color of the vertex, if null the default color of the group will be used
  12652. */
  12653. WireFrameGroup2D.prototype.startLineStrip = function (p, c) {
  12654. if (c === void 0) { c = null; }
  12655. this.pushVertex(p, (c == null) ? this._defaultColor : c);
  12656. this._buildingStrip = true;
  12657. };
  12658. /**
  12659. * Close the Strip by storing a last vertex
  12660. * @param p Position of the vertex
  12661. * @param c Color of the vertex, if null the default color of the group will be used
  12662. */
  12663. WireFrameGroup2D.prototype.endLineStrip = function (p, c) {
  12664. if (c === void 0) { c = null; }
  12665. this._buildingStrip = false;
  12666. this.pushVertex(p, (c == null) ? this._defaultColor : c);
  12667. };
  12668. Object.defineProperty(WireFrameGroup2D.prototype, "vertices", {
  12669. /**
  12670. * Access to the array of Vertices, you can manipulate its content but BEWARE of what you're doing!
  12671. */
  12672. get: function () {
  12673. return this._vertices;
  12674. },
  12675. enumerable: true,
  12676. configurable: true
  12677. });
  12678. return WireFrameGroup2D;
  12679. }());
  12680. WireFrameGroup2D = __decorate([
  12681. BABYLON.className("WireFrameGroup2D", "BABYLON")
  12682. ], WireFrameGroup2D);
  12683. BABYLON.WireFrameGroup2D = WireFrameGroup2D;
  12684. var WireFrame2D = WireFrame2D_1 = (function (_super) {
  12685. __extends(WireFrame2D, _super);
  12686. /**
  12687. * Create an WireFrame 2D primitive
  12688. * @param wireFrameGroups an array of WireFrameGroup.
  12689. * @param settings a combination of settings, possible ones are
  12690. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  12691. * - children: an array of direct children
  12692. * - id a text identifier, for information purpose
  12693. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  12694. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  12695. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  12696. * - size: the size of the sprite displayed in the canvas, if not specified the spriteSize will be used
  12697. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  12698. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  12699. * - zOrder: override the zOrder with the specified value
  12700. * - origin: define the normalized origin point location, default [0.5;0.5]
  12701. * - alignToPixel: the rendered lines will be aligned to the rendering device' pixels
  12702. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  12703. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  12704. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  12705. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  12706. * - levelCollision: this primitive is an actor of the Collision Manager and only this level will be used for collision (i.e. not the children). Use deepCollision if you want collision detection on the primitives and its children.
  12707. * - deepCollision: this primitive is an actor of the Collision Manager, this level AND ALSO its children will be used for collision (note: you don't need to set the children as level/deepCollision).
  12708. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  12709. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12710. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12711. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12712. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12713. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  12714. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  12715. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  12716. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  12717. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12718. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12719. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12720. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12721. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  12722. */
  12723. function WireFrame2D(wireFrameGroups, settings) {
  12724. var _this;
  12725. if (!settings) {
  12726. settings = {};
  12727. }
  12728. _this = _super.call(this, settings) || this;
  12729. _this._wireFrameGroups = new BABYLON.StringDictionary();
  12730. for (var _i = 0, wireFrameGroups_1 = wireFrameGroups; _i < wireFrameGroups_1.length; _i++) {
  12731. var wfg = wireFrameGroups_1[_i];
  12732. _this._wireFrameGroups.add(wfg.id, wfg);
  12733. }
  12734. _this._vtxTransparent = false;
  12735. if (settings.size != null) {
  12736. _this.size = settings.size;
  12737. }
  12738. _this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  12739. return _this;
  12740. }
  12741. Object.defineProperty(WireFrame2D.prototype, "wireFrameGroups", {
  12742. get: function () {
  12743. return this._wireFrameGroups;
  12744. },
  12745. enumerable: true,
  12746. configurable: true
  12747. });
  12748. /**
  12749. * If you change the content of the wireFrameGroups you MUST call this method for the changes to be reflected during rendering
  12750. */
  12751. WireFrame2D.prototype.wireFrameGroupsDirty = function () {
  12752. this._setFlags(BABYLON.SmartPropertyPrim.flagModelUpdate);
  12753. this.onPrimBecomesDirty();
  12754. };
  12755. Object.defineProperty(WireFrame2D.prototype, "size", {
  12756. get: function () {
  12757. if (this._size == null) {
  12758. this._computeMinMaxTrans();
  12759. }
  12760. return this._size;
  12761. },
  12762. set: function (value) {
  12763. this.internalSetSize(value);
  12764. },
  12765. enumerable: true,
  12766. configurable: true
  12767. });
  12768. WireFrame2D.prototype.updateLevelBoundingInfo = function () {
  12769. var v = this._computeMinMaxTrans();
  12770. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(v.x, v.z, v.y, v.w, this._levelBoundingInfo);
  12771. return true;
  12772. };
  12773. WireFrame2D.prototype.levelIntersect = function (intersectInfo) {
  12774. // TODO !
  12775. return true;
  12776. };
  12777. Object.defineProperty(WireFrame2D.prototype, "alignToPixel", {
  12778. /**
  12779. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  12780. */
  12781. get: function () {
  12782. return this._alignToPixel;
  12783. },
  12784. set: function (value) {
  12785. this._alignToPixel = value;
  12786. },
  12787. enumerable: true,
  12788. configurable: true
  12789. });
  12790. WireFrame2D.prototype.createModelRenderCache = function (modelKey) {
  12791. var renderCache = new WireFrame2DRenderCache(this.owner.engine, modelKey);
  12792. return renderCache;
  12793. };
  12794. WireFrame2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  12795. var renderCache = modelRenderCache;
  12796. var engine = this.owner.engine;
  12797. // Create the VertexBuffer
  12798. this._updateVertexBuffer(renderCache);
  12799. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  12800. var ei = this.getDataPartEffectInfo(WireFrame2D_1.WIREFRAME2D_MAINPARTID, ["pos", "col"], [], true);
  12801. if (ei) {
  12802. renderCache.effectInstanced = engine.createEffect("wireframe2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  12803. }
  12804. ei = this.getDataPartEffectInfo(WireFrame2D_1.WIREFRAME2D_MAINPARTID, ["pos", "col"], [], false);
  12805. renderCache.effect = engine.createEffect("wireframe2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  12806. return renderCache;
  12807. };
  12808. WireFrame2D.prototype._updateVertexBuffer = function (mrc) {
  12809. var engine = this.owner.engine;
  12810. if (mrc.vb != null) {
  12811. engine._releaseBuffer(mrc.vb);
  12812. }
  12813. var vtxCount = 0;
  12814. this._wireFrameGroups.forEach(function (k, v) { return vtxCount += v.vertices.length; });
  12815. var vb = new Float32Array(vtxCount * 6);
  12816. var i = 0;
  12817. this._wireFrameGroups.forEach(function (k, v) {
  12818. for (var _i = 0, _a = v.vertices; _i < _a.length; _i++) {
  12819. var vtx = _a[_i];
  12820. vb[i++] = vtx.x;
  12821. vb[i++] = vtx.y;
  12822. vb[i++] = vtx.r;
  12823. vb[i++] = vtx.g;
  12824. vb[i++] = vtx.b;
  12825. vb[i++] = vtx.a;
  12826. }
  12827. });
  12828. mrc.vb = engine.createVertexBuffer(vb);
  12829. mrc.vtxCount = vtxCount;
  12830. };
  12831. WireFrame2D.prototype.refreshInstanceDataPart = function (part) {
  12832. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  12833. return false;
  12834. }
  12835. if (part.id === WireFrame2D_1.WIREFRAME2D_MAINPARTID) {
  12836. var d = this._instanceDataParts[0];
  12837. d.properties = new BABYLON.Vector3(this.alignToPixel ? 1 : 0, 2 / this.renderGroup.actualWidth, 2 / this.renderGroup.actualHeight);
  12838. }
  12839. return true;
  12840. };
  12841. WireFrame2D.prototype._computeMinMaxTrans = function () {
  12842. var xmin = Number.MAX_VALUE;
  12843. var xmax = Number.MIN_VALUE;
  12844. var ymin = Number.MAX_VALUE;
  12845. var ymax = Number.MIN_VALUE;
  12846. var transparent = false;
  12847. this._wireFrameGroups.forEach(function (k, v) {
  12848. for (var _i = 0, _a = v.vertices; _i < _a.length; _i++) {
  12849. var vtx = _a[_i];
  12850. xmin = Math.min(xmin, vtx.x);
  12851. xmax = Math.max(xmax, vtx.x);
  12852. ymin = Math.min(ymin, vtx.y);
  12853. ymax = Math.max(ymax, vtx.y);
  12854. if (vtx.a < 1) {
  12855. transparent = true;
  12856. }
  12857. }
  12858. });
  12859. this._vtxTransparent = transparent;
  12860. this._size = new BABYLON.Size(xmax - xmin, ymax - ymin);
  12861. return new BABYLON.Vector4(xmin, ymin, xmax, ymax);
  12862. };
  12863. WireFrame2D.prototype.createInstanceDataParts = function () {
  12864. return [new WireFrame2DInstanceData(WireFrame2D_1.WIREFRAME2D_MAINPARTID)];
  12865. };
  12866. return WireFrame2D;
  12867. }(BABYLON.RenderablePrim2D));
  12868. WireFrame2D.WIREFRAME2D_MAINPARTID = 1;
  12869. __decorate([
  12870. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return WireFrame2D_1.wireFrameGroupsProperty = pi; })
  12871. ], WireFrame2D.prototype, "wireFrameGroups", null);
  12872. WireFrame2D = WireFrame2D_1 = __decorate([
  12873. BABYLON.className("WireFrame2D", "BABYLON")
  12874. ], WireFrame2D);
  12875. BABYLON.WireFrame2D = WireFrame2D;
  12876. var WireFrame2DInstanceData = (function (_super) {
  12877. __extends(WireFrame2DInstanceData, _super);
  12878. function WireFrame2DInstanceData(partId) {
  12879. return _super.call(this, partId, 1) || this;
  12880. }
  12881. Object.defineProperty(WireFrame2DInstanceData.prototype, "properties", {
  12882. // the properties is for now the alignedToPixel value
  12883. get: function () {
  12884. return null;
  12885. },
  12886. set: function (value) {
  12887. },
  12888. enumerable: true,
  12889. configurable: true
  12890. });
  12891. return WireFrame2DInstanceData;
  12892. }(BABYLON.InstanceDataBase));
  12893. __decorate([
  12894. BABYLON.instanceData()
  12895. ], WireFrame2DInstanceData.prototype, "properties", null);
  12896. BABYLON.WireFrame2DInstanceData = WireFrame2DInstanceData;
  12897. var WireFrame2D_1;
  12898. })(BABYLON || (BABYLON = {}));
  12899. var __extends = (this && this.__extends) || function (d, b) {
  12900. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12901. function __() { this.constructor = d; }
  12902. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  12903. };
  12904. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  12905. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  12906. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  12907. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  12908. return c > 3 && r && Object.defineProperty(target, key, r), r;
  12909. };
  12910. var BABYLON;
  12911. (function (BABYLON) {
  12912. var Rectangle2DRenderCache = (function (_super) {
  12913. __extends(Rectangle2DRenderCache, _super);
  12914. function Rectangle2DRenderCache(engine, modelKey) {
  12915. var _this = _super.call(this, engine, modelKey) || this;
  12916. _this.effectsReady = false;
  12917. _this.fillVB = null;
  12918. _this.fillIB = null;
  12919. _this.fillIndicesCount = 0;
  12920. _this.instancingFillAttributes = null;
  12921. _this.effectFill = null;
  12922. _this.effectFillInstanced = null;
  12923. _this.borderVB = null;
  12924. _this.borderIB = null;
  12925. _this.borderIndicesCount = 0;
  12926. _this.instancingBorderAttributes = null;
  12927. _this.effectBorder = null;
  12928. _this.effectBorderInstanced = null;
  12929. return _this;
  12930. }
  12931. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  12932. // Do nothing if the shader is still loading/preparing
  12933. if (!this.effectsReady) {
  12934. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  12935. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  12936. return false;
  12937. }
  12938. this.effectsReady = true;
  12939. }
  12940. var canvas = instanceInfo.owner.owner;
  12941. var engine = canvas.engine;
  12942. var depthFunction = 0;
  12943. if (this.effectFill && this.effectBorder) {
  12944. depthFunction = engine.getDepthFunction();
  12945. engine.setDepthFunctionToLessOrEqual();
  12946. }
  12947. var curAlphaMode = engine.getAlphaMode();
  12948. if (this.effectFill) {
  12949. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  12950. var pid = context.groupInfoPartData[partIndex];
  12951. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  12952. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  12953. }
  12954. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  12955. engine.enableEffect(effect);
  12956. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  12957. if (context.useInstancing) {
  12958. if (!this.instancingFillAttributes) {
  12959. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  12960. }
  12961. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  12962. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  12963. canvas._addDrawCallCount(1, context.renderMode);
  12964. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  12965. engine.draw(true, 0, this.fillIndicesCount, count);
  12966. engine.unbindInstanceAttributes();
  12967. }
  12968. else {
  12969. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  12970. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  12971. this.setupUniforms(effect, partIndex, pid._partData, i);
  12972. engine.draw(true, 0, this.fillIndicesCount);
  12973. }
  12974. }
  12975. }
  12976. if (this.effectBorder) {
  12977. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  12978. var pid = context.groupInfoPartData[partIndex];
  12979. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  12980. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  12981. }
  12982. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  12983. engine.enableEffect(effect);
  12984. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  12985. if (context.useInstancing) {
  12986. if (!this.instancingBorderAttributes) {
  12987. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  12988. }
  12989. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  12990. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  12991. canvas._addDrawCallCount(1, context.renderMode);
  12992. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  12993. engine.draw(true, 0, this.borderIndicesCount, count);
  12994. engine.unbindInstanceAttributes();
  12995. }
  12996. else {
  12997. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  12998. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  12999. this.setupUniforms(effect, partIndex, pid._partData, i);
  13000. engine.draw(true, 0, this.borderIndicesCount);
  13001. }
  13002. }
  13003. }
  13004. engine.setAlphaMode(curAlphaMode, true);
  13005. if (this.effectFill && this.effectBorder) {
  13006. engine.setDepthFunction(depthFunction);
  13007. }
  13008. return true;
  13009. };
  13010. Rectangle2DRenderCache.prototype.dispose = function () {
  13011. if (!_super.prototype.dispose.call(this)) {
  13012. return false;
  13013. }
  13014. if (this.fillVB) {
  13015. this._engine._releaseBuffer(this.fillVB);
  13016. this.fillVB = null;
  13017. }
  13018. if (this.fillIB) {
  13019. this._engine._releaseBuffer(this.fillIB);
  13020. this.fillIB = null;
  13021. }
  13022. this.effectFill = null;
  13023. this.effectFillInstanced = null;
  13024. this.effectBorder = null;
  13025. this.effectBorderInstanced = null;
  13026. if (this.borderVB) {
  13027. this._engine._releaseBuffer(this.borderVB);
  13028. this.borderVB = null;
  13029. }
  13030. if (this.borderIB) {
  13031. this._engine._releaseBuffer(this.borderIB);
  13032. this.borderIB = null;
  13033. }
  13034. return true;
  13035. };
  13036. return Rectangle2DRenderCache;
  13037. }(BABYLON.ModelRenderCache));
  13038. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  13039. var Rectangle2DInstanceData = (function (_super) {
  13040. __extends(Rectangle2DInstanceData, _super);
  13041. function Rectangle2DInstanceData(partId) {
  13042. return _super.call(this, partId, 1) || this;
  13043. }
  13044. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  13045. get: function () {
  13046. return null;
  13047. },
  13048. set: function (value) {
  13049. },
  13050. enumerable: true,
  13051. configurable: true
  13052. });
  13053. return Rectangle2DInstanceData;
  13054. }(BABYLON.Shape2DInstanceData));
  13055. __decorate([
  13056. BABYLON.instanceData()
  13057. ], Rectangle2DInstanceData.prototype, "properties", null);
  13058. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  13059. var Rectangle2D = Rectangle2D_1 = (function (_super) {
  13060. __extends(Rectangle2D, _super);
  13061. /**
  13062. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  13063. * @param settings a combination of settings, possible ones are
  13064. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  13065. * - children: an array of direct children
  13066. * - id a text identifier, for information purpose
  13067. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  13068. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  13069. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  13070. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  13071. * - alignToPixel: if true the primitive will be aligned to the target rendering device's pixel
  13072. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  13073. * - zOrder: override the zOrder with the specified value
  13074. * - origin: define the normalized origin point location, default [0.5;0.5]
  13075. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  13076. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  13077. * - fill: the brush used to draw the fill content of the rectangle, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can also be a string value (see Canvas2D.GetBrushFromString)
  13078. * - border: the brush used to draw the border of the rectangle, you can set null to draw nothing (but you will have to set a fill brush), default is null. can also be a string value (see Canvas2D.GetBrushFromString)
  13079. * - borderThickness: the thickness of the drawn border, default is 1.
  13080. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  13081. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  13082. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  13083. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  13084. * - levelCollision: this primitive is an actor of the Collision Manager and only this level will be used for collision (i.e. not the children). Use deepCollision if you want collision detection on the primitives and its children.
  13085. * - deepCollision: this primitive is an actor of the Collision Manager, this level AND ALSO its children will be used for collision (note: you don't need to set the children as level/deepCollision).
  13086. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  13087. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13088. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13089. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13090. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13091. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  13092. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  13093. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  13094. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  13095. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13096. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13097. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13098. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13099. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  13100. */
  13101. function Rectangle2D(settings) {
  13102. var _this;
  13103. // Avoid checking every time if the object exists
  13104. if (settings == null) {
  13105. settings = {};
  13106. }
  13107. _this = _super.call(this, settings) || this;
  13108. if (settings.size != null) {
  13109. _this.size = settings.size;
  13110. }
  13111. else if (settings.width || settings.height) {
  13112. var size = new BABYLON.Size(settings.width, settings.height);
  13113. _this.size = size;
  13114. }
  13115. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  13116. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  13117. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  13118. //this.size = size;
  13119. _this.roundRadius = roundRadius;
  13120. _this.borderThickness = borderThickness;
  13121. return _this;
  13122. }
  13123. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  13124. get: function () {
  13125. return this._notRounded;
  13126. },
  13127. set: function (value) {
  13128. this._notRounded = value;
  13129. },
  13130. enumerable: true,
  13131. configurable: true
  13132. });
  13133. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  13134. get: function () {
  13135. return this._roundRadius;
  13136. },
  13137. set: function (value) {
  13138. this._roundRadius = value;
  13139. this.notRounded = value === 0;
  13140. this._positioningDirty();
  13141. },
  13142. enumerable: true,
  13143. configurable: true
  13144. });
  13145. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  13146. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  13147. if (this.notRounded) {
  13148. return true;
  13149. }
  13150. // If we got so far it means the bounding box at least passed, so we know it's inside the bounding rectangle, but it can be outside the roundedRectangle.
  13151. // The easiest way is to check if the point is inside on of the four corners area (a little square of roundRadius size at the four corners)
  13152. // If it's the case for one, check if the mouse is located in the quarter that we care about (the one who is visible) then finally make a distance check with the roundRadius radius to see if it's inside the circle quarter or outside.
  13153. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  13154. var size = this.size;
  13155. Rectangle2D_1._i0.x = intersectInfo._localPickPosition.x;
  13156. Rectangle2D_1._i0.y = intersectInfo._localPickPosition.y;
  13157. var rr = this.roundRadius;
  13158. var rrs = rr * rr;
  13159. // Check if the point is in the bottom/left quarter area
  13160. Rectangle2D_1._i1.x = rr;
  13161. Rectangle2D_1._i1.y = rr;
  13162. if (Rectangle2D_1._i0.x <= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y <= Rectangle2D_1._i1.y) {
  13163. // Compute the intersection point in the quarter local space
  13164. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  13165. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  13166. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  13167. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  13168. }
  13169. // Check if the point is in the top/left quarter area
  13170. Rectangle2D_1._i1.x = rr;
  13171. Rectangle2D_1._i1.y = size.height - rr;
  13172. if (Rectangle2D_1._i0.x <= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y >= Rectangle2D_1._i1.y) {
  13173. // Compute the intersection point in the quarter local space
  13174. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  13175. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  13176. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  13177. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  13178. }
  13179. // Check if the point is in the top/right quarter area
  13180. Rectangle2D_1._i1.x = size.width - rr;
  13181. Rectangle2D_1._i1.y = size.height - rr;
  13182. if (Rectangle2D_1._i0.x >= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y >= Rectangle2D_1._i1.y) {
  13183. // Compute the intersection point in the quarter local space
  13184. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  13185. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  13186. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  13187. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  13188. }
  13189. // Check if the point is in the bottom/right quarter area
  13190. Rectangle2D_1._i1.x = size.width - rr;
  13191. Rectangle2D_1._i1.y = rr;
  13192. if (Rectangle2D_1._i0.x >= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y <= Rectangle2D_1._i1.y) {
  13193. // Compute the intersection point in the quarter local space
  13194. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  13195. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  13196. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  13197. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  13198. }
  13199. // At any other locations the point is guarantied to be inside
  13200. return true;
  13201. };
  13202. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  13203. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  13204. return true;
  13205. };
  13206. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  13207. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  13208. return renderCache;
  13209. };
  13210. Rectangle2D.prototype.updateTriArray = function () {
  13211. // Not Rounded = sharp edge rect, the default implementation is the right one!
  13212. if (this.notRounded) {
  13213. _super.prototype.updateTriArray.call(this);
  13214. return;
  13215. }
  13216. // Rounded Corner? It's more complicated! :)
  13217. var subDiv = Rectangle2D_1.roundSubdivisions * 4;
  13218. if (this._primTriArray == null) {
  13219. this._primTriArray = new BABYLON.Tri2DArray(subDiv);
  13220. }
  13221. else {
  13222. this._primTriArray.clear(subDiv);
  13223. }
  13224. var size = this.actualSize;
  13225. var w = size.width;
  13226. var h = size.height;
  13227. var r = this.roundRadius;
  13228. var rsub0 = subDiv * 0.25;
  13229. var rsub1 = subDiv * 0.50;
  13230. var rsub2 = subDiv * 0.75;
  13231. var center = new BABYLON.Vector2(0.5 * size.width, 0.5 * size.height);
  13232. var twopi = Math.PI * 2;
  13233. var nru = r / w;
  13234. var nrv = r / h;
  13235. var computePos = function (index, p) {
  13236. // right/bottom
  13237. if (index < rsub0) {
  13238. p.x = 1.0 - nru;
  13239. p.y = nrv;
  13240. }
  13241. else if (index < rsub1) {
  13242. p.x = nru;
  13243. p.y = nrv;
  13244. }
  13245. else if (index < rsub2) {
  13246. p.x = nru;
  13247. p.y = 1.0 - nrv;
  13248. }
  13249. else {
  13250. p.x = 1.0 - nru;
  13251. p.y = 1.0 - nrv;
  13252. }
  13253. var angle = twopi - (index * twopi / (subDiv - 0.5));
  13254. p.x += Math.cos(angle) * nru;
  13255. p.y += Math.sin(angle) * nrv;
  13256. p.x *= w;
  13257. p.y *= h;
  13258. };
  13259. console.log("Genetre TriList for " + this.id);
  13260. var first = BABYLON.Vector2.Zero();
  13261. var cur = BABYLON.Vector2.Zero();
  13262. computePos(0, first);
  13263. var prev = first.clone();
  13264. for (var index = 1; index < subDiv; index++) {
  13265. computePos(index, cur);
  13266. this._primTriArray.storeTriangle(index - 1, center, prev, cur);
  13267. console.log(index - 1 + ", " + center + ", " + prev + ", " + cur);
  13268. prev.copyFrom(cur);
  13269. }
  13270. this._primTriArray.storeTriangle(subDiv - 1, center, first, prev);
  13271. console.log(subDiv - 1 + ", " + center + ", " + prev + ", " + first);
  13272. };
  13273. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  13274. var renderCache = modelRenderCache;
  13275. var engine = this.owner.engine;
  13276. // Need to create WebGL resources for fill part?
  13277. if (this.fill) {
  13278. var vbSize = ((this.notRounded ? 1 : Rectangle2D_1.roundSubdivisions) * 4) + 1;
  13279. var vb = new Float32Array(vbSize);
  13280. for (var i = 0; i < vbSize; i++) {
  13281. vb[i] = i;
  13282. }
  13283. renderCache.fillVB = engine.createVertexBuffer(vb);
  13284. var triCount = vbSize - 1;
  13285. var ib = new Float32Array(triCount * 3);
  13286. for (var i = 0; i < triCount; i++) {
  13287. ib[i * 3 + 0] = 0;
  13288. ib[i * 3 + 2] = i + 1;
  13289. ib[i * 3 + 1] = i + 2;
  13290. }
  13291. ib[triCount * 3 - 2] = 1;
  13292. renderCache.fillIB = engine.createIndexBuffer(ib);
  13293. renderCache.fillIndicesCount = triCount * 3;
  13294. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  13295. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  13296. if (ei) {
  13297. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  13298. }
  13299. // Get the non instanced version
  13300. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  13301. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  13302. }
  13303. // Need to create WebGL resource for border part?
  13304. if (this.border) {
  13305. var vbSize = (this.notRounded ? 1 : Rectangle2D_1.roundSubdivisions) * 4 * 2;
  13306. var vb = new Float32Array(vbSize);
  13307. for (var i = 0; i < vbSize; i++) {
  13308. vb[i] = i;
  13309. }
  13310. renderCache.borderVB = engine.createVertexBuffer(vb);
  13311. var triCount = vbSize;
  13312. var rs = triCount / 2;
  13313. var ib = new Float32Array(triCount * 3);
  13314. for (var i = 0; i < rs; i++) {
  13315. var r0 = i;
  13316. var r1 = (i + 1) % rs;
  13317. ib[i * 6 + 0] = rs + r1;
  13318. ib[i * 6 + 1] = rs + r0;
  13319. ib[i * 6 + 2] = r0;
  13320. ib[i * 6 + 3] = r1;
  13321. ib[i * 6 + 4] = rs + r1;
  13322. ib[i * 6 + 5] = r0;
  13323. }
  13324. renderCache.borderIB = engine.createIndexBuffer(ib);
  13325. renderCache.borderIndicesCount = triCount * 3;
  13326. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  13327. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  13328. if (ei) {
  13329. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  13330. }
  13331. // Get the non instanced version
  13332. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  13333. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  13334. }
  13335. return renderCache;
  13336. };
  13337. // We override this method because if there's a roundRadius set, we will reduce the initial Content Area to make sure the computed area won't intersect with the shape contour. The formula is simple: we shrink the incoming size by the amount of the roundRadius
  13338. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  13339. // Fall back to default implementation if there's no round Radius
  13340. if (this._notRounded) {
  13341. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  13342. }
  13343. else {
  13344. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  13345. initialContentPosition.x = initialContentPosition.y = rr;
  13346. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  13347. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  13348. initialContentPosition.z = primSize.width - (initialContentPosition.x + initialContentArea.width);
  13349. initialContentPosition.w = primSize.height - (initialContentPosition.y + initialContentArea.height);
  13350. }
  13351. };
  13352. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, paddingOffset, newPrimSize) {
  13353. // Fall back to default implementation if there's no round Radius
  13354. if (this._notRounded) {
  13355. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, paddingOffset, newPrimSize);
  13356. }
  13357. else {
  13358. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  13359. newPrimSize.copyFrom(primSize);
  13360. newPrimSize.width += rr * 2;
  13361. newPrimSize.height += rr * 2;
  13362. paddingOffset.x += rr;
  13363. paddingOffset.y += rr;
  13364. paddingOffset.z += rr;
  13365. paddingOffset.w += rr;
  13366. }
  13367. };
  13368. Rectangle2D.prototype.createInstanceDataParts = function () {
  13369. var res = new Array();
  13370. if (this.border) {
  13371. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  13372. }
  13373. if (this.fill) {
  13374. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  13375. }
  13376. return res;
  13377. };
  13378. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  13379. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  13380. return false;
  13381. }
  13382. var s = Rectangle2D_1._riv0;
  13383. this.getActualGlobalScaleToRef(s);
  13384. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  13385. var d = part;
  13386. var size = this.actualSize;
  13387. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  13388. }
  13389. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  13390. var d = part;
  13391. var size = this.actualSize;
  13392. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  13393. }
  13394. return true;
  13395. };
  13396. return Rectangle2D;
  13397. }(BABYLON.Shape2D));
  13398. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  13399. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  13400. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  13401. Rectangle2D.roundSubdivisions = 16;
  13402. Rectangle2D._riv0 = new BABYLON.Vector2(0, 0);
  13403. __decorate([
  13404. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D_1.notRoundedProperty = pi; })
  13405. ], Rectangle2D.prototype, "notRounded", null);
  13406. __decorate([
  13407. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D_1.roundRadiusProperty = pi; })
  13408. ], Rectangle2D.prototype, "roundRadius", null);
  13409. Rectangle2D = Rectangle2D_1 = __decorate([
  13410. BABYLON.className("Rectangle2D", "BABYLON")
  13411. ], Rectangle2D);
  13412. BABYLON.Rectangle2D = Rectangle2D;
  13413. var Rectangle2D_1;
  13414. })(BABYLON || (BABYLON = {}));
  13415. var __extends = (this && this.__extends) || function (d, b) {
  13416. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13417. function __() { this.constructor = d; }
  13418. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  13419. };
  13420. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  13421. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  13422. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  13423. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  13424. return c > 3 && r && Object.defineProperty(target, key, r), r;
  13425. };
  13426. var BABYLON;
  13427. (function (BABYLON) {
  13428. var Ellipse2DRenderCache = (function (_super) {
  13429. __extends(Ellipse2DRenderCache, _super);
  13430. function Ellipse2DRenderCache(engine, modelKey) {
  13431. var _this = _super.call(this, engine, modelKey) || this;
  13432. _this.effectsReady = false;
  13433. _this.fillVB = null;
  13434. _this.fillIB = null;
  13435. _this.fillIndicesCount = 0;
  13436. _this.instancingFillAttributes = null;
  13437. _this.effectFillInstanced = null;
  13438. _this.effectFill = null;
  13439. _this.borderVB = null;
  13440. _this.borderIB = null;
  13441. _this.borderIndicesCount = 0;
  13442. _this.instancingBorderAttributes = null;
  13443. _this.effectBorderInstanced = null;
  13444. _this.effectBorder = null;
  13445. return _this;
  13446. }
  13447. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  13448. // Do nothing if the shader is still loading/preparing
  13449. if (!this.effectsReady) {
  13450. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  13451. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  13452. return false;
  13453. }
  13454. this.effectsReady = true;
  13455. }
  13456. var canvas = instanceInfo.owner.owner;
  13457. var engine = canvas.engine;
  13458. var depthFunction = 0;
  13459. if (this.effectFill && this.effectBorder) {
  13460. depthFunction = engine.getDepthFunction();
  13461. engine.setDepthFunctionToLessOrEqual();
  13462. }
  13463. var curAlphaMode = engine.getAlphaMode();
  13464. if (this.effectFill) {
  13465. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  13466. var pid = context.groupInfoPartData[partIndex];
  13467. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  13468. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  13469. }
  13470. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  13471. engine.enableEffect(effect);
  13472. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  13473. if (context.useInstancing) {
  13474. if (!this.instancingFillAttributes) {
  13475. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  13476. }
  13477. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  13478. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  13479. canvas._addDrawCallCount(1, context.renderMode);
  13480. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  13481. engine.draw(true, 0, this.fillIndicesCount, count);
  13482. engine.unbindInstanceAttributes();
  13483. }
  13484. else {
  13485. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  13486. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  13487. this.setupUniforms(effect, partIndex, pid._partData, i);
  13488. engine.draw(true, 0, this.fillIndicesCount);
  13489. }
  13490. }
  13491. }
  13492. if (this.effectBorder) {
  13493. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  13494. var pid = context.groupInfoPartData[partIndex];
  13495. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  13496. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  13497. }
  13498. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  13499. engine.enableEffect(effect);
  13500. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  13501. if (context.useInstancing) {
  13502. if (!this.instancingBorderAttributes) {
  13503. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  13504. }
  13505. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  13506. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  13507. canvas._addDrawCallCount(1, context.renderMode);
  13508. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  13509. engine.draw(true, 0, this.borderIndicesCount, count);
  13510. engine.unbindInstanceAttributes();
  13511. }
  13512. else {
  13513. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  13514. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  13515. this.setupUniforms(effect, partIndex, pid._partData, i);
  13516. engine.draw(true, 0, this.borderIndicesCount);
  13517. }
  13518. }
  13519. }
  13520. engine.setAlphaMode(curAlphaMode, true);
  13521. if (this.effectFill && this.effectBorder) {
  13522. engine.setDepthFunction(depthFunction);
  13523. }
  13524. return true;
  13525. };
  13526. Ellipse2DRenderCache.prototype.dispose = function () {
  13527. if (!_super.prototype.dispose.call(this)) {
  13528. return false;
  13529. }
  13530. if (this.fillVB) {
  13531. this._engine._releaseBuffer(this.fillVB);
  13532. this.fillVB = null;
  13533. }
  13534. if (this.fillIB) {
  13535. this._engine._releaseBuffer(this.fillIB);
  13536. this.fillIB = null;
  13537. }
  13538. this.effectFill = null;
  13539. this.effectFillInstanced = null;
  13540. this.effectBorder = null;
  13541. this.effectBorderInstanced = null;
  13542. if (this.borderVB) {
  13543. this._engine._releaseBuffer(this.borderVB);
  13544. this.borderVB = null;
  13545. }
  13546. if (this.borderIB) {
  13547. this._engine._releaseBuffer(this.borderIB);
  13548. this.borderIB = null;
  13549. }
  13550. return true;
  13551. };
  13552. return Ellipse2DRenderCache;
  13553. }(BABYLON.ModelRenderCache));
  13554. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  13555. var Ellipse2DInstanceData = (function (_super) {
  13556. __extends(Ellipse2DInstanceData, _super);
  13557. function Ellipse2DInstanceData(partId) {
  13558. return _super.call(this, partId, 1) || this;
  13559. }
  13560. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  13561. get: function () {
  13562. return null;
  13563. },
  13564. set: function (value) {
  13565. },
  13566. enumerable: true,
  13567. configurable: true
  13568. });
  13569. return Ellipse2DInstanceData;
  13570. }(BABYLON.Shape2DInstanceData));
  13571. __decorate([
  13572. BABYLON.instanceData()
  13573. ], Ellipse2DInstanceData.prototype, "properties", null);
  13574. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  13575. var Ellipse2D = Ellipse2D_1 = (function (_super) {
  13576. __extends(Ellipse2D, _super);
  13577. /**
  13578. * Create an Ellipse 2D Shape primitive
  13579. * @param settings a combination of settings, possible ones are
  13580. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  13581. * - children: an array of direct children
  13582. * - id: a text identifier, for information purpose
  13583. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  13584. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  13585. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  13586. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  13587. * - alignToPixel: if true the primitive will be aligned to the target rendering device's pixel
  13588. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  13589. * - zOrder: override the zOrder with the specified value
  13590. * - origin: define the normalized origin point location, default [0.5;0.5]
  13591. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  13592. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  13593. * - fill: the brush used to draw the fill content of the ellipse, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can also be a string value (see Canvas2D.GetBrushFromString)
  13594. * - border: the brush used to draw the border of the ellipse, you can set null to draw nothing (but you will have to set a fill brush), default is null. can be a string value (see Canvas2D.GetBrushFromString)
  13595. * - borderThickness: the thickness of the drawn border, default is 1.
  13596. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  13597. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  13598. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  13599. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  13600. * - levelCollision: this primitive is an actor of the Collision Manager and only this level will be used for collision (i.e. not the children). Use deepCollision if you want collision detection on the primitives and its children.
  13601. * - deepCollision: this primitive is an actor of the Collision Manager, this level AND ALSO its children will be used for collision (note: you don't need to set the children as level/deepCollision).
  13602. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  13603. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13604. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13605. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13606. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13607. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  13608. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  13609. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  13610. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  13611. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13612. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13613. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13614. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13615. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  13616. */
  13617. function Ellipse2D(settings) {
  13618. var _this;
  13619. // Avoid checking every time if the object exists
  13620. if (settings == null) {
  13621. settings = {};
  13622. }
  13623. _this = _super.call(this, settings) || this;
  13624. if (settings.size != null) {
  13625. _this.size = settings.size;
  13626. }
  13627. else if (settings.width || settings.height) {
  13628. var size = new BABYLON.Size(settings.width, settings.height);
  13629. _this.size = size;
  13630. }
  13631. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  13632. _this.subdivisions = sub;
  13633. return _this;
  13634. }
  13635. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  13636. get: function () {
  13637. return this._subdivisions;
  13638. },
  13639. set: function (value) {
  13640. this._subdivisions = value;
  13641. },
  13642. enumerable: true,
  13643. configurable: true
  13644. });
  13645. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  13646. var w = this.size.width / 2;
  13647. var h = this.size.height / 2;
  13648. var x = intersectInfo._localPickPosition.x - w;
  13649. var y = intersectInfo._localPickPosition.y - h;
  13650. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  13651. };
  13652. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  13653. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  13654. return true;
  13655. };
  13656. Ellipse2D.prototype.updateTriArray = function () {
  13657. var subDiv = this._subdivisions;
  13658. if (this._primTriArray == null) {
  13659. this._primTriArray = new BABYLON.Tri2DArray(subDiv);
  13660. }
  13661. else {
  13662. this._primTriArray.clear(subDiv);
  13663. }
  13664. var size = this.actualSize;
  13665. var center = new BABYLON.Vector2(0.5 * size.width, 0.5 * size.height);
  13666. var v1 = BABYLON.Vector2.Zero();
  13667. var v2 = BABYLON.Vector2.Zero();
  13668. for (var i = 0; i < subDiv; i++) {
  13669. var angle1 = Math.PI * 2 * (i - 1) / subDiv;
  13670. var angle2 = Math.PI * 2 * i / subDiv;
  13671. v1.x = ((Math.cos(angle1) / 2.0) + 0.5) * size.width;
  13672. v1.y = ((Math.sin(angle1) / 2.0) + 0.5) * size.height;
  13673. v2.x = ((Math.cos(angle2) / 2.0) + 0.5) * size.width;
  13674. v2.y = ((Math.sin(angle2) / 2.0) + 0.5) * size.height;
  13675. this._primTriArray.storeTriangle(i, center, v1, v2);
  13676. }
  13677. };
  13678. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  13679. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  13680. return renderCache;
  13681. };
  13682. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  13683. var renderCache = modelRenderCache;
  13684. var engine = this.owner.engine;
  13685. // Need to create WebGL resources for fill part?
  13686. if (this.fill) {
  13687. var vbSize = this.subdivisions + 1;
  13688. var vb = new Float32Array(vbSize);
  13689. for (var i = 0; i < vbSize; i++) {
  13690. vb[i] = i;
  13691. }
  13692. renderCache.fillVB = engine.createVertexBuffer(vb);
  13693. var triCount = vbSize - 1;
  13694. var ib = new Float32Array(triCount * 3);
  13695. for (var i = 0; i < triCount; i++) {
  13696. ib[i * 3 + 0] = 0;
  13697. ib[i * 3 + 2] = i + 2;
  13698. ib[i * 3 + 1] = i + 1;
  13699. }
  13700. ib[triCount * 3 - 1] = 1;
  13701. renderCache.fillIB = engine.createIndexBuffer(ib);
  13702. renderCache.fillIndicesCount = triCount * 3;
  13703. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  13704. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  13705. if (ei) {
  13706. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  13707. }
  13708. // Get the non instanced version
  13709. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  13710. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  13711. }
  13712. // Need to create WebGL resource for border part?
  13713. if (this.border) {
  13714. var vbSize = this.subdivisions * 2;
  13715. var vb = new Float32Array(vbSize);
  13716. for (var i = 0; i < vbSize; i++) {
  13717. vb[i] = i;
  13718. }
  13719. renderCache.borderVB = engine.createVertexBuffer(vb);
  13720. var triCount = vbSize;
  13721. var rs = triCount / 2;
  13722. var ib = new Float32Array(triCount * 3);
  13723. for (var i = 0; i < rs; i++) {
  13724. var r0 = i;
  13725. var r1 = (i + 1) % rs;
  13726. ib[i * 6 + 0] = rs + r1;
  13727. ib[i * 6 + 1] = rs + r0;
  13728. ib[i * 6 + 2] = r0;
  13729. ib[i * 6 + 3] = r1;
  13730. ib[i * 6 + 4] = rs + r1;
  13731. ib[i * 6 + 5] = r0;
  13732. }
  13733. renderCache.borderIB = engine.createIndexBuffer(ib);
  13734. renderCache.borderIndicesCount = (triCount * 3);
  13735. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  13736. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  13737. if (ei) {
  13738. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  13739. }
  13740. // Get the non instanced version
  13741. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  13742. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  13743. }
  13744. return renderCache;
  13745. };
  13746. Ellipse2D.prototype.createInstanceDataParts = function () {
  13747. var res = new Array();
  13748. if (this.border) {
  13749. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  13750. }
  13751. if (this.fill) {
  13752. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  13753. }
  13754. return res;
  13755. };
  13756. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  13757. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  13758. return false;
  13759. }
  13760. var s = Ellipse2D_1._riv0;
  13761. this.getActualGlobalScaleToRef(s);
  13762. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  13763. var d = part;
  13764. var size = this.actualSize;
  13765. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  13766. }
  13767. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  13768. var d = part;
  13769. var size = this.actualSize;
  13770. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  13771. }
  13772. return true;
  13773. };
  13774. return Ellipse2D;
  13775. }(BABYLON.Shape2D));
  13776. Ellipse2D._riv0 = new BABYLON.Vector2(0, 0);
  13777. __decorate([
  13778. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D_1.subdivisionsProperty = pi; })
  13779. ], Ellipse2D.prototype, "subdivisions", null);
  13780. Ellipse2D = Ellipse2D_1 = __decorate([
  13781. BABYLON.className("Ellipse2D", "BABYLON")
  13782. ], Ellipse2D);
  13783. BABYLON.Ellipse2D = Ellipse2D;
  13784. var Ellipse2D_1;
  13785. })(BABYLON || (BABYLON = {}));
  13786. var __extends = (this && this.__extends) || function (d, b) {
  13787. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13788. function __() { this.constructor = d; }
  13789. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  13790. };
  13791. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  13792. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  13793. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  13794. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  13795. return c > 3 && r && Object.defineProperty(target, key, r), r;
  13796. };
  13797. var BABYLON;
  13798. (function (BABYLON) {
  13799. var Sprite2DRenderCache = (function (_super) {
  13800. __extends(Sprite2DRenderCache, _super);
  13801. function Sprite2DRenderCache() {
  13802. var _this = _super.apply(this, arguments) || this;
  13803. _this.effectsReady = false;
  13804. _this.vb = null;
  13805. _this.ib = null;
  13806. _this.instancingAttributes = null;
  13807. _this.texture = null;
  13808. _this.effect = null;
  13809. _this.effectInstanced = null;
  13810. return _this;
  13811. }
  13812. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  13813. // Do nothing if the shader is still loading/preparing
  13814. if (!this.effectsReady) {
  13815. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  13816. return false;
  13817. }
  13818. this.effectsReady = true;
  13819. }
  13820. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  13821. var canvas = instanceInfo.owner.owner;
  13822. var engine = canvas.engine;
  13823. var cur = engine.getAlphaMode();
  13824. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  13825. engine.enableEffect(effect);
  13826. effect.setTexture("diffuseSampler", this.texture);
  13827. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  13828. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  13829. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  13830. }
  13831. effect.setBool("alphaTest", context.renderMode === BABYLON.Render2DContext.RenderModeAlphaTest);
  13832. var pid = context.groupInfoPartData[0];
  13833. if (context.useInstancing) {
  13834. if (!this.instancingAttributes) {
  13835. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  13836. }
  13837. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  13838. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  13839. canvas._addDrawCallCount(1, context.renderMode);
  13840. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  13841. engine.draw(true, 0, 6, count);
  13842. engine.unbindInstanceAttributes();
  13843. }
  13844. else {
  13845. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  13846. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  13847. this.setupUniforms(effect, 0, pid._partData, i);
  13848. engine.draw(true, 0, 6);
  13849. }
  13850. }
  13851. engine.setAlphaMode(cur, true);
  13852. return true;
  13853. };
  13854. Sprite2DRenderCache.prototype.dispose = function () {
  13855. if (!_super.prototype.dispose.call(this)) {
  13856. return false;
  13857. }
  13858. if (this.vb) {
  13859. this._engine._releaseBuffer(this.vb);
  13860. this.vb = null;
  13861. }
  13862. if (this.ib) {
  13863. this._engine._releaseBuffer(this.ib);
  13864. this.ib = null;
  13865. }
  13866. //if (this.texture) {
  13867. // this.texture.dispose();
  13868. // this.texture = null;
  13869. //}
  13870. this.effect = null;
  13871. this.effectInstanced = null;
  13872. return true;
  13873. };
  13874. return Sprite2DRenderCache;
  13875. }(BABYLON.ModelRenderCache));
  13876. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  13877. var Sprite2D = Sprite2D_1 = (function (_super) {
  13878. __extends(Sprite2D, _super);
  13879. /**
  13880. * Create an 2D Sprite primitive
  13881. * @param texture the texture that stores the sprite to render
  13882. * @param settings a combination of settings, possible ones are
  13883. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  13884. * - children: an array of direct children
  13885. * - id a text identifier, for information purpose
  13886. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  13887. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  13888. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  13889. * - size: the size of the sprite displayed in the canvas, if not specified the spriteSize will be used
  13890. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  13891. * - alignToPixel: if true the sprite's texels will be aligned to the rendering viewport pixels, ensuring the best rendering quality but slow animations won't be done as smooth as if you set false. If false a texel could lies between two pixels, being blended by the texture sampling mode you choose, the rendering result won't be as good, but very slow animation will be overall better looking. Default is true: content will be aligned.
  13892. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  13893. * - zOrder: override the zOrder with the specified value
  13894. * - origin: define the normalized origin point location, default [0.5;0.5]
  13895. * - spriteSize: the size of the sprite (in pixels) as it is stored in the texture, if null the size of the given texture will be used, default is null.
  13896. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  13897. * - scale9: draw the sprite as a Scale9 sprite, see http://yannickloriot.com/2013/03/9-patch-technique-in-cocos2d/ for more info. x, y, w, z are left, bottom, right, top coordinate of the resizable box
  13898. * - invertY: if true the texture Y will be inverted, default is false.
  13899. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  13900. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  13901. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  13902. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  13903. * - levelCollision: this primitive is an actor of the Collision Manager and only this level will be used for collision (i.e. not the children). Use deepCollision if you want collision detection on the primitives and its children.
  13904. * - deepCollision: this primitive is an actor of the Collision Manager, this level AND ALSO its children will be used for collision (note: you don't need to set the children as level/deepCollision).
  13905. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  13906. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13907. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13908. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13909. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13910. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  13911. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  13912. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  13913. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  13914. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13915. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13916. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13917. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13918. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  13919. */
  13920. function Sprite2D(texture, settings) {
  13921. var _this;
  13922. if (!settings) {
  13923. settings = {};
  13924. }
  13925. _this = _super.call(this, settings) || this;
  13926. _this.texture = texture;
  13927. // This is removed to let the user the possibility to setup the addressing mode he wants
  13928. //this.texture.wrapU = Texture.CLAMP_ADDRESSMODE;
  13929. //this.texture.wrapV = Texture.CLAMP_ADDRESSMODE;
  13930. _this._useSize = false;
  13931. _this._spriteSize = (settings.spriteSize != null) ? settings.spriteSize.clone() : null;
  13932. _this._spriteLocation = (settings.spriteLocation != null) ? settings.spriteLocation.clone() : new BABYLON.Vector2(0, 0);
  13933. if (settings.size != null) {
  13934. _this.size = settings.size;
  13935. }
  13936. _this.spriteFrame = 0;
  13937. _this.invertY = (settings.invertY == null) ? false : settings.invertY;
  13938. _this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  13939. _this.useAlphaFromTexture = true;
  13940. _this._scale9 = (settings.scale9 != null) ? settings.scale9.clone() : null;
  13941. // If the user doesn't set a size, we'll use the texture's one, but if the texture is not loading, we HAVE to set a temporary dummy size otherwise the positioning engine will switch the marginAlignement to stretch/stretch, and WE DON'T WANT THAT.
  13942. // The fucking delayed texture sprite bug is fixed!
  13943. if (settings.spriteSize == null) {
  13944. _this.spriteSize = new BABYLON.Size(10, 10);
  13945. }
  13946. if (settings.spriteSize == null || !texture.isReady()) {
  13947. if (texture.isReady()) {
  13948. var s = texture.getBaseSize();
  13949. _this.spriteSize = new BABYLON.Size(s.width, s.height);
  13950. _this._updateSpriteScaleFactor();
  13951. }
  13952. else {
  13953. texture.onLoadObservable.add(function () {
  13954. if (settings.spriteSize == null) {
  13955. var s = texture.getBaseSize();
  13956. _this.spriteSize = new BABYLON.Size(s.width, s.height);
  13957. }
  13958. _this._updateSpriteScaleFactor();
  13959. _this._positioningDirty();
  13960. _this._setLayoutDirty();
  13961. _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId | Sprite2D_1.textureProperty.flagId; // To make sure the sprite is issued again for render
  13962. });
  13963. }
  13964. }
  13965. return _this;
  13966. }
  13967. Object.defineProperty(Sprite2D.prototype, "texture", {
  13968. get: function () {
  13969. return this._texture;
  13970. },
  13971. set: function (value) {
  13972. this._texture = value;
  13973. this._oldTextureHasAlpha = this._texture && this.texture.hasAlpha;
  13974. },
  13975. enumerable: true,
  13976. configurable: true
  13977. });
  13978. Object.defineProperty(Sprite2D.prototype, "useAlphaFromTexture", {
  13979. get: function () {
  13980. return this._useAlphaFromTexture;
  13981. },
  13982. set: function (value) {
  13983. if (this._useAlphaFromTexture === value) {
  13984. return;
  13985. }
  13986. this._useAlphaFromTexture = value;
  13987. this._updateRenderMode();
  13988. },
  13989. enumerable: true,
  13990. configurable: true
  13991. });
  13992. Object.defineProperty(Sprite2D.prototype, "size", {
  13993. get: function () {
  13994. if (this._size == null) {
  13995. return this.spriteSize;
  13996. }
  13997. return this.internalGetSize();
  13998. },
  13999. set: function (value) {
  14000. this._useSize = value != null;
  14001. this.internalSetSize(value);
  14002. this._updateSpriteScaleFactor();
  14003. },
  14004. enumerable: true,
  14005. configurable: true
  14006. });
  14007. Object.defineProperty(Sprite2D.prototype, "spriteSize", {
  14008. get: function () {
  14009. return this._spriteSize;
  14010. },
  14011. set: function (value) {
  14012. if (!this._spriteSize) {
  14013. this._spriteSize = value.clone();
  14014. }
  14015. else {
  14016. this._spriteSize.copyFrom(value);
  14017. }
  14018. this._updateSpriteScaleFactor();
  14019. },
  14020. enumerable: true,
  14021. configurable: true
  14022. });
  14023. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  14024. get: function () {
  14025. return this._spriteLocation;
  14026. },
  14027. set: function (value) {
  14028. if (!this._spriteLocation) {
  14029. this._spriteLocation = value.clone();
  14030. }
  14031. else {
  14032. this._spriteLocation.copyFrom(value);
  14033. }
  14034. },
  14035. enumerable: true,
  14036. configurable: true
  14037. });
  14038. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  14039. get: function () {
  14040. return this._spriteFrame;
  14041. },
  14042. set: function (value) {
  14043. this._spriteFrame = value;
  14044. },
  14045. enumerable: true,
  14046. configurable: true
  14047. });
  14048. Object.defineProperty(Sprite2D.prototype, "invertY", {
  14049. get: function () {
  14050. return this._invertY;
  14051. },
  14052. set: function (value) {
  14053. this._invertY = value;
  14054. },
  14055. enumerable: true,
  14056. configurable: true
  14057. });
  14058. Object.defineProperty(Sprite2D.prototype, "isScale9", {
  14059. get: function () {
  14060. return this._scale9 !== null;
  14061. },
  14062. enumerable: true,
  14063. configurable: true
  14064. });
  14065. //@instanceLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, pi => Sprite2D.spriteScaleFactorProperty = pi)
  14066. ///**
  14067. // * Get/set the sprite location (in pixels) in the texture
  14068. // */
  14069. //public get spriteScaleFactor(): Vector2 {
  14070. // return this._spriteScaleFactor;
  14071. //}
  14072. //public set spriteScaleFactor(value: Vector2) {
  14073. // this._spriteScaleFactor = value;
  14074. //}
  14075. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  14076. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  14077. return true;
  14078. };
  14079. /**
  14080. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  14081. */
  14082. Sprite2D.prototype.getAnimatables = function () {
  14083. var res = new Array();
  14084. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  14085. res.push(this.texture);
  14086. }
  14087. return res;
  14088. };
  14089. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  14090. // If we've made it so far it means the boundingInfo intersection test succeed, the Sprite2D is shaped the same, so we always return true
  14091. return true;
  14092. };
  14093. Object.defineProperty(Sprite2D.prototype, "isSizeAuto", {
  14094. get: function () {
  14095. return this.size == null;
  14096. },
  14097. enumerable: true,
  14098. configurable: true
  14099. });
  14100. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  14101. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  14102. return renderCache;
  14103. };
  14104. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  14105. var renderCache = modelRenderCache;
  14106. var engine = this.owner.engine;
  14107. var vb = new Float32Array(4);
  14108. for (var i = 0; i < 4; i++) {
  14109. vb[i] = i;
  14110. }
  14111. renderCache.vb = engine.createVertexBuffer(vb);
  14112. var ib = new Float32Array(6);
  14113. ib[0] = 0;
  14114. ib[1] = 2;
  14115. ib[2] = 1;
  14116. ib[3] = 0;
  14117. ib[4] = 3;
  14118. ib[5] = 2;
  14119. renderCache.ib = engine.createIndexBuffer(ib);
  14120. renderCache.texture = this.texture;
  14121. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  14122. var ei = this.getDataPartEffectInfo(Sprite2D_1.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], true);
  14123. if (ei) {
  14124. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  14125. }
  14126. ei = this.getDataPartEffectInfo(Sprite2D_1.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], false);
  14127. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  14128. return renderCache;
  14129. };
  14130. Sprite2D.prototype.getUsedShaderCategories = function (dataPart) {
  14131. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  14132. if (dataPart.id === Sprite2D_1.SPRITE2D_MAINPARTID) {
  14133. var useScale9 = this._scale9 != null;
  14134. if (useScale9) {
  14135. cat.push(Sprite2D_1.SHAPE2D_CATEGORY_SCALE9);
  14136. }
  14137. }
  14138. return cat;
  14139. };
  14140. Sprite2D.prototype.createInstanceDataParts = function () {
  14141. return [new Sprite2DInstanceData(Sprite2D_1.SPRITE2D_MAINPARTID)];
  14142. };
  14143. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  14144. Sprite2D_1.layoutConstructMode = true;
  14145. };
  14146. // if obj contains something, we restore the _text property
  14147. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  14148. Sprite2D_1.layoutConstructMode = false;
  14149. };
  14150. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  14151. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  14152. return false;
  14153. }
  14154. if (!this.texture.isReady() && !Sprite2D_1.layoutConstructMode) {
  14155. return false;
  14156. }
  14157. if (part.id === Sprite2D_1.SPRITE2D_MAINPARTID) {
  14158. var d = this._instanceDataParts[0];
  14159. if (Sprite2D_1.layoutConstructMode) {
  14160. d.topLeftUV = BABYLON.Vector2.Zero();
  14161. d.sizeUV = BABYLON.Vector2.Zero();
  14162. d.properties = BABYLON.Vector3.Zero();
  14163. d.textureSize = BABYLON.Vector2.Zero();
  14164. d.scaleFactor = BABYLON.Vector2.Zero();
  14165. if (this.isScale9) {
  14166. d.scale9 = BABYLON.Vector4.Zero();
  14167. }
  14168. }
  14169. else {
  14170. var ts = this.texture.getBaseSize();
  14171. var ss = this.spriteSize;
  14172. var sl = this.spriteLocation;
  14173. var ssf = this.actualScale;
  14174. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  14175. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  14176. d.sizeUV = suv;
  14177. d.scaleFactor = ssf;
  14178. Sprite2D_1._prop.x = this.spriteFrame;
  14179. Sprite2D_1._prop.y = this.invertY ? 1 : 0;
  14180. Sprite2D_1._prop.z = this.alignToPixel ? 1 : 0;
  14181. d.properties = Sprite2D_1._prop;
  14182. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  14183. var scale9 = this._scale9;
  14184. if (scale9 != null) {
  14185. var normalizedScale9 = new BABYLON.Vector4(scale9.x * suv.x / ss.width, scale9.y * suv.y / ss.height, scale9.z * suv.x / ss.width, scale9.w * suv.y / ss.height);
  14186. d.scale9 = normalizedScale9;
  14187. }
  14188. }
  14189. }
  14190. return true;
  14191. };
  14192. Sprite2D.prototype._mustUpdateInstance = function () {
  14193. var res = this._oldTextureHasAlpha !== (this.texture != null && this.texture.hasAlpha);
  14194. this._oldTextureHasAlpha = this.texture != null && this.texture.hasAlpha;
  14195. if (res) {
  14196. this._updateRenderMode();
  14197. }
  14198. return res;
  14199. };
  14200. Sprite2D.prototype._useTextureAlpha = function () {
  14201. return this.texture != null && this.texture.hasAlpha;
  14202. };
  14203. Sprite2D.prototype._shouldUseAlphaFromTexture = function () {
  14204. return this.texture != null && this.texture.hasAlpha && this.useAlphaFromTexture;
  14205. };
  14206. Sprite2D.prototype._updateSpriteScaleFactor = function () {
  14207. if (!this._useSize) {
  14208. return;
  14209. }
  14210. var sS = this.spriteSize;
  14211. var s = this.size;
  14212. if (s == null || sS == null) {
  14213. return;
  14214. }
  14215. this._postScale.x = s.width / sS.width;
  14216. this._postScale.y = s.height / sS.height;
  14217. };
  14218. return Sprite2D;
  14219. }(BABYLON.RenderablePrim2D));
  14220. Sprite2D.SPRITE2D_MAINPARTID = 1;
  14221. Sprite2D.SHAPE2D_CATEGORY_SCALE9 = "Scale9";
  14222. Sprite2D._prop = BABYLON.Vector3.Zero();
  14223. Sprite2D.layoutConstructMode = false;
  14224. __decorate([
  14225. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D_1.textureProperty = pi; })
  14226. ], Sprite2D.prototype, "texture", null);
  14227. __decorate([
  14228. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D_1.useAlphaFromTextureProperty = pi; })
  14229. ], Sprite2D.prototype, "useAlphaFromTexture", null);
  14230. __decorate([
  14231. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D_1.spriteSizeProperty = pi; }, false, true)
  14232. ], Sprite2D.prototype, "spriteSize", null);
  14233. __decorate([
  14234. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D_1.spriteLocationProperty = pi; })
  14235. ], Sprite2D.prototype, "spriteLocation", null);
  14236. __decorate([
  14237. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D_1.spriteFrameProperty = pi; })
  14238. ], Sprite2D.prototype, "spriteFrame", null);
  14239. __decorate([
  14240. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Sprite2D_1.invertYProperty = pi; })
  14241. ], Sprite2D.prototype, "invertY", null);
  14242. __decorate([
  14243. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 8, function (pi) { return Sprite2D_1.spriteScale9Property = pi; })
  14244. ], Sprite2D.prototype, "isScale9", null);
  14245. Sprite2D = Sprite2D_1 = __decorate([
  14246. BABYLON.className("Sprite2D", "BABYLON")
  14247. ], Sprite2D);
  14248. BABYLON.Sprite2D = Sprite2D;
  14249. var Sprite2DInstanceData = (function (_super) {
  14250. __extends(Sprite2DInstanceData, _super);
  14251. function Sprite2DInstanceData(partId) {
  14252. return _super.call(this, partId, 1) || this;
  14253. }
  14254. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  14255. get: function () {
  14256. return null;
  14257. },
  14258. set: function (value) {
  14259. },
  14260. enumerable: true,
  14261. configurable: true
  14262. });
  14263. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  14264. get: function () {
  14265. return null;
  14266. },
  14267. set: function (value) {
  14268. },
  14269. enumerable: true,
  14270. configurable: true
  14271. });
  14272. Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
  14273. get: function () {
  14274. return null;
  14275. },
  14276. set: function (value) {
  14277. },
  14278. enumerable: true,
  14279. configurable: true
  14280. });
  14281. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  14282. get: function () {
  14283. return null;
  14284. },
  14285. set: function (value) {
  14286. },
  14287. enumerable: true,
  14288. configurable: true
  14289. });
  14290. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  14291. // 3 floats being:
  14292. // - x: frame number to display
  14293. // - y: invertY setting
  14294. // - z: alignToPixel setting
  14295. get: function () {
  14296. return null;
  14297. },
  14298. set: function (value) {
  14299. },
  14300. enumerable: true,
  14301. configurable: true
  14302. });
  14303. Object.defineProperty(Sprite2DInstanceData.prototype, "scale9", {
  14304. get: function () {
  14305. return null;
  14306. },
  14307. set: function (value) {
  14308. },
  14309. enumerable: true,
  14310. configurable: true
  14311. });
  14312. return Sprite2DInstanceData;
  14313. }(BABYLON.InstanceDataBase));
  14314. __decorate([
  14315. BABYLON.instanceData()
  14316. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  14317. __decorate([
  14318. BABYLON.instanceData()
  14319. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  14320. __decorate([
  14321. BABYLON.instanceData(Sprite2D.SHAPE2D_CATEGORY_SCALE9)
  14322. ], Sprite2DInstanceData.prototype, "scaleFactor", null);
  14323. __decorate([
  14324. BABYLON.instanceData()
  14325. ], Sprite2DInstanceData.prototype, "textureSize", null);
  14326. __decorate([
  14327. BABYLON.instanceData()
  14328. ], Sprite2DInstanceData.prototype, "properties", null);
  14329. __decorate([
  14330. BABYLON.instanceData(Sprite2D.SHAPE2D_CATEGORY_SCALE9)
  14331. ], Sprite2DInstanceData.prototype, "scale9", null);
  14332. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  14333. var Sprite2D_1;
  14334. })(BABYLON || (BABYLON = {}));
  14335. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  14336. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  14337. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  14338. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  14339. return c > 3 && r && Object.defineProperty(target, key, r), r;
  14340. };
  14341. var BABYLON;
  14342. (function (BABYLON) {
  14343. /**
  14344. * This class will contains information about a sub picture present in an Atlas Picture.
  14345. */
  14346. var AtlasSubPictureInfo = (function () {
  14347. function AtlasSubPictureInfo() {
  14348. }
  14349. return AtlasSubPictureInfo;
  14350. }());
  14351. BABYLON.AtlasSubPictureInfo = AtlasSubPictureInfo;
  14352. /**
  14353. * This class represent an Atlas Picture, it contains the information of all the sub pictures and the Texture that stores the bitmap.
  14354. * You get an instance of this class using methods of the AtlasPictureInfoFactory
  14355. */
  14356. var AtlasPictureInfo = (function () {
  14357. function AtlasPictureInfo() {
  14358. }
  14359. /**
  14360. * Creates many sprite from the Atlas Picture
  14361. * @param filterCallback a predicate if true is returned then the corresponding sub picture will be used to create a sprite.
  14362. * The Predicate has many parameters:
  14363. * - index: just an index incremented at each sub picture submitted for Sprite creation
  14364. * - name: the sub picture's name
  14365. * - aspi: the AtlasSubPictureInfo corresponding to the submitted sub picture
  14366. * - settings: the Sprite2D creation settings, you can alter this JSON object but BEWARE, the alterations will be kept for subsequent Sprite2D creations!
  14367. * @param spriteSettings The Sprite2D settings to use for Sprite creation, this JSON object will be passed to the filterCallback for you to alter it, if needed.
  14368. */
  14369. AtlasPictureInfo.prototype.createSprites = function (filterCallback, spriteSettings) {
  14370. var _this = this;
  14371. var res = new Array();
  14372. var index = 0;
  14373. this.subPictures.forEach(function (k, v) {
  14374. if (!filterCallback || filterCallback(index++, k, v, spriteSettings)) {
  14375. var s = _this.createSprite(k, spriteSettings);
  14376. if (s) {
  14377. res.push(s);
  14378. }
  14379. }
  14380. });
  14381. return res;
  14382. };
  14383. /**
  14384. * Create one Sprite from a sub picture
  14385. * @param subPictureName the name of the sub picture to use
  14386. * @param spriteSettings the Sprite2D settings to use for the Sprite instance creation
  14387. */
  14388. AtlasPictureInfo.prototype.createSprite = function (subPictureName, spriteSettings) {
  14389. var spi = this.subPictures.get(subPictureName);
  14390. if (!spi) {
  14391. return null;
  14392. }
  14393. if (!spriteSettings) {
  14394. spriteSettings = {};
  14395. }
  14396. var s = spriteSettings;
  14397. s.id = subPictureName;
  14398. s.spriteLocation = spi.location;
  14399. s.spriteSize = spi.size;
  14400. var sprite = new BABYLON.Sprite2D(this.texture, spriteSettings);
  14401. return sprite;
  14402. };
  14403. return AtlasPictureInfo;
  14404. }());
  14405. BABYLON.AtlasPictureInfo = AtlasPictureInfo;
  14406. /**
  14407. * This if the Factory class containing static method to create Atlas Pictures Info objects or add new loaders
  14408. */
  14409. var AtlasPictureInfoFactory = (function () {
  14410. function AtlasPictureInfoFactory() {
  14411. }
  14412. /**
  14413. * Add a custom loader
  14414. * @param fileExtension must be the file extension (without the dot) of the file that is loaded by this loader (e.g.: json)
  14415. * @param plugin the instance of the loader
  14416. */
  14417. AtlasPictureInfoFactory.addLoader = function (fileExtension, plugin) {
  14418. var a = AtlasPictureInfoFactory.plugins.getOrAddWithFactory(fileExtension.toLocaleLowerCase(), function () { return new Array(); });
  14419. a.push(plugin);
  14420. };
  14421. /**
  14422. * Load an Atlas Picture Info object from a data file at a given url and with a given texture
  14423. * @param texture the texture containing the atlas bitmap
  14424. * @param url the URL of the Atlas Info data file
  14425. * @param onLoad a callback that will be called when the AtlasPictureInfo object will be loaded and ready
  14426. * @param onError a callback that will be called in case of error
  14427. */
  14428. AtlasPictureInfoFactory.loadFromUrl = function (texture, url, onLoad, onError) {
  14429. if (onError === void 0) { onError = null; }
  14430. BABYLON.Tools.LoadFile(url, function (data) {
  14431. var ext = url.split('.').pop().split(/\#|\?/)[0];
  14432. var plugins = AtlasPictureInfoFactory.plugins.get(ext.toLocaleLowerCase());
  14433. if (!plugins) {
  14434. if (onError) {
  14435. onError("couldn't find a plugin for this file extension", -1);
  14436. }
  14437. return;
  14438. }
  14439. for (var _i = 0, plugins_1 = plugins; _i < plugins_1.length; _i++) {
  14440. var p = plugins_1[_i];
  14441. var ret = p.loadFile(data);
  14442. if (ret) {
  14443. if (ret.api) {
  14444. ret.api.texture = texture;
  14445. if (onLoad) {
  14446. onLoad(ret.api);
  14447. }
  14448. }
  14449. else if (onError) {
  14450. onError(ret.errorMsg, ret.errorCode);
  14451. }
  14452. return;
  14453. }
  14454. }
  14455. if (onError) {
  14456. onError("No plugin to load this Atlas Data file format", -1);
  14457. }
  14458. }, null, null, null, function () {
  14459. if (onError) {
  14460. onError("Couldn't load file", -1);
  14461. }
  14462. });
  14463. return null;
  14464. };
  14465. return AtlasPictureInfoFactory;
  14466. }());
  14467. AtlasPictureInfoFactory.plugins = new BABYLON.StringDictionary();
  14468. BABYLON.AtlasPictureInfoFactory = AtlasPictureInfoFactory;
  14469. // Loader class for the TexturePacker's JSON Array data format
  14470. var JSONArrayLoader = JSONArrayLoader_1 = (function () {
  14471. function JSONArrayLoader() {
  14472. }
  14473. JSONArrayLoader.prototype.loadFile = function (content) {
  14474. var errorMsg = null;
  14475. var errorCode = 0;
  14476. var root = null;
  14477. var api = null;
  14478. try {
  14479. var frames_1;
  14480. var meta = void 0;
  14481. try {
  14482. root = JSON.parse(content);
  14483. frames_1 = root.frames;
  14484. meta = root.meta;
  14485. if (!frames_1 || !meta) {
  14486. throw Error("Not a JSON Array file format");
  14487. }
  14488. }
  14489. catch (ex1) {
  14490. return null;
  14491. }
  14492. api = new AtlasPictureInfo();
  14493. api.atlasSize = new BABYLON.Size(meta.size.w, meta.size.h);
  14494. api.subPictures = new BABYLON.StringDictionary();
  14495. for (var _i = 0, frames_2 = frames_1; _i < frames_2.length; _i++) {
  14496. var f = frames_2[_i];
  14497. var aspi = new AtlasSubPictureInfo();
  14498. aspi.name = f.filename;
  14499. aspi.location = new BABYLON.Vector2(f.frame.x, api.atlasSize.height - (f.frame.y + f.frame.h));
  14500. aspi.size = new BABYLON.Size(f.frame.w, f.frame.h);
  14501. api.subPictures.add(aspi.name, aspi);
  14502. }
  14503. }
  14504. catch (ex2) {
  14505. errorMsg = "Unknown Exception: " + ex2;
  14506. errorCode = -2;
  14507. }
  14508. return { api: api, errorMsg: errorMsg, errorCode: errorCode };
  14509. };
  14510. return JSONArrayLoader;
  14511. }());
  14512. JSONArrayLoader = JSONArrayLoader_1 = __decorate([
  14513. AtlasLoaderPlugin("json", new JSONArrayLoader_1())
  14514. ], JSONArrayLoader);
  14515. /**
  14516. * Use this decorator when you declare an Atlas Loader Class for the loader to register itself automatically.
  14517. * @param fileExtension the extension of the file that the plugin is loading (there can be many plugin for the same extension)
  14518. * @param plugin an instance of the plugin class to add to the AtlasPictureInfoFactory
  14519. */
  14520. function AtlasLoaderPlugin(fileExtension, plugin) {
  14521. return function () {
  14522. AtlasPictureInfoFactory.addLoader(fileExtension, plugin);
  14523. };
  14524. }
  14525. BABYLON.AtlasLoaderPlugin = AtlasLoaderPlugin;
  14526. var JSONArrayLoader_1;
  14527. })(BABYLON || (BABYLON = {}));
  14528. var __extends = (this && this.__extends) || function (d, b) {
  14529. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14530. function __() { this.constructor = d; }
  14531. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  14532. };
  14533. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  14534. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  14535. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  14536. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  14537. return c > 3 && r && Object.defineProperty(target, key, r), r;
  14538. };
  14539. var BABYLON;
  14540. (function (BABYLON) {
  14541. var Text2DRenderCache = (function (_super) {
  14542. __extends(Text2DRenderCache, _super);
  14543. function Text2DRenderCache() {
  14544. var _this = _super.apply(this, arguments) || this;
  14545. _this.effectsReady = false;
  14546. _this.vb = null;
  14547. _this.ib = null;
  14548. _this.instancingAttributes = null;
  14549. _this.fontTexture = null;
  14550. _this.effect = null;
  14551. _this.effectInstanced = null;
  14552. _this.fontPremulAlpha = false;
  14553. return _this;
  14554. }
  14555. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  14556. // Do nothing if the shader is still loading/preparing
  14557. if (!this.effectsReady) {
  14558. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  14559. return false;
  14560. }
  14561. this.effectsReady = true;
  14562. }
  14563. var canvas = instanceInfo.owner.owner;
  14564. var engine = canvas.engine;
  14565. this.fontTexture.update();
  14566. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  14567. engine.enableEffect(effect);
  14568. effect.setTexture("diffuseSampler", this.fontTexture);
  14569. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  14570. var sdf = this.fontTexture.isSignedDistanceField;
  14571. // Enable alpha mode only if the texture is not using SDF, SDF is rendered in AlphaTest mode, which mean no alpha blend
  14572. var curAlphaMode;
  14573. if (!sdf) {
  14574. curAlphaMode = engine.getAlphaMode();
  14575. engine.setAlphaMode(this.fontPremulAlpha ? BABYLON.Engine.ALPHA_PREMULTIPLIED : BABYLON.Engine.ALPHA_COMBINE, true);
  14576. }
  14577. var pid = context.groupInfoPartData[0];
  14578. if (context.useInstancing) {
  14579. if (!this.instancingAttributes) {
  14580. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  14581. }
  14582. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  14583. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  14584. canvas._addDrawCallCount(1, context.renderMode);
  14585. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  14586. engine.draw(true, 0, 6, count);
  14587. engine.unbindInstanceAttributes();
  14588. }
  14589. else {
  14590. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  14591. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  14592. this.setupUniforms(effect, 0, pid._partData, i);
  14593. engine.draw(true, 0, 6);
  14594. }
  14595. }
  14596. if (!sdf) {
  14597. engine.setAlphaMode(curAlphaMode, true);
  14598. }
  14599. return true;
  14600. };
  14601. Text2DRenderCache.prototype.dispose = function () {
  14602. if (!_super.prototype.dispose.call(this)) {
  14603. return false;
  14604. }
  14605. if (this.vb) {
  14606. this._engine._releaseBuffer(this.vb);
  14607. this.vb = null;
  14608. }
  14609. if (this.ib) {
  14610. this._engine._releaseBuffer(this.ib);
  14611. this.ib = null;
  14612. }
  14613. if (this.fontTexture) {
  14614. this.fontTexture.decCachedFontTextureCounter();
  14615. this.fontTexture = null;
  14616. }
  14617. this.effect = null;
  14618. this.effectInstanced = null;
  14619. return true;
  14620. };
  14621. return Text2DRenderCache;
  14622. }(BABYLON.ModelRenderCache));
  14623. BABYLON.Text2DRenderCache = Text2DRenderCache;
  14624. var Text2DInstanceData = (function (_super) {
  14625. __extends(Text2DInstanceData, _super);
  14626. function Text2DInstanceData(partId, dataElementCount) {
  14627. return _super.call(this, partId, dataElementCount) || this;
  14628. }
  14629. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  14630. get: function () {
  14631. return null;
  14632. },
  14633. set: function (value) {
  14634. },
  14635. enumerable: true,
  14636. configurable: true
  14637. });
  14638. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  14639. get: function () {
  14640. return null;
  14641. },
  14642. set: function (value) {
  14643. },
  14644. enumerable: true,
  14645. configurable: true
  14646. });
  14647. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  14648. get: function () {
  14649. return null;
  14650. },
  14651. set: function (value) {
  14652. },
  14653. enumerable: true,
  14654. configurable: true
  14655. });
  14656. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  14657. get: function () {
  14658. return null;
  14659. },
  14660. set: function (value) {
  14661. },
  14662. enumerable: true,
  14663. configurable: true
  14664. });
  14665. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  14666. get: function () {
  14667. return null;
  14668. },
  14669. set: function (value) {
  14670. },
  14671. enumerable: true,
  14672. configurable: true
  14673. });
  14674. return Text2DInstanceData;
  14675. }(BABYLON.InstanceDataBase));
  14676. __decorate([
  14677. BABYLON.instanceData()
  14678. ], Text2DInstanceData.prototype, "topLeftUV", null);
  14679. __decorate([
  14680. BABYLON.instanceData()
  14681. ], Text2DInstanceData.prototype, "sizeUV", null);
  14682. __decorate([
  14683. BABYLON.instanceData()
  14684. ], Text2DInstanceData.prototype, "textureSize", null);
  14685. __decorate([
  14686. BABYLON.instanceData()
  14687. ], Text2DInstanceData.prototype, "color", null);
  14688. __decorate([
  14689. BABYLON.instanceData()
  14690. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  14691. BABYLON.Text2DInstanceData = Text2DInstanceData;
  14692. var Text2D = Text2D_1 = (function (_super) {
  14693. __extends(Text2D, _super);
  14694. /**
  14695. * Create a Text primitive
  14696. * @param text the text to display
  14697. * @param settings a combination of settings, possible ones are
  14698. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  14699. * - children: an array of direct children
  14700. * - id a text identifier, for information purpose
  14701. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  14702. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  14703. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  14704. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  14705. * - alignToPixel: if true the primitive will be aligned to the target rendering device's pixel
  14706. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  14707. * - zOrder: override the zOrder with the specified value
  14708. * - origin: define the normalized origin point location, default [0.5;0.5]
  14709. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  14710. * - fontSuperSample: if true the text will be rendered with a superSampled font (the font is twice the given size). Use this settings if the text lies in world space or if it's scaled in.
  14711. * - signedDistanceField: if true the text will be rendered using the SignedDistanceField technique. This technique has the advantage to be rendered order independent (then much less drawing calls), but only works on font that are a little more than one pixel wide on the screen but the rendering quality is excellent whatever the font size is on the screen (which is the purpose of this technique). Outlining/Shadow is not supported right now. If you can, you should use this mode, the quality and the performances are the best. Note that fontSuperSample has no effect when this mode is on.
  14712. * - bitmapFontTexture: set a BitmapFontTexture to use instead of a fontName.
  14713. * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white.
  14714. * - useBilinearFiltering: if true a FontTexture using Bilinear filtering will be used, if false a FontTexture using Nearest filtering will be used. If not specified then bilinear will be chosen for Signed Distance Field mode or a Text2D inside a WorldSpaceCanvas2D, otherwise nearest will be chose.
  14715. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  14716. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  14717. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  14718. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  14719. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  14720. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  14721. * - levelCollision: this primitive is an actor of the Collision Manager and only this level will be used for collision (i.e. not the children). Use deepCollision if you want collision detection on the primitives and its children.
  14722. * - deepCollision: this primitive is an actor of the Collision Manager, this level AND ALSO its children will be used for collision (note: you don't need to set the children as level/deepCollision).
  14723. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  14724. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14725. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14726. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14727. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14728. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  14729. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  14730. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  14731. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  14732. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14733. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14734. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14735. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14736. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  14737. * - textAlignmentH: align text horizontally (Text2D.AlignLeft, Text2D.AlignCenter, Text2D.AlignRight)
  14738. * - textAlignmentV: align text vertically (Text2D.AlignTop, Text2D.AlignCenter, Text2D.AlignBottom)
  14739. * - textAlignment: a string defining the text alignment, text can be: [<h:|horizontal:><left|right|center>], [<v:|vertical:><top|bottom|center>]
  14740. * - wordWrap: if true the text will wrap inside content area
  14741. */
  14742. function Text2D(text, settings) {
  14743. var _this;
  14744. if (!settings) {
  14745. settings = {};
  14746. }
  14747. _this = _super.call(this, settings) || this;
  14748. if (settings.bitmapFontTexture != null) {
  14749. _this._fontTexture = settings.bitmapFontTexture;
  14750. _this._fontName = null;
  14751. _this._fontSuperSample = false;
  14752. _this._fontSDF = false;
  14753. _this._textureIsPremulAlpha = _this._fontTexture.isPremultipliedAlpha;
  14754. var ft = _this._fontTexture;
  14755. if (ft != null && !ft.isReady()) {
  14756. ft.onLoadObservable.add(function () {
  14757. _this._positioningDirty();
  14758. _this._setLayoutDirty();
  14759. _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId; // To make sure the Text2D is issued again for render
  14760. });
  14761. }
  14762. }
  14763. else {
  14764. _this._fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  14765. _this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  14766. _this._fontSDF = (settings.fontSignedDistanceField != null && settings.fontSignedDistanceField);
  14767. }
  14768. _this._defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor.clone();
  14769. _this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  14770. _this._textureIsPremulAlpha = true; //settings.fontTexturePremulAlpha === true;
  14771. _this._textSize = null;
  14772. _this.text = text;
  14773. if (settings.size != null) {
  14774. _this.size = settings.size;
  14775. _this._sizeSetByUser = true;
  14776. }
  14777. else {
  14778. _this.size = null;
  14779. }
  14780. _this._useBilinearFiltering = (settings.useBilinearFiltering != null) ? settings.useBilinearFiltering : null;
  14781. // Text rendering must always be aligned to the target's pixel to ensure a good quality
  14782. _this.alignToPixel = true;
  14783. _this.textAlignmentH = (settings.textAlignmentH == null) ? Text2D_1.AlignLeft : settings.textAlignmentH;
  14784. _this.textAlignmentV = (settings.textAlignmentV == null) ? Text2D_1.AlignTop : settings.textAlignmentV;
  14785. _this.textAlignment = (settings.textAlignment == null) ? "" : settings.textAlignment;
  14786. _this._wordWrap = (settings.wordWrap == null) ? false : settings.wordWrap;
  14787. _this._updateRenderMode();
  14788. return _this;
  14789. }
  14790. Object.defineProperty(Text2D, "AlignLeft", {
  14791. /**
  14792. * Alignment is made relative to the left edge of the Content Area. Valid for horizontal alignment only.
  14793. */
  14794. get: function () { return Text2D_1._AlignLeft; },
  14795. enumerable: true,
  14796. configurable: true
  14797. });
  14798. Object.defineProperty(Text2D, "AlignTop", {
  14799. /**
  14800. * Alignment is made relative to the top edge of the Content Area. Valid for vertical alignment only.
  14801. */
  14802. get: function () { return Text2D_1._AlignTop; },
  14803. enumerable: true,
  14804. configurable: true
  14805. });
  14806. Object.defineProperty(Text2D, "AlignRight", {
  14807. /**
  14808. * Alignment is made relative to the right edge of the Content Area. Valid for horizontal alignment only.
  14809. */
  14810. get: function () { return Text2D_1._AlignRight; },
  14811. enumerable: true,
  14812. configurable: true
  14813. });
  14814. Object.defineProperty(Text2D, "AlignBottom", {
  14815. /**
  14816. * Alignment is made relative to the bottom edge of the Content Area. Valid for vertical alignment only.
  14817. */
  14818. get: function () { return Text2D_1._AlignBottom; },
  14819. enumerable: true,
  14820. configurable: true
  14821. });
  14822. Object.defineProperty(Text2D, "AlignCenter", {
  14823. /**
  14824. * Alignment is made to center the text from equal distance to the opposite edges of the Content Area
  14825. */
  14826. get: function () { return Text2D_1._AlignCenter; },
  14827. enumerable: true,
  14828. configurable: true
  14829. });
  14830. Object.defineProperty(Text2D.prototype, "fontName", {
  14831. get: function () {
  14832. return this._fontName;
  14833. },
  14834. set: function (value) {
  14835. if (this._fontName) {
  14836. throw new Error("Font Name change is not supported right now.");
  14837. }
  14838. this._fontName = value;
  14839. },
  14840. enumerable: true,
  14841. configurable: true
  14842. });
  14843. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  14844. get: function () {
  14845. return this._defaultFontColor;
  14846. },
  14847. set: function (value) {
  14848. if (!this._defaultFontColor) {
  14849. this._defaultFontColor = value.clone();
  14850. }
  14851. else {
  14852. this._defaultFontColor.copyFrom(value);
  14853. }
  14854. },
  14855. enumerable: true,
  14856. configurable: true
  14857. });
  14858. Object.defineProperty(Text2D.prototype, "text", {
  14859. get: function () {
  14860. return this._text;
  14861. },
  14862. set: function (value) {
  14863. if (!value) {
  14864. value = "";
  14865. }
  14866. this._text = value;
  14867. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  14868. if (!this._sizeSetByUser) {
  14869. this._size = null;
  14870. this._actualSize = null;
  14871. }
  14872. this._updateCharCount();
  14873. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  14874. var s = this.textSize;
  14875. },
  14876. enumerable: true,
  14877. configurable: true
  14878. });
  14879. Object.defineProperty(Text2D.prototype, "size", {
  14880. get: function () {
  14881. if (this._size != null) {
  14882. return this._size;
  14883. }
  14884. return this.textSize;
  14885. },
  14886. set: function (value) {
  14887. this.internalSetSize(value);
  14888. },
  14889. enumerable: true,
  14890. configurable: true
  14891. });
  14892. Object.defineProperty(Text2D.prototype, "fontSuperSample", {
  14893. get: function () {
  14894. return this._fontTexture && this._fontTexture.isSuperSampled;
  14895. },
  14896. enumerable: true,
  14897. configurable: true
  14898. });
  14899. Object.defineProperty(Text2D.prototype, "fontSignedDistanceField", {
  14900. get: function () {
  14901. return this._fontTexture && this._fontTexture.isSignedDistanceField;
  14902. },
  14903. enumerable: true,
  14904. configurable: true
  14905. });
  14906. Object.defineProperty(Text2D.prototype, "textureIsPremulAlpha", {
  14907. get: function () {
  14908. return this._textureIsPremulAlpha;
  14909. },
  14910. set: function (value) {
  14911. this._textureIsPremulAlpha = value;
  14912. },
  14913. enumerable: true,
  14914. configurable: true
  14915. });
  14916. Object.defineProperty(Text2D.prototype, "isSizeAuto", {
  14917. get: function () {
  14918. return false;
  14919. },
  14920. enumerable: true,
  14921. configurable: true
  14922. });
  14923. Object.defineProperty(Text2D.prototype, "isVerticalSizeAuto", {
  14924. get: function () {
  14925. return false;
  14926. },
  14927. enumerable: true,
  14928. configurable: true
  14929. });
  14930. Object.defineProperty(Text2D.prototype, "isHorizontalSizeAuto", {
  14931. get: function () {
  14932. return false;
  14933. },
  14934. enumerable: true,
  14935. configurable: true
  14936. });
  14937. Object.defineProperty(Text2D.prototype, "textSize", {
  14938. /**
  14939. * Get the area that bounds the text associated to the primitive
  14940. */
  14941. get: function () {
  14942. if (!this._textSize) {
  14943. if (this.owner && this._text) {
  14944. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  14945. if (!newSize.equals(this._textSize)) {
  14946. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  14947. this._positioningDirty();
  14948. }
  14949. this._textSize = newSize;
  14950. }
  14951. else {
  14952. return Text2D_1.nullSize;
  14953. }
  14954. }
  14955. return this._textSize;
  14956. },
  14957. enumerable: true,
  14958. configurable: true
  14959. });
  14960. Text2D.prototype.onSetOwner = function () {
  14961. if (!this._textSize) {
  14962. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  14963. this._setLayoutDirty();
  14964. this._positioningDirty();
  14965. this._actualSize = null;
  14966. this._setFlags(BABYLON.SmartPropertyPrim.flagLevelBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  14967. }
  14968. };
  14969. Object.defineProperty(Text2D.prototype, "fontTexture", {
  14970. get: function () {
  14971. if (this._fontTexture) {
  14972. return this._fontTexture;
  14973. }
  14974. if (this.fontName == null || this.owner == null || this.owner.scene == null) {
  14975. return null;
  14976. }
  14977. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample, this._fontSDF, (this._useBilinearFiltering === null) ? (this.owner instanceof BABYLON.WorldSpaceCanvas2D) : this._useBilinearFiltering);
  14978. this._textureIsPremulAlpha = this._fontTexture.isPremultipliedAlpha;
  14979. return this._fontTexture;
  14980. },
  14981. enumerable: true,
  14982. configurable: true
  14983. });
  14984. /**
  14985. * Dispose the primitive, remove it from its parent
  14986. */
  14987. Text2D.prototype.dispose = function () {
  14988. if (!_super.prototype.dispose.call(this)) {
  14989. return false;
  14990. }
  14991. if (this._fontTexture) {
  14992. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample, this._fontSDF, this._fontTexture._samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  14993. this._fontTexture = null;
  14994. }
  14995. return true;
  14996. };
  14997. Text2D.prototype.updateLevelBoundingInfo = function () {
  14998. if (!this.owner || !this._text) {
  14999. return false;
  15000. }
  15001. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  15002. return true;
  15003. };
  15004. Object.defineProperty(Text2D.prototype, "textAlignment", {
  15005. /**
  15006. * You can get/set the text alignment through this property
  15007. */
  15008. get: function () {
  15009. return this._textAlignment;
  15010. },
  15011. set: function (value) {
  15012. this._textAlignment = value;
  15013. this._setTextAlignmentfromString(value);
  15014. },
  15015. enumerable: true,
  15016. configurable: true
  15017. });
  15018. Text2D.prototype.levelIntersect = function (intersectInfo) {
  15019. // For now I can't do something better that boundingInfo is a hit, detecting an intersection on a particular letter would be possible, but do we really need it? Not for now...
  15020. return true;
  15021. };
  15022. Text2D.prototype.createModelRenderCache = function (modelKey) {
  15023. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  15024. return renderCache;
  15025. };
  15026. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  15027. var renderCache = modelRenderCache;
  15028. var engine = this.owner.engine;
  15029. renderCache.fontTexture = this.fontTexture;
  15030. renderCache.fontTexture.incCachedFontTextureCounter();
  15031. renderCache.fontPremulAlpha = this.textureIsPremulAlpha;
  15032. var vb = new Float32Array(4);
  15033. for (var i = 0; i < 4; i++) {
  15034. vb[i] = i;
  15035. }
  15036. renderCache.vb = engine.createVertexBuffer(vb);
  15037. var ib = new Float32Array(6);
  15038. ib[0] = 0;
  15039. ib[1] = 2;
  15040. ib[2] = 1;
  15041. ib[3] = 0;
  15042. ib[4] = 3;
  15043. ib[5] = 2;
  15044. renderCache.ib = engine.createIndexBuffer(ib);
  15045. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  15046. var ei = this.getDataPartEffectInfo(Text2D_1.TEXT2D_MAINPARTID, ["index"], null, true);
  15047. if (ei) {
  15048. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  15049. }
  15050. ei = this.getDataPartEffectInfo(Text2D_1.TEXT2D_MAINPARTID, ["index"], null, false);
  15051. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  15052. return renderCache;
  15053. };
  15054. Text2D.prototype.createInstanceDataParts = function () {
  15055. return [new Text2DInstanceData(Text2D_1.TEXT2D_MAINPARTID, this._charCount)];
  15056. };
  15057. // Looks like a hack!? Yes! Because that's what it is!
  15058. // For the InstanceData layer to compute correctly we need to set all the properties involved, which won't be the case if there's no text
  15059. // This method is called before the layout construction for us to detect this case, set some text and return the initial one to restore it after (there can be some text without char to display, say "\t\n" for instance)
  15060. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  15061. if (!this._charCount) {
  15062. var curText = this._text;
  15063. this.text = "A";
  15064. return curText;
  15065. }
  15066. };
  15067. // if obj contains something, we restore the _text property
  15068. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  15069. if (obj !== undefined) {
  15070. this.text = obj;
  15071. }
  15072. };
  15073. Text2D.prototype.getUsedShaderCategories = function (dataPart) {
  15074. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  15075. if (this._fontSDF) {
  15076. cat.push(Text2D_1.TEXT2D_CATEGORY_SDF);
  15077. }
  15078. if (this._fontTexture instanceof BABYLON.FontTexture) {
  15079. cat.push(Text2D_1.TEXT2D_CATEGORY_FONTTEXTURE);
  15080. }
  15081. return cat;
  15082. };
  15083. Text2D.prototype.refreshInstanceDataPart = function (part) {
  15084. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  15085. return false;
  15086. }
  15087. if (part.id === Text2D_1.TEXT2D_MAINPARTID) {
  15088. var d = part;
  15089. var texture = this.fontTexture;
  15090. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  15091. var ts = texture.getSize();
  15092. var offset = BABYLON.Vector2.Zero();
  15093. var lh = this.fontTexture.lineHeight;
  15094. d.dataElementCount = this._charCount;
  15095. d.curElement = 0;
  15096. var lineLengths = [];
  15097. var charWidths = [];
  15098. var charsPerLine = [];
  15099. var numCharsCurrenLine = 0;
  15100. var contentAreaWidth = this.contentArea.width;
  15101. var contentAreaHeight = this.contentArea.height;
  15102. var numCharsCurrentWord = 0;
  15103. var widthCurrentWord = 0;
  15104. var numWordsPerLine = 0;
  15105. var text = this.text;
  15106. var tabWidth = this._tabulationSize * texture.spaceWidth;
  15107. // First pass: analyze the text to build data like pixel length of each lines, width of each char, number of char per line
  15108. for (var i_1 = 0; i_1 < text.length; i_1++) {
  15109. var char = text[i_1];
  15110. numCharsCurrenLine++;
  15111. charWidths[i_1] = 0;
  15112. // Line feed
  15113. if (this._isWhiteSpaceCharVert(char)) {
  15114. lineLengths.push(offset.x);
  15115. charsPerLine.push(numCharsCurrenLine - 1);
  15116. numCharsCurrenLine = 1;
  15117. offset.x = 0;
  15118. if (widthCurrentWord > 0) {
  15119. numWordsPerLine++;
  15120. }
  15121. numWordsPerLine = 0;
  15122. numCharsCurrentWord = 0;
  15123. widthCurrentWord = 0;
  15124. continue;
  15125. }
  15126. var ci = texture.getChar(char);
  15127. var charWidth = 0;
  15128. if (char === "\t") {
  15129. charWidth = tabWidth;
  15130. }
  15131. else {
  15132. charWidth = ci.xAdvance;
  15133. }
  15134. offset.x += charWidth;
  15135. charWidths[i_1] = charWidth;
  15136. if (this._isWhiteSpaceCharHoriz(char)) {
  15137. if (widthCurrentWord > 0) {
  15138. numWordsPerLine++;
  15139. }
  15140. numCharsCurrentWord = 0;
  15141. widthCurrentWord = 0;
  15142. }
  15143. else {
  15144. widthCurrentWord += ci.xAdvance;
  15145. numCharsCurrentWord++;
  15146. }
  15147. if (this._wordWrap && numWordsPerLine > 0 && offset.x > contentAreaWidth) {
  15148. lineLengths.push(offset.x - widthCurrentWord);
  15149. numCharsCurrenLine -= numCharsCurrentWord;
  15150. var j = i_1 - numCharsCurrentWord;
  15151. //skip white space at the end of this line
  15152. while (this._isWhiteSpaceCharHoriz(text[j])) {
  15153. lineLengths[lineLengths.length - 1] -= charWidths[j];
  15154. j--;
  15155. }
  15156. charsPerLine.push(numCharsCurrenLine);
  15157. if (this._isWhiteSpaceCharHoriz(text[i_1])) {
  15158. //skip white space at the beginning of next line
  15159. var numSpaces = 0;
  15160. while (this._isWhiteSpaceCharHoriz(text[i_1 + numSpaces])) {
  15161. numSpaces++;
  15162. charWidths[i_1 + numSpaces] = 0;
  15163. }
  15164. i_1 += numSpaces - 1;
  15165. offset.x = 0;
  15166. numCharsCurrenLine = numSpaces - 1;
  15167. }
  15168. else {
  15169. numCharsCurrenLine = numCharsCurrentWord;
  15170. offset.x = widthCurrentWord;
  15171. }
  15172. numWordsPerLine = 0;
  15173. }
  15174. }
  15175. lineLengths.push(offset.x);
  15176. charsPerLine.push(numCharsCurrenLine);
  15177. //skip white space at the end
  15178. var i = text.length - 1;
  15179. while (this._isWhiteSpaceCharHoriz(text[i])) {
  15180. lineLengths[lineLengths.length - 1] -= charWidths[i];
  15181. i--;
  15182. }
  15183. var charNum = 0;
  15184. var maxLineLen = 0;
  15185. var alignH = this.textAlignmentH;
  15186. var alignV = this.textAlignmentV;
  15187. offset.x = 0;
  15188. if (alignH == Text2D_1.AlignRight || alignH == Text2D_1.AlignCenter) {
  15189. for (var i_2 = 0; i_2 < lineLengths.length; i_2++) {
  15190. if (lineLengths[i_2] > maxLineLen) {
  15191. maxLineLen = lineLengths[i_2];
  15192. }
  15193. }
  15194. }
  15195. var textHeight = lineLengths.length * lh;
  15196. var offsetX = this.padding.leftPixels;
  15197. if (alignH == Text2D_1.AlignRight) {
  15198. offsetX += contentAreaWidth - maxLineLen;
  15199. }
  15200. else if (alignH == Text2D_1.AlignCenter) {
  15201. offsetX += (contentAreaWidth - maxLineLen) * .5;
  15202. }
  15203. offset.x += offsetX;
  15204. offset.y += contentAreaHeight + textHeight - lh;
  15205. offset.y += this.padding.bottomPixels;
  15206. if (alignV == Text2D_1.AlignBottom) {
  15207. offset.y -= contentAreaHeight;
  15208. }
  15209. else if (alignV == Text2D_1.AlignCenter) {
  15210. offset.y -= (contentAreaHeight - textHeight) * .5 + lineLengths.length * lh;
  15211. }
  15212. else {
  15213. offset.y -= lineLengths.length * lh;
  15214. }
  15215. var lineHeight = texture.lineHeight;
  15216. for (var i_3 = 0; i_3 < lineLengths.length; i_3++) {
  15217. var numChars = charsPerLine[i_3];
  15218. var lineLength = lineLengths[i_3];
  15219. if (alignH == Text2D_1.AlignRight) {
  15220. offset.x += maxLineLen - lineLength;
  15221. }
  15222. else if (alignH == Text2D_1.AlignCenter) {
  15223. offset.x += (maxLineLen - lineLength) * .5;
  15224. }
  15225. for (var j = 0; j < numChars; j++) {
  15226. var char = text[charNum];
  15227. var charWidth = charWidths[charNum];
  15228. if (char !== "\t" && !this._isWhiteSpaceCharVert(char)) {
  15229. //make sure space char gets processed here or overlapping can occur when text is set
  15230. var ci = texture.getChar(char);
  15231. this.updateInstanceDataPart(d, new BABYLON.Vector2(offset.x + ci.xOffset, offset.y + ci.yOffset));
  15232. d.topLeftUV = ci.topLeftUV;
  15233. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  15234. d.sizeUV = suv;
  15235. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  15236. d.color = this.defaultFontColor;
  15237. d.superSampleFactor = superSampleFactor;
  15238. ++d.curElement;
  15239. }
  15240. offset.x += charWidth;
  15241. charNum++;
  15242. }
  15243. offset.x = offsetX;
  15244. offset.y -= lineHeight;
  15245. }
  15246. }
  15247. return true;
  15248. };
  15249. Text2D.prototype._isWhiteSpaceCharHoriz = function (char) {
  15250. if (char === " " || char === "\t") {
  15251. return true;
  15252. }
  15253. };
  15254. Text2D.prototype._isWhiteSpaceCharVert = function (char) {
  15255. if (char === "\n" || char === "\r") {
  15256. return true;
  15257. }
  15258. };
  15259. Text2D.prototype._updateCharCount = function () {
  15260. var count = 0;
  15261. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  15262. var char = _a[_i];
  15263. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  15264. continue;
  15265. }
  15266. ++count;
  15267. }
  15268. this._charCount = count;
  15269. };
  15270. Text2D.prototype._setTextAlignmentfromString = function (value) {
  15271. var m = value.trim().split(",");
  15272. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  15273. var v = m_1[_i];
  15274. v = v.toLocaleLowerCase().trim();
  15275. // Horizontal
  15276. var i = v.indexOf("h:");
  15277. if (i === -1) {
  15278. i = v.indexOf("horizontal:");
  15279. }
  15280. if (i !== -1) {
  15281. v = v.substr(v.indexOf(":") + 1);
  15282. this._setTextAlignmentHorizontal(v);
  15283. continue;
  15284. }
  15285. // Vertical
  15286. i = v.indexOf("v:");
  15287. if (i === -1) {
  15288. i = v.indexOf("vertical:");
  15289. }
  15290. if (i !== -1) {
  15291. v = v.substr(v.indexOf(":") + 1);
  15292. this._setTextAlignmentVertical(v);
  15293. continue;
  15294. }
  15295. }
  15296. };
  15297. Text2D.prototype._setTextAlignmentHorizontal = function (text) {
  15298. var v = text.trim().toLocaleLowerCase();
  15299. switch (v) {
  15300. case "left":
  15301. this.textAlignmentH = Text2D_1.AlignLeft;
  15302. return;
  15303. case "right":
  15304. this.textAlignmentH = Text2D_1.AlignRight;
  15305. return;
  15306. case "center":
  15307. this.textAlignmentH = Text2D_1.AlignCenter;
  15308. return;
  15309. }
  15310. };
  15311. Text2D.prototype._setTextAlignmentVertical = function (text) {
  15312. var v = text.trim().toLocaleLowerCase();
  15313. switch (v) {
  15314. case "top":
  15315. this.textAlignmentV = Text2D_1.AlignTop;
  15316. return;
  15317. case "bottom":
  15318. this.textAlignmentV = Text2D_1.AlignBottom;
  15319. return;
  15320. case "center":
  15321. this.textAlignmentV = Text2D_1.AlignCenter;
  15322. return;
  15323. }
  15324. };
  15325. Text2D.prototype._useTextureAlpha = function () {
  15326. return this._fontSDF;
  15327. };
  15328. Text2D.prototype._shouldUseAlphaFromTexture = function () {
  15329. return !this._fontSDF;
  15330. };
  15331. return Text2D;
  15332. }(BABYLON.RenderablePrim2D));
  15333. Text2D.TEXT2D_MAINPARTID = 1;
  15334. Text2D.TEXT2D_CATEGORY_SDF = "SignedDistanceField";
  15335. Text2D.TEXT2D_CATEGORY_FONTTEXTURE = "FontTexture";
  15336. Text2D._AlignLeft = 1;
  15337. Text2D._AlignTop = 1; // Same as left
  15338. Text2D._AlignRight = 2;
  15339. Text2D._AlignBottom = 2; // Same as right
  15340. Text2D._AlignCenter = 3;
  15341. __decorate([
  15342. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D_1.fontProperty = pi; }, false, true)
  15343. ], Text2D.prototype, "fontName", null);
  15344. __decorate([
  15345. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D_1.defaultFontColorProperty = pi; })
  15346. ], Text2D.prototype, "defaultFontColor", null);
  15347. __decorate([
  15348. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D_1.textProperty = pi; }, false, true)
  15349. ], Text2D.prototype, "text", null);
  15350. __decorate([
  15351. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D_1.sizeProperty = pi; })
  15352. ], Text2D.prototype, "size", null);
  15353. __decorate([
  15354. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Text2D_1.fontSuperSampleProperty = pi; }, false, false)
  15355. ], Text2D.prototype, "fontSuperSample", null);
  15356. __decorate([
  15357. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Text2D_1.fontSignedDistanceFieldProperty = pi; }, false, false)
  15358. ], Text2D.prototype, "fontSignedDistanceField", null);
  15359. __decorate([
  15360. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Text2D_1.textureIsPremulAlphaProperty = pi; })
  15361. ], Text2D.prototype, "textureIsPremulAlpha", null);
  15362. Text2D = Text2D_1 = __decorate([
  15363. BABYLON.className("Text2D", "BABYLON")
  15364. ], Text2D);
  15365. BABYLON.Text2D = Text2D;
  15366. var Text2D_1;
  15367. })(BABYLON || (BABYLON = {}));
  15368. var __extends = (this && this.__extends) || function (d, b) {
  15369. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15370. function __() { this.constructor = d; }
  15371. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15372. };
  15373. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  15374. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  15375. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  15376. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  15377. return c > 3 && r && Object.defineProperty(target, key, r), r;
  15378. };
  15379. var BABYLON;
  15380. (function (BABYLON) {
  15381. var Lines2DRenderCache = (function (_super) {
  15382. __extends(Lines2DRenderCache, _super);
  15383. function Lines2DRenderCache(engine, modelKey) {
  15384. var _this = _super.call(this, engine, modelKey) || this;
  15385. _this.effectsReady = false;
  15386. _this.fillVB = null;
  15387. _this.fillIB = null;
  15388. _this.fillIndicesCount = 0;
  15389. _this.instancingFillAttributes = null;
  15390. _this.effectFill = null;
  15391. _this.effectFillInstanced = null;
  15392. _this.borderVB = null;
  15393. _this.borderIB = null;
  15394. _this.borderIndicesCount = 0;
  15395. _this.instancingBorderAttributes = null;
  15396. _this.effectBorder = null;
  15397. _this.effectBorderInstanced = null;
  15398. return _this;
  15399. }
  15400. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  15401. // Do nothing if the shader is still loading/preparing
  15402. if (!this.effectsReady) {
  15403. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  15404. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  15405. return false;
  15406. }
  15407. this.effectsReady = true;
  15408. }
  15409. var canvas = instanceInfo.owner.owner;
  15410. var engine = canvas.engine;
  15411. engine.setState(false, undefined, true);
  15412. var depthFunction = 0;
  15413. if (this.effectFill && this.effectBorder) {
  15414. depthFunction = engine.getDepthFunction();
  15415. engine.setDepthFunctionToLessOrEqual();
  15416. }
  15417. var curAlphaMode = engine.getAlphaMode();
  15418. if (this.effectFill) {
  15419. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  15420. var pid = context.groupInfoPartData[partIndex];
  15421. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  15422. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  15423. }
  15424. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  15425. engine.enableEffect(effect);
  15426. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  15427. if (context.useInstancing) {
  15428. if (!this.instancingFillAttributes) {
  15429. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  15430. }
  15431. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  15432. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  15433. canvas._addDrawCallCount(1, context.renderMode);
  15434. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  15435. engine.draw(true, 0, this.fillIndicesCount, count);
  15436. engine.unbindInstanceAttributes();
  15437. }
  15438. else {
  15439. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  15440. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  15441. this.setupUniforms(effect, partIndex, pid._partData, i);
  15442. engine.draw(true, 0, this.fillIndicesCount);
  15443. }
  15444. }
  15445. }
  15446. if (this.effectBorder) {
  15447. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  15448. var pid = context.groupInfoPartData[partIndex];
  15449. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  15450. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  15451. }
  15452. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  15453. engine.enableEffect(effect);
  15454. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  15455. if (context.useInstancing) {
  15456. if (!this.instancingBorderAttributes) {
  15457. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  15458. }
  15459. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  15460. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  15461. canvas._addDrawCallCount(1, context.renderMode);
  15462. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  15463. engine.draw(true, 0, this.borderIndicesCount, count);
  15464. engine.unbindInstanceAttributes();
  15465. }
  15466. else {
  15467. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  15468. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  15469. this.setupUniforms(effect, partIndex, pid._partData, i);
  15470. engine.draw(true, 0, this.borderIndicesCount);
  15471. }
  15472. }
  15473. }
  15474. engine.setAlphaMode(curAlphaMode, true);
  15475. if (this.effectFill && this.effectBorder) {
  15476. engine.setDepthFunction(depthFunction);
  15477. }
  15478. return true;
  15479. };
  15480. Lines2DRenderCache.prototype.dispose = function () {
  15481. if (!_super.prototype.dispose.call(this)) {
  15482. return false;
  15483. }
  15484. if (this.fillVB) {
  15485. this._engine._releaseBuffer(this.fillVB);
  15486. this.fillVB = null;
  15487. }
  15488. if (this.fillIB) {
  15489. this._engine._releaseBuffer(this.fillIB);
  15490. this.fillIB = null;
  15491. }
  15492. this.effectFill = null;
  15493. this.effectFillInstanced = null;
  15494. this.effectBorder = null;
  15495. this.effectBorderInstanced = null;
  15496. if (this.borderVB) {
  15497. this._engine._releaseBuffer(this.borderVB);
  15498. this.borderVB = null;
  15499. }
  15500. if (this.borderIB) {
  15501. this._engine._releaseBuffer(this.borderIB);
  15502. this.borderIB = null;
  15503. }
  15504. return true;
  15505. };
  15506. return Lines2DRenderCache;
  15507. }(BABYLON.ModelRenderCache));
  15508. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  15509. var Lines2DInstanceData = (function (_super) {
  15510. __extends(Lines2DInstanceData, _super);
  15511. function Lines2DInstanceData(partId) {
  15512. return _super.call(this, partId, 1) || this;
  15513. }
  15514. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  15515. get: function () {
  15516. return null;
  15517. },
  15518. set: function (value) {
  15519. },
  15520. enumerable: true,
  15521. configurable: true
  15522. });
  15523. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  15524. get: function () {
  15525. return null;
  15526. },
  15527. set: function (value) {
  15528. },
  15529. enumerable: true,
  15530. configurable: true
  15531. });
  15532. return Lines2DInstanceData;
  15533. }(BABYLON.Shape2DInstanceData));
  15534. __decorate([
  15535. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  15536. ], Lines2DInstanceData.prototype, "boundingMin", null);
  15537. __decorate([
  15538. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  15539. ], Lines2DInstanceData.prototype, "boundingMax", null);
  15540. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  15541. var Lines2D = Lines2D_1 = (function (_super) {
  15542. __extends(Lines2D, _super);
  15543. /**
  15544. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  15545. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  15546. * @param settings a combination of settings, possible ones are
  15547. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  15548. * - children: an array of direct children
  15549. * - id a text identifier, for information purpose
  15550. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  15551. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  15552. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  15553. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  15554. * - alignToPixel: if true the primitive will be aligned to the target rendering device's pixel
  15555. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  15556. * - zOrder: override the zOrder with the specified value
  15557. * - origin: define the normalized origin point location, default [0.5;0.5]
  15558. * - fillThickness: the thickness of the fill part of the line, can be null to draw nothing (but a border brush must be given), default is 1.
  15559. * - closed: if false the lines are said to be opened, the first point and the latest DON'T connect. if true the lines are said to be closed, the first and last point will be connected by a line. For instance you can define the 4 points of a rectangle, if you set closed to true a 4 edges rectangle will be drawn. If you set false, only three edges will be drawn, the edge formed by the first and last point won't exist. Default is false.
  15560. * - startCap: Draw a cap of the given type at the start of the first line, you can't define a Cap if the Lines2D is closed. Default is Lines2D.NoCap.
  15561. * - endCap: Draw a cap of the given type at the end of the last line, you can't define a Cap if the Lines2D is closed. Default is Lines2D.NoCap.
  15562. * - fill: the brush used to draw the fill content of the lines, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can be a string value (see Canvas2D.GetBrushFromString)
  15563. * - border: the brush used to draw the border of the lines, you can set null to draw nothing (but you will have to set a fill brush), default is null. can be a string value (see Canvas2D.GetBrushFromString)
  15564. * - borderThickness: the thickness of the drawn border, default is 1.
  15565. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  15566. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  15567. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  15568. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  15569. * - levelCollision: this primitive is an actor of the Collision Manager and only this level will be used for collision (i.e. not the children). Use deepCollision if you want collision detection on the primitives and its children.
  15570. * - deepCollision: this primitive is an actor of the Collision Manager, this level AND ALSO its children will be used for collision (note: you don't need to set the children as level/deepCollision).
  15571. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  15572. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15573. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15574. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15575. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15576. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  15577. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  15578. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  15579. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  15580. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15581. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15582. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15583. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15584. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  15585. */
  15586. function Lines2D(points, settings) {
  15587. var _this;
  15588. if (!settings) {
  15589. settings = {};
  15590. }
  15591. _this = _super.call(this, settings) || this;
  15592. _this._fillVB = null;
  15593. _this._fillIB = null;
  15594. _this._borderVB = null;
  15595. _this._borderIB = null;
  15596. _this._boundingMin = null;
  15597. _this._boundingMax = null;
  15598. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  15599. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  15600. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  15601. var closed = (settings.closed == null) ? false : settings.closed;
  15602. _this.points = points;
  15603. _this.fillThickness = fillThickness;
  15604. _this.startCap = startCap;
  15605. _this.endCap = endCap;
  15606. _this.closed = closed;
  15607. return _this;
  15608. }
  15609. Object.defineProperty(Lines2D, "NoCap", {
  15610. /**
  15611. * No Cap to apply on the extremity
  15612. */
  15613. get: function () { return Lines2D_1._noCap; },
  15614. enumerable: true,
  15615. configurable: true
  15616. });
  15617. Object.defineProperty(Lines2D, "RoundCap", {
  15618. /**
  15619. * A round cap, will use the line thickness as diameter
  15620. */
  15621. get: function () { return Lines2D_1._roundCap; },
  15622. enumerable: true,
  15623. configurable: true
  15624. });
  15625. Object.defineProperty(Lines2D, "TriangleCap", {
  15626. /**
  15627. * Creates a triangle at the extremity.
  15628. */
  15629. get: function () { return Lines2D_1._triangleCap; },
  15630. enumerable: true,
  15631. configurable: true
  15632. });
  15633. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  15634. /**
  15635. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  15636. */
  15637. get: function () { return Lines2D_1._squareAnchorCap; },
  15638. enumerable: true,
  15639. configurable: true
  15640. });
  15641. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  15642. /**
  15643. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  15644. */
  15645. get: function () { return Lines2D_1._roundAnchorCap; },
  15646. enumerable: true,
  15647. configurable: true
  15648. });
  15649. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  15650. /**
  15651. * Creates a diamond anchor at the extremity.
  15652. */
  15653. get: function () { return Lines2D_1._diamondAnchorCap; },
  15654. enumerable: true,
  15655. configurable: true
  15656. });
  15657. Object.defineProperty(Lines2D, "ArrowCap", {
  15658. /**
  15659. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  15660. */
  15661. get: function () { return Lines2D_1._arrowCap; },
  15662. enumerable: true,
  15663. configurable: true
  15664. });
  15665. Object.defineProperty(Lines2D.prototype, "points", {
  15666. get: function () {
  15667. return this._points;
  15668. },
  15669. set: function (value) {
  15670. this._points = value;
  15671. this._primTriArrayDirty = true;
  15672. this._boundingBoxDirty();
  15673. },
  15674. enumerable: true,
  15675. configurable: true
  15676. });
  15677. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  15678. get: function () {
  15679. return this._fillThickness;
  15680. },
  15681. set: function (value) {
  15682. this._fillThickness = value;
  15683. },
  15684. enumerable: true,
  15685. configurable: true
  15686. });
  15687. Object.defineProperty(Lines2D.prototype, "closed", {
  15688. get: function () {
  15689. return this._closed;
  15690. },
  15691. set: function (value) {
  15692. this._closed = value;
  15693. },
  15694. enumerable: true,
  15695. configurable: true
  15696. });
  15697. Object.defineProperty(Lines2D.prototype, "startCap", {
  15698. get: function () {
  15699. return this._startCap;
  15700. },
  15701. set: function (value) {
  15702. this._startCap = value;
  15703. },
  15704. enumerable: true,
  15705. configurable: true
  15706. });
  15707. Object.defineProperty(Lines2D.prototype, "endCap", {
  15708. get: function () {
  15709. return this._endCap;
  15710. },
  15711. set: function (value) {
  15712. this._endCap = value;
  15713. },
  15714. enumerable: true,
  15715. configurable: true
  15716. });
  15717. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  15718. var p = intersectInfo._localPickPosition;
  15719. this.updateTriArray();
  15720. return this._primTriArray.doesContain(p);
  15721. };
  15722. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  15723. get: function () {
  15724. if (!this._boundingMin) {
  15725. this._computeLines2D();
  15726. }
  15727. return this._boundingMin;
  15728. },
  15729. enumerable: true,
  15730. configurable: true
  15731. });
  15732. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  15733. get: function () {
  15734. if (!this._boundingMax) {
  15735. this._computeLines2D();
  15736. }
  15737. return this._boundingMax;
  15738. },
  15739. enumerable: true,
  15740. configurable: true
  15741. });
  15742. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  15743. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  15744. // Remove the BORDER category, we don't use it in the VertexShader
  15745. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  15746. if (i !== -1) {
  15747. res.splice(i, 1);
  15748. }
  15749. return res;
  15750. };
  15751. Lines2D.prototype.updateLevelBoundingInfo = function () {
  15752. if (!this._boundingMin) {
  15753. this._computeLines2D();
  15754. }
  15755. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  15756. return true;
  15757. };
  15758. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  15759. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  15760. return renderCache;
  15761. };
  15762. ///////////////////////////////////////////////////////////////////////////////////
  15763. // Methods for Lines building
  15764. Lines2D.prototype._perp = function (v, res) {
  15765. res.x = v.y;
  15766. res.y = -v.x;
  15767. };
  15768. ;
  15769. Lines2D.prototype._direction = function (a, b, res) {
  15770. a.subtractToRef(b, res);
  15771. res.normalize();
  15772. };
  15773. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  15774. a.addToRef(b, tangent);
  15775. tangent.normalize();
  15776. miter.x = -tangent.y;
  15777. miter.y = tangent.x;
  15778. Lines2D_1._miterTps.x = -a.y;
  15779. Lines2D_1._miterTps.y = a.x;
  15780. return 1 / BABYLON.Vector2.Dot(miter, Lines2D_1._miterTps);
  15781. };
  15782. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  15783. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  15784. if (d === 0)
  15785. return false;
  15786. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  15787. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  15788. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  15789. return false;
  15790. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  15791. return false;
  15792. return true;
  15793. };
  15794. Lines2D.prototype._updateMinMax = function (array, offset) {
  15795. if (offset >= array.length) {
  15796. return;
  15797. }
  15798. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  15799. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  15800. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  15801. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  15802. };
  15803. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  15804. var borderMode = borderThickness != null && !isNaN(borderThickness);
  15805. var off = index * (borderMode ? 8 : 4);
  15806. // Mandatory because we'll be out of bound in case of closed line, for the very last point (which is a duplicate of the first that we don't store in the vb)
  15807. if (off >= array.length) {
  15808. return;
  15809. }
  15810. // Store start/end normal, we need it for the cap construction
  15811. if (index === 0) {
  15812. this._perp(n, Lines2D_1._startDir);
  15813. }
  15814. else if (index === max - 1) {
  15815. this._perp(n, Lines2D_1._endDir);
  15816. Lines2D_1._endDir.x *= -1;
  15817. Lines2D_1._endDir.y *= -1;
  15818. }
  15819. var swap = false;
  15820. array[off + 0] = p.x + n.x * halfThickness;
  15821. array[off + 1] = p.y + n.y * halfThickness;
  15822. array[off + 2] = p.x + n.x * -halfThickness;
  15823. array[off + 3] = p.y + n.y * -halfThickness;
  15824. this._updateMinMax(array, off);
  15825. this._updateMinMax(array, off + 2);
  15826. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  15827. // It should not be the case, they should be parallel, so if they cross, we switch the order of storage to ensure we'll have parallel lines
  15828. if (detectFlip != 0) {
  15829. // Flip if intersect
  15830. var flipOff = detectFlip * (borderMode ? 8 : 4);
  15831. if (this._intersect(array[off + 0], array[off + 1], array[flipOff + 0], array[flipOff + 1], array[off + 2], array[off + 3], array[flipOff + 2], array[flipOff + 3])) {
  15832. swap = true;
  15833. var tps = array[off + 0];
  15834. array[off + 0] = array[off + 2];
  15835. array[off + 2] = tps;
  15836. tps = array[off + 1];
  15837. array[off + 1] = array[off + 3];
  15838. array[off + 3] = tps;
  15839. }
  15840. }
  15841. if (borderMode) {
  15842. var t = halfThickness + borderThickness;
  15843. array[off + 4] = p.x + n.x * (swap ? -t : t);
  15844. array[off + 5] = p.y + n.y * (swap ? -t : t);
  15845. array[off + 6] = p.x + n.x * (swap ? t : -t);
  15846. array[off + 7] = p.y + n.y * (swap ? t : -t);
  15847. this._updateMinMax(array, off + 4);
  15848. this._updateMinMax(array, off + 6);
  15849. }
  15850. if (contour) {
  15851. off += borderMode ? 4 : 0;
  15852. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  15853. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  15854. }
  15855. };
  15856. Lines2D.prototype._getCapSize = function (type, border) {
  15857. if (border === void 0) { border = false; }
  15858. var sd = Lines2D_1._roundCapSubDiv;
  15859. // If no array given, we call this to get the size
  15860. var vbsize = 0, ibsize = 0;
  15861. switch (type) {
  15862. case Lines2D_1.NoCap:
  15863. {
  15864. // If the line is not close and we're computing border, we add the size to generate the edge border
  15865. if (!this.closed && border) {
  15866. vbsize = 4;
  15867. ibsize = 6;
  15868. }
  15869. else {
  15870. vbsize = ibsize = 0;
  15871. }
  15872. break;
  15873. }
  15874. case Lines2D_1.RoundCap:
  15875. {
  15876. if (border) {
  15877. vbsize = sd;
  15878. ibsize = (sd - 2) * 3;
  15879. }
  15880. else {
  15881. vbsize = (sd / 2) + 1;
  15882. ibsize = (sd / 2) * 3;
  15883. }
  15884. break;
  15885. }
  15886. case Lines2D_1.ArrowCap:
  15887. {
  15888. if (border) {
  15889. vbsize = 12;
  15890. ibsize = 24;
  15891. }
  15892. else {
  15893. vbsize = 3;
  15894. ibsize = 3;
  15895. }
  15896. break;
  15897. }
  15898. case Lines2D_1.TriangleCap:
  15899. {
  15900. if (border) {
  15901. vbsize = 6;
  15902. ibsize = 12;
  15903. }
  15904. else {
  15905. vbsize = 3;
  15906. ibsize = 3;
  15907. }
  15908. break;
  15909. }
  15910. case Lines2D_1.DiamondAnchorCap:
  15911. {
  15912. if (border) {
  15913. vbsize = 10;
  15914. ibsize = 24;
  15915. }
  15916. else {
  15917. vbsize = 5;
  15918. ibsize = 9;
  15919. }
  15920. break;
  15921. }
  15922. case Lines2D_1.SquareAnchorCap:
  15923. {
  15924. if (border) {
  15925. vbsize = 12;
  15926. ibsize = 30;
  15927. }
  15928. else {
  15929. vbsize = 4;
  15930. ibsize = 6;
  15931. }
  15932. break;
  15933. }
  15934. case Lines2D_1.RoundAnchorCap:
  15935. {
  15936. if (border) {
  15937. vbsize = sd * 2;
  15938. ibsize = (sd - 1) * 6;
  15939. }
  15940. else {
  15941. vbsize = sd + 1;
  15942. ibsize = (sd + 1) * 3;
  15943. }
  15944. break;
  15945. }
  15946. }
  15947. return { vbsize: vbsize * 2, ibsize: ibsize };
  15948. };
  15949. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  15950. var c = Math.cos(rotation);
  15951. var s = Math.sin(rotation);
  15952. Lines2D_1._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  15953. Lines2D_1._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  15954. var offset = baseOffset + (index * 2);
  15955. vb[offset + 0] = Lines2D_1._tpsV.x;
  15956. vb[offset + 1] = Lines2D_1._tpsV.y;
  15957. if (contour) {
  15958. contour.push(Lines2D_1._tpsV.x);
  15959. contour.push(Lines2D_1._tpsV.y);
  15960. }
  15961. this._updateMinMax(vb, offset);
  15962. return (baseOffset + index * 2) / 2;
  15963. };
  15964. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  15965. ib[baseOffset + index] = vertexIndex;
  15966. };
  15967. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  15968. // Compute the transformation from the direction of the cap to build relative to our default orientation [1;0] (our cap are by default pointing toward right, horizontal
  15969. var sd = Lines2D_1._roundCapSubDiv;
  15970. var dir = new BABYLON.Vector2(1, 0);
  15971. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  15972. var ht = thickness / 2;
  15973. var t = thickness;
  15974. var borderMode = borderThickness != null;
  15975. var bt = borderThickness;
  15976. switch (type) {
  15977. case Lines2D_1.NoCap:
  15978. if (borderMode && !this.closed) {
  15979. var vi = 0;
  15980. var ii = 0;
  15981. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  15982. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  15983. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  15984. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  15985. this._storeIndex(ib, ibi, ii++, v1);
  15986. this._storeIndex(ib, ibi, ii++, v2);
  15987. this._storeIndex(ib, ibi, ii++, v3);
  15988. this._storeIndex(ib, ibi, ii++, v1);
  15989. this._storeIndex(ib, ibi, ii++, v3);
  15990. this._storeIndex(ib, ibi, ii++, v4);
  15991. }
  15992. break;
  15993. case Lines2D_1.ArrowCap:
  15994. ht *= 2;
  15995. case Lines2D_1.TriangleCap:
  15996. {
  15997. if (borderMode) {
  15998. var f = type === Lines2D_1.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  15999. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  16000. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  16001. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  16002. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  16003. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  16004. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  16005. var ii = 0;
  16006. this._storeIndex(ib, ibi, ii++, v1);
  16007. this._storeIndex(ib, ibi, ii++, v4);
  16008. this._storeIndex(ib, ibi, ii++, v5);
  16009. this._storeIndex(ib, ibi, ii++, v1);
  16010. this._storeIndex(ib, ibi, ii++, v5);
  16011. this._storeIndex(ib, ibi, ii++, v2);
  16012. this._storeIndex(ib, ibi, ii++, v6);
  16013. this._storeIndex(ib, ibi, ii++, v3);
  16014. this._storeIndex(ib, ibi, ii++, v2);
  16015. this._storeIndex(ib, ibi, ii++, v6);
  16016. this._storeIndex(ib, ibi, ii++, v2);
  16017. this._storeIndex(ib, ibi, ii++, v5);
  16018. if (type === Lines2D_1.ArrowCap) {
  16019. var rht = thickness / 2;
  16020. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  16021. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  16022. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  16023. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  16024. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  16025. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  16026. this._storeIndex(ib, ibi, ii++, v7);
  16027. this._storeIndex(ib, ibi, ii++, v8);
  16028. this._storeIndex(ib, ibi, ii++, v9);
  16029. this._storeIndex(ib, ibi, ii++, v7);
  16030. this._storeIndex(ib, ibi, ii++, v9);
  16031. this._storeIndex(ib, ibi, ii++, v4);
  16032. this._storeIndex(ib, ibi, ii++, v10);
  16033. this._storeIndex(ib, ibi, ii++, v12);
  16034. this._storeIndex(ib, ibi, ii++, v11);
  16035. this._storeIndex(ib, ibi, ii++, v10);
  16036. this._storeIndex(ib, ibi, ii++, v6);
  16037. this._storeIndex(ib, ibi, ii++, v12);
  16038. }
  16039. }
  16040. else {
  16041. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  16042. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  16043. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  16044. this._storeIndex(ib, ibi, 0, v1);
  16045. this._storeIndex(ib, ibi, 1, v2);
  16046. this._storeIndex(ib, ibi, 2, v3);
  16047. }
  16048. break;
  16049. }
  16050. case Lines2D_1.RoundCap:
  16051. {
  16052. if (borderMode) {
  16053. var curA = -Math.PI / 2;
  16054. var incA = Math.PI / (sd / 2 - 1);
  16055. var ii = 0;
  16056. for (var i = 0; i < (sd / 2); i++) {
  16057. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  16058. var v2 = this._storeVertex(vb, vbi, i * 2 + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * (ht + bt), Math.sin(curA) * (ht + bt)), contour);
  16059. if (i > 0) {
  16060. this._storeIndex(ib, ibi, ii++, v1 - 2);
  16061. this._storeIndex(ib, ibi, ii++, v2 - 2);
  16062. this._storeIndex(ib, ibi, ii++, v2);
  16063. this._storeIndex(ib, ibi, ii++, v1 - 2);
  16064. this._storeIndex(ib, ibi, ii++, v2);
  16065. this._storeIndex(ib, ibi, ii++, v1);
  16066. }
  16067. curA += incA;
  16068. }
  16069. }
  16070. else {
  16071. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  16072. var curA = -Math.PI / 2;
  16073. var incA = Math.PI / (sd / 2 - 1);
  16074. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  16075. curA += incA;
  16076. for (var i = 1; i < (sd / 2); i++) {
  16077. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  16078. this._storeIndex(ib, ibi, i * 3 + 0, c);
  16079. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  16080. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  16081. curA += incA;
  16082. }
  16083. }
  16084. break;
  16085. }
  16086. case Lines2D_1.SquareAnchorCap:
  16087. {
  16088. var vi = 0;
  16089. var c = borderMode ? null : contour;
  16090. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  16091. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  16092. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  16093. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  16094. if (borderMode) {
  16095. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  16096. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  16097. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  16098. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  16099. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  16100. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  16101. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  16102. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  16103. var ii = 0;
  16104. this._storeIndex(ib, ibi, ii++, v6);
  16105. this._storeIndex(ib, ibi, ii++, v1);
  16106. this._storeIndex(ib, ibi, ii++, v5);
  16107. this._storeIndex(ib, ibi, ii++, v6);
  16108. this._storeIndex(ib, ibi, ii++, v7);
  16109. this._storeIndex(ib, ibi, ii++, v1);
  16110. this._storeIndex(ib, ibi, ii++, v1);
  16111. this._storeIndex(ib, ibi, ii++, v7);
  16112. this._storeIndex(ib, ibi, ii++, v8);
  16113. this._storeIndex(ib, ibi, ii++, v1);
  16114. this._storeIndex(ib, ibi, ii++, v8);
  16115. this._storeIndex(ib, ibi, ii++, v2);
  16116. this._storeIndex(ib, ibi, ii++, v2);
  16117. this._storeIndex(ib, ibi, ii++, v8);
  16118. this._storeIndex(ib, ibi, ii++, v9);
  16119. this._storeIndex(ib, ibi, ii++, v2);
  16120. this._storeIndex(ib, ibi, ii++, v9);
  16121. this._storeIndex(ib, ibi, ii++, v3);
  16122. this._storeIndex(ib, ibi, ii++, v3);
  16123. this._storeIndex(ib, ibi, ii++, v9);
  16124. this._storeIndex(ib, ibi, ii++, v10);
  16125. this._storeIndex(ib, ibi, ii++, v3);
  16126. this._storeIndex(ib, ibi, ii++, v10);
  16127. this._storeIndex(ib, ibi, ii++, v4);
  16128. this._storeIndex(ib, ibi, ii++, v10);
  16129. this._storeIndex(ib, ibi, ii++, v11);
  16130. this._storeIndex(ib, ibi, ii++, v4);
  16131. this._storeIndex(ib, ibi, ii++, v11);
  16132. this._storeIndex(ib, ibi, ii++, v12);
  16133. this._storeIndex(ib, ibi, ii++, v4);
  16134. }
  16135. else {
  16136. this._storeIndex(ib, ibi, 0, v1);
  16137. this._storeIndex(ib, ibi, 1, v2);
  16138. this._storeIndex(ib, ibi, 2, v3);
  16139. this._storeIndex(ib, ibi, 3, v1);
  16140. this._storeIndex(ib, ibi, 4, v3);
  16141. this._storeIndex(ib, ibi, 5, v4);
  16142. }
  16143. break;
  16144. }
  16145. case Lines2D_1.RoundAnchorCap:
  16146. {
  16147. var cpos = Math.sqrt(t * t - ht * ht);
  16148. var center = new BABYLON.Vector2(cpos, 0);
  16149. var curA = BABYLON.Tools.ToRadians(-150);
  16150. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  16151. if (borderMode) {
  16152. var ii = 0;
  16153. for (var i = 0; i < sd; i++) {
  16154. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  16155. var v2 = this._storeVertex(vb, vbi, i * 2 + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * (t + bt), Math.sin(curA) * (t + bt)), contour);
  16156. if (i > 0) {
  16157. this._storeIndex(ib, ibi, ii++, v1 - 2);
  16158. this._storeIndex(ib, ibi, ii++, v2 - 2);
  16159. this._storeIndex(ib, ibi, ii++, v2);
  16160. this._storeIndex(ib, ibi, ii++, v1 - 2);
  16161. this._storeIndex(ib, ibi, ii++, v2);
  16162. this._storeIndex(ib, ibi, ii++, v1);
  16163. }
  16164. curA += incA;
  16165. }
  16166. }
  16167. else {
  16168. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  16169. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  16170. curA += incA;
  16171. for (var i = 1; i < sd; i++) {
  16172. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  16173. this._storeIndex(ib, ibi, i * 3 + 0, c);
  16174. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  16175. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  16176. curA += incA;
  16177. }
  16178. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  16179. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  16180. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  16181. }
  16182. break;
  16183. }
  16184. case Lines2D_1.DiamondAnchorCap:
  16185. {
  16186. var vi = 0;
  16187. var c = borderMode ? null : contour;
  16188. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  16189. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  16190. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  16191. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  16192. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  16193. if (borderMode) {
  16194. var f = Math.sqrt(bt * bt * 2);
  16195. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  16196. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  16197. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  16198. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  16199. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  16200. var ii = 0;
  16201. this._storeIndex(ib, ibi, ii++, v6);
  16202. this._storeIndex(ib, ibi, ii++, v7);
  16203. this._storeIndex(ib, ibi, ii++, v1);
  16204. this._storeIndex(ib, ibi, ii++, v1);
  16205. this._storeIndex(ib, ibi, ii++, v7);
  16206. this._storeIndex(ib, ibi, ii++, v2);
  16207. this._storeIndex(ib, ibi, ii++, v2);
  16208. this._storeIndex(ib, ibi, ii++, v7);
  16209. this._storeIndex(ib, ibi, ii++, v8);
  16210. this._storeIndex(ib, ibi, ii++, v2);
  16211. this._storeIndex(ib, ibi, ii++, v8);
  16212. this._storeIndex(ib, ibi, ii++, v3);
  16213. this._storeIndex(ib, ibi, ii++, v3);
  16214. this._storeIndex(ib, ibi, ii++, v8);
  16215. this._storeIndex(ib, ibi, ii++, v9);
  16216. this._storeIndex(ib, ibi, ii++, v3);
  16217. this._storeIndex(ib, ibi, ii++, v9);
  16218. this._storeIndex(ib, ibi, ii++, v4);
  16219. this._storeIndex(ib, ibi, ii++, v4);
  16220. this._storeIndex(ib, ibi, ii++, v9);
  16221. this._storeIndex(ib, ibi, ii++, v10);
  16222. this._storeIndex(ib, ibi, ii++, v4);
  16223. this._storeIndex(ib, ibi, ii++, v10);
  16224. this._storeIndex(ib, ibi, ii++, v5);
  16225. }
  16226. else {
  16227. this._storeIndex(ib, ibi, 0, v1);
  16228. this._storeIndex(ib, ibi, 1, v2);
  16229. this._storeIndex(ib, ibi, 2, v3);
  16230. this._storeIndex(ib, ibi, 3, v1);
  16231. this._storeIndex(ib, ibi, 4, v3);
  16232. this._storeIndex(ib, ibi, 5, v5);
  16233. this._storeIndex(ib, ibi, 6, v5);
  16234. this._storeIndex(ib, ibi, 7, v3);
  16235. this._storeIndex(ib, ibi, 8, v4);
  16236. }
  16237. break;
  16238. }
  16239. }
  16240. return null;
  16241. };
  16242. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  16243. var lineA = BABYLON.Vector2.Zero();
  16244. var lineB = BABYLON.Vector2.Zero();
  16245. var tangent = BABYLON.Vector2.Zero();
  16246. var miter = BABYLON.Vector2.Zero();
  16247. var curNormal = null;
  16248. if (this.closed) {
  16249. this.points.push(this.points[0]);
  16250. }
  16251. var total = this.points.length;
  16252. for (var i = 1; i < total; i++) {
  16253. var last = this.points[i - 1];
  16254. var cur = this.points[i];
  16255. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  16256. this._direction(cur, last, lineA);
  16257. if (!curNormal) {
  16258. curNormal = BABYLON.Vector2.Zero();
  16259. this._perp(lineA, curNormal);
  16260. }
  16261. if (i === 1) {
  16262. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  16263. }
  16264. if (!next) {
  16265. this._perp(lineA, curNormal);
  16266. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  16267. }
  16268. else {
  16269. this._direction(next, cur, lineB);
  16270. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  16271. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  16272. }
  16273. }
  16274. if (this.points.length > 2 && this.closed) {
  16275. var last2 = this.points[total - 2];
  16276. var cur2 = this.points[0];
  16277. var next2 = this.points[1];
  16278. this._direction(cur2, last2, lineA);
  16279. this._direction(next2, cur2, lineB);
  16280. this._perp(lineA, curNormal);
  16281. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  16282. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  16283. // Patch contour
  16284. if (contour) {
  16285. var off = (bt == null) ? 0 : 4;
  16286. contour[0].x = vb[off + 0];
  16287. contour[0].y = vb[off + 1];
  16288. contour[1].x = vb[off + 2];
  16289. contour[1].y = vb[off + 3];
  16290. }
  16291. }
  16292. // Remove the point we added at the beginning
  16293. if (this.closed) {
  16294. this.points.splice(total - 1);
  16295. }
  16296. };
  16297. // Methods for Lines building
  16298. ///////////////////////////////////////////////////////////////////////////////////
  16299. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  16300. var renderCache = modelRenderCache;
  16301. var engine = this.owner.engine;
  16302. if (this._fillVB === null) {
  16303. this._computeLines2D();
  16304. }
  16305. // Need to create WebGL resources for fill part?
  16306. if (this.fill) {
  16307. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  16308. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  16309. renderCache.fillIndicesCount = this._fillIB.length;
  16310. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  16311. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, true);
  16312. if (ei) {
  16313. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  16314. }
  16315. // Get the non instanced version
  16316. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, false);
  16317. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  16318. }
  16319. // Need to create WebGL resources for border part?
  16320. if (this.border) {
  16321. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  16322. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  16323. renderCache.borderIndicesCount = this._borderIB.length;
  16324. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  16325. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, true);
  16326. if (ei) {
  16327. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  16328. }
  16329. // Get the non instanced version
  16330. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, false);
  16331. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  16332. }
  16333. this._fillVB = null;
  16334. this._fillIB = null;
  16335. this._borderVB = null;
  16336. this._borderIB = null;
  16337. return renderCache;
  16338. };
  16339. Lines2D.prototype.updateTriArray = function () {
  16340. if (this._primTriArrayDirty) {
  16341. this._computeLines2D();
  16342. }
  16343. };
  16344. Lines2D.prototype._computeLines2D = function () {
  16345. // Init min/max because their being computed here
  16346. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  16347. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  16348. var contour = new Array();
  16349. var startCapContour = new Array();
  16350. var endCapContour = new Array();
  16351. // Need to create WebGL resources for fill part?
  16352. if (this.fill) {
  16353. var startCapInfo = this._getCapSize(this.startCap);
  16354. var endCapInfo = this._getCapSize(this.endCap);
  16355. var count = this.points.length;
  16356. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  16357. this._fillVB = new Float32Array(vbSize);
  16358. var vb = this._fillVB;
  16359. var ht = this.fillThickness / 2;
  16360. var total = this.points.length;
  16361. this._buildLine(vb, this.border ? null : contour, ht);
  16362. var max = total * 2;
  16363. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  16364. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  16365. var ib = this._fillIB;
  16366. for (var i = 0; i < triCount; i += 2) {
  16367. ib[i * 3 + 0] = i + 0;
  16368. ib[i * 3 + 1] = i + 1;
  16369. ib[i * 3 + 2] = (i + 2) % max;
  16370. ib[i * 3 + 3] = i + 1;
  16371. ib[i * 3 + 4] = (i + 3) % max;
  16372. ib[i * 3 + 5] = (i + 2) % max;
  16373. }
  16374. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D_1._startDir, this.border ? null : startCapContour);
  16375. this._buildCap(vb, (count * 2 * 2) + startCapInfo.vbsize, ib, (triCount * 3) + startCapInfo.ibsize, this.points[total - 1], this.fillThickness, null, this.endCap, Lines2D_1._endDir, this.border ? null : startCapContour);
  16376. }
  16377. // Need to create WebGL resources for border part?
  16378. if (this.border) {
  16379. var startCapInfo = this._getCapSize(this.startCap, true);
  16380. var endCapInfo = this._getCapSize(this.endCap, true);
  16381. var count = this.points.length;
  16382. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  16383. this._borderVB = new Float32Array(vbSize);
  16384. var vb = this._borderVB;
  16385. var ht = this.fillThickness / 2;
  16386. var bt = this.borderThickness;
  16387. var total = this.points.length;
  16388. this._buildLine(vb, contour, ht, bt);
  16389. var max = total * 2 * 2;
  16390. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  16391. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  16392. var ib = this._borderIB;
  16393. for (var i = 0; i < triCount; i += 4) {
  16394. ib[i * 3 + 0] = i + 0;
  16395. ib[i * 3 + 1] = i + 2;
  16396. ib[i * 3 + 2] = (i + 6) % max;
  16397. ib[i * 3 + 3] = i + 0;
  16398. ib[i * 3 + 4] = (i + 6) % max;
  16399. ib[i * 3 + 5] = (i + 4) % max;
  16400. ib[i * 3 + 6] = i + 3;
  16401. ib[i * 3 + 7] = i + 1;
  16402. ib[i * 3 + 8] = (i + 5) % max;
  16403. ib[i * 3 + 9] = i + 3;
  16404. ib[i * 3 + 10] = (i + 5) % max;
  16405. ib[i * 3 + 11] = (i + 7) % max;
  16406. }
  16407. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D_1._startDir, startCapContour);
  16408. this._buildCap(vb, (count * 2 * 2 * 2) + startCapInfo.vbsize, ib, (triCount * 3) + startCapInfo.ibsize, this.points[total - 1], this.fillThickness, this.borderThickness, this.endCap, Lines2D_1._endDir, endCapContour);
  16409. }
  16410. var startCapTri;
  16411. if (startCapContour.length > 0) {
  16412. startCapTri = Earcut.earcut(startCapContour, null, 2);
  16413. }
  16414. var endCapTri;
  16415. if (endCapContour.length > 0) {
  16416. endCapTri = Earcut.earcut(endCapContour, null, 2);
  16417. }
  16418. // Build the Tri2DArray using the contour info from the shape and the caps (if any)
  16419. {
  16420. var pl = this.points.length;
  16421. // Count the number of needed triangles
  16422. var count = ((this.closed ? pl : (pl - 1)) * 2) + (startCapTri != null ? ((startCapTri.length + endCapTri.length) / 3) : 0);
  16423. // Init/Clear the TriArray
  16424. if (!this._primTriArray) {
  16425. this._primTriArray = new BABYLON.Tri2DArray(count);
  16426. }
  16427. else {
  16428. this._primTriArray.clear(count);
  16429. }
  16430. var pta_1 = this._primTriArray;
  16431. var l = this.closed ? pl + 1 : pl;
  16432. Lines2D_1._prevA.copyFrom(contour[0]);
  16433. Lines2D_1._prevB.copyFrom(contour[1]);
  16434. var si_1 = 0;
  16435. for (var i = 1; i < l; i++) {
  16436. Lines2D_1._curA.copyFrom(contour[(i % pl) * 2 + 0]);
  16437. Lines2D_1._curB.copyFrom(contour[(i % pl) * 2 + 1]);
  16438. pta_1.storeTriangle(si_1++, Lines2D_1._prevA, Lines2D_1._prevB, Lines2D_1._curA);
  16439. pta_1.storeTriangle(si_1++, Lines2D_1._curA, Lines2D_1._prevB, Lines2D_1._curB);
  16440. Lines2D_1._prevA.x = Lines2D_1._curA.x;
  16441. Lines2D_1._prevA.y = Lines2D_1._curA.y;
  16442. Lines2D_1._prevB.x = Lines2D_1._curB.x;
  16443. Lines2D_1._prevB.y = Lines2D_1._curB.y;
  16444. }
  16445. var capIntersect = function (tri, points) {
  16446. var l = tri.length;
  16447. for (var i = 0; i < l; i += 3) {
  16448. Lines2D_1._curA.x = points[tri[i + 0] * 2 + 0];
  16449. Lines2D_1._curA.y = points[tri[i + 0] * 2 + 1];
  16450. Lines2D_1._curB.copyFrom(Lines2D_1._curA);
  16451. Lines2D_1._curA.x = points[tri[i + 1] * 2 + 0];
  16452. Lines2D_1._curA.y = points[tri[i + 1] * 2 + 1];
  16453. Lines2D_1._prevA.copyFrom(Lines2D_1._curA);
  16454. Lines2D_1._curA.x = points[tri[i + 2] * 2 + 0];
  16455. Lines2D_1._curA.y = points[tri[i + 2] * 2 + 1];
  16456. Lines2D_1._prevB.copyFrom(Lines2D_1._curA);
  16457. pta_1.storeTriangle(si_1++, Lines2D_1._prevA, Lines2D_1._prevB, Lines2D_1._curB);
  16458. }
  16459. return false;
  16460. };
  16461. if (startCapTri) {
  16462. if (startCapTri) {
  16463. capIntersect(startCapTri, startCapContour);
  16464. }
  16465. if (endCapTri) {
  16466. capIntersect(endCapTri, endCapContour);
  16467. }
  16468. }
  16469. this._primTriArrayDirty = false;
  16470. }
  16471. var bs = this._boundingMax.subtract(this._boundingMin);
  16472. // If the size is not size we were computing the first pass to determine the size took by the primitive
  16473. if (!this._size) {
  16474. // Set the size and compute a second time to consider the size while computing the points using the origin
  16475. this._size = new BABYLON.Size(bs.x, bs.y);
  16476. this._updatePositioningState();
  16477. }
  16478. this._size.width = bs.x;
  16479. this._size.height = bs.y;
  16480. this._actualSize = null;
  16481. };
  16482. Object.defineProperty(Lines2D.prototype, "size", {
  16483. get: function () {
  16484. if (this._size == null) {
  16485. this._computeLines2D();
  16486. }
  16487. return this._size;
  16488. },
  16489. enumerable: true,
  16490. configurable: true
  16491. });
  16492. Lines2D.prototype.createInstanceDataParts = function () {
  16493. var res = new Array();
  16494. if (this.border) {
  16495. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  16496. }
  16497. if (this.fill) {
  16498. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  16499. }
  16500. return res;
  16501. };
  16502. Lines2D.prototype.applyActualScaleOnTransform = function () {
  16503. return true;
  16504. };
  16505. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  16506. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  16507. return false;
  16508. }
  16509. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  16510. var d = part;
  16511. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  16512. d.boundingMin = this.boundingMin;
  16513. d.boundingMax = this.boundingMax;
  16514. }
  16515. }
  16516. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  16517. var d = part;
  16518. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  16519. d.boundingMin = this.boundingMin;
  16520. d.boundingMax = this.boundingMax;
  16521. }
  16522. }
  16523. return true;
  16524. };
  16525. return Lines2D;
  16526. }(BABYLON.Shape2D));
  16527. Lines2D._prevA = BABYLON.Vector2.Zero();
  16528. Lines2D._prevB = BABYLON.Vector2.Zero();
  16529. Lines2D._curA = BABYLON.Vector2.Zero();
  16530. Lines2D._curB = BABYLON.Vector2.Zero();
  16531. Lines2D._miterTps = BABYLON.Vector2.Zero();
  16532. Lines2D._startDir = BABYLON.Vector2.Zero();
  16533. Lines2D._endDir = BABYLON.Vector2.Zero();
  16534. Lines2D._tpsV = BABYLON.Vector2.Zero();
  16535. Lines2D._noCap = 0;
  16536. Lines2D._roundCap = 1;
  16537. Lines2D._triangleCap = 2;
  16538. Lines2D._squareAnchorCap = 3;
  16539. Lines2D._roundAnchorCap = 4;
  16540. Lines2D._diamondAnchorCap = 5;
  16541. Lines2D._arrowCap = 6;
  16542. Lines2D._roundCapSubDiv = 36;
  16543. __decorate([
  16544. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D_1.pointsProperty = pi; })
  16545. ], Lines2D.prototype, "points", null);
  16546. __decorate([
  16547. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D_1.fillThicknessProperty = pi; })
  16548. ], Lines2D.prototype, "fillThickness", null);
  16549. __decorate([
  16550. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D_1.closedProperty = pi; })
  16551. ], Lines2D.prototype, "closed", null);
  16552. __decorate([
  16553. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D_1.startCapProperty = pi; })
  16554. ], Lines2D.prototype, "startCap", null);
  16555. __decorate([
  16556. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D_1.endCapProperty = pi; })
  16557. ], Lines2D.prototype, "endCap", null);
  16558. Lines2D = Lines2D_1 = __decorate([
  16559. BABYLON.className("Lines2D", "BABYLON")
  16560. ], Lines2D);
  16561. BABYLON.Lines2D = Lines2D;
  16562. var Lines2D_1;
  16563. })(BABYLON || (BABYLON = {}));
  16564. var __extends = (this && this.__extends) || function (d, b) {
  16565. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16566. function __() { this.constructor = d; }
  16567. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  16568. };
  16569. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  16570. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  16571. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  16572. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  16573. return c > 3 && r && Object.defineProperty(target, key, r), r;
  16574. };
  16575. var BABYLON;
  16576. (function (BABYLON) {
  16577. // This class contains data that lifetime is bounding to the Babylon Engine object
  16578. var Canvas2DEngineBoundData = (function () {
  16579. function Canvas2DEngineBoundData() {
  16580. this._modelCache = new BABYLON.StringDictionary();
  16581. }
  16582. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  16583. return this._modelCache.getOrAddWithFactory(key, factory);
  16584. };
  16585. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  16586. if (!modelRenderCache.isDisposed) {
  16587. return false;
  16588. }
  16589. this._modelCache.remove(modelRenderCache.modelKey);
  16590. return true;
  16591. };
  16592. return Canvas2DEngineBoundData;
  16593. }());
  16594. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  16595. var Canvas2D = Canvas2D_1 = (function (_super) {
  16596. __extends(Canvas2D, _super);
  16597. function Canvas2D(scene, settings) {
  16598. var _this = _super.call(this, settings) || this;
  16599. /**
  16600. * If you set your own WorldSpaceNode to display the Canvas2D you have to provide your own implementation of this method which computes the local position in the Canvas based on the given 3D World one.
  16601. * Beware that you have to take under consideration the origin and unitScaleFactor in your calculations! Good luck!
  16602. */
  16603. _this.worldSpaceToNodeLocal = function (worldPos) {
  16604. var node = _this._worldSpaceNode;
  16605. if (!node) {
  16606. return;
  16607. }
  16608. var mtx = node.getWorldMatrix().clone();
  16609. mtx.invert();
  16610. var usf = _this.unitScaleFactor;
  16611. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  16612. var res = new BABYLON.Vector2(v.x, v.y);
  16613. var size = _this.actualSize;
  16614. res.x += (size.width / usf) * 0.5; // res is centered, make it relative to bottom/left
  16615. res.y += (size.height / usf) * 0.5;
  16616. res.x *= usf; // multiply by the unitScaleFactor, which defines if the canvas is nth time bigger than the original world plane
  16617. res.y *= usf;
  16618. return res;
  16619. };
  16620. /**
  16621. * If you use a custom WorldSpaceCanvasNode you have to override this property to update the UV of your object to reflect the changes due to a resizing of the cached bitmap
  16622. */
  16623. _this.worldSpaceCacheChanged = function () {
  16624. var plane = _this.worldSpaceCanvasNode;
  16625. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  16626. vd.uvs = new Float32Array(8);
  16627. var material = plane.material;
  16628. var tex = _this._renderableData._cacheTexture;
  16629. if (material.diffuseTexture !== tex) {
  16630. material.diffuseTexture = tex;
  16631. tex.hasAlpha = true;
  16632. }
  16633. var nodeuv = _this._renderableData._cacheNodeUVs;
  16634. for (var i = 0; i < 4; i++) {
  16635. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  16636. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  16637. }
  16638. vd.applyToMesh(plane);
  16639. };
  16640. _this._notifDebugMode = false;
  16641. /**
  16642. * Instanced Array will be create if there's at least this number of parts/prim that can fit into it
  16643. */
  16644. _this.minPartCountToUseInstancedArray = 5;
  16645. _this._mapCounter = 0;
  16646. _this._cachedCanvasGroup = null;
  16647. _this._renderingGroupObserver = null;
  16648. _this._beforeRenderObserver = null;
  16649. _this._afterRenderObserver = null;
  16650. _this._profileInfoText = null;
  16651. BABYLON.Prim2DBase._isCanvasInit = false;
  16652. if (!settings) {
  16653. settings = {};
  16654. }
  16655. if (_this._cachingStrategy !== Canvas2D_1.CACHESTRATEGY_TOPLEVELGROUPS) {
  16656. _this._background = new BABYLON.Rectangle2D({ parent: _this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  16657. _this._background.zOrder = 1.0;
  16658. _this._background.isPickable = false;
  16659. _this._background.origin = BABYLON.Vector2.Zero();
  16660. _this._background.levelVisible = false;
  16661. if (settings.backgroundRoundRadius != null) {
  16662. _this.backgroundRoundRadius = settings.backgroundRoundRadius;
  16663. }
  16664. if (settings.backgroundBorder != null) {
  16665. if (typeof (settings.backgroundBorder) === "string") {
  16666. _this.backgroundBorder = Canvas2D_1.GetBrushFromString(settings.backgroundBorder);
  16667. }
  16668. else {
  16669. _this.backgroundBorder = settings.backgroundBorder;
  16670. }
  16671. }
  16672. if (settings.backgroundBorderThickNess != null) {
  16673. _this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  16674. }
  16675. if (settings.backgroundFill != null) {
  16676. if (typeof (settings.backgroundFill) === "string") {
  16677. _this.backgroundFill = Canvas2D_1.GetBrushFromString(settings.backgroundFill);
  16678. }
  16679. else {
  16680. _this.backgroundFill = settings.backgroundFill;
  16681. }
  16682. }
  16683. // Put a handler to resize the background whenever the canvas is resizing
  16684. _this.propertyChanged.add(function (e, s) {
  16685. if (e.propertyName === "size") {
  16686. _this._background.size = _this.size;
  16687. }
  16688. }, BABYLON.Group2D.sizeProperty.flagId);
  16689. _this._background._patchHierarchy(_this);
  16690. }
  16691. var engine = scene.getEngine();
  16692. _this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  16693. _this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  16694. _this._capturedPointers = new BABYLON.StringDictionary();
  16695. _this._pickStartingPosition = BABYLON.Vector2.Zero();
  16696. _this._hierarchyLevelMaxSiblingCount = 50;
  16697. _this._hierarchyDepth = 0;
  16698. _this._zOrder = 0;
  16699. _this._zMax = 1;
  16700. _this._scene = scene;
  16701. _this._engine = engine;
  16702. _this._renderingSize = new BABYLON.Size(0, 0);
  16703. _this._curHWScale = 0;
  16704. _this._canvasLevelScale = new BABYLON.Vector3(1, 1, 1);
  16705. _this._designSize = settings.designSize || null;
  16706. _this._designUseHorizAxis = settings.designUseHorizAxis === true;
  16707. if (!_this._trackedGroups) {
  16708. _this._trackedGroups = new Array();
  16709. }
  16710. _this._maxAdaptiveWorldSpaceCanvasSize = null;
  16711. _this._groupCacheMaps = new BABYLON.StringDictionary();
  16712. _this._patchHierarchy(_this);
  16713. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  16714. _this._fitRenderingDevice = !settings.size;
  16715. if (!settings.size) {
  16716. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  16717. }
  16718. // Register scene dispose to also dispose the canvas when it'll happens
  16719. scene.onDisposeObservable.add(function (d, s) {
  16720. _this.dispose();
  16721. });
  16722. if (_this._isScreenSpace) {
  16723. if (settings.renderingPhase) {
  16724. if (!settings.renderingPhase.camera || settings.renderingPhase.renderingGroupID == null) {
  16725. throw Error("You have to specify a valid camera and renderingGroup");
  16726. }
  16727. _this._renderingGroupObserver = _this._scene.onRenderingGroupObservable.add(function (e, s) {
  16728. if ((_this._scene.activeCamera === settings.renderingPhase.camera) && (e.renderStage === BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT)) {
  16729. _this._engine.clear(null, false, true, true);
  16730. BABYLON.C2DLogging._startFrameRender();
  16731. _this._render();
  16732. BABYLON.C2DLogging._endFrameRender();
  16733. }
  16734. }, Math.pow(2, settings.renderingPhase.renderingGroupID));
  16735. }
  16736. else {
  16737. _this._afterRenderObserver = _this._scene.onAfterRenderObservable.add(function (d, s) {
  16738. _this._engine.clear(null, false, true, true);
  16739. BABYLON.C2DLogging._startFrameRender();
  16740. _this._render();
  16741. BABYLON.C2DLogging._endFrameRender();
  16742. });
  16743. }
  16744. }
  16745. else {
  16746. _this._beforeRenderObserver = _this._scene.onBeforeRenderObservable.add(function (d, s) {
  16747. BABYLON.C2DLogging._startFrameRender();
  16748. _this._render();
  16749. BABYLON.C2DLogging._endFrameRender();
  16750. });
  16751. }
  16752. _this._supprtInstancedArray = _this._engine.getCaps().instancedArrays !== null;
  16753. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  16754. // Setup the canvas for interaction (or not)
  16755. _this._setupInteraction(enableInteraction);
  16756. // Initialize the Primitive Collision Manager
  16757. if (settings.enableCollisionManager) {
  16758. var enableBorders = settings.collisionManagerUseBorders;
  16759. _this._primitiveCollisionManager = (settings.customCollisionManager == null) ? BABYLON.PrimitiveCollisionManagerBase.allocBasicPCM(_this, enableBorders) : settings.customCollisionManager(_this, enableBorders);
  16760. }
  16761. // Register this instance
  16762. Canvas2D_1._INSTANCES.push(_this);
  16763. return _this;
  16764. }
  16765. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  16766. get: function () {
  16767. if (!this._drawCallsOpaqueCounter) {
  16768. this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  16769. }
  16770. return this._drawCallsOpaqueCounter;
  16771. },
  16772. enumerable: true,
  16773. configurable: true
  16774. });
  16775. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  16776. get: function () {
  16777. if (!this._drawCallsAlphaTestCounter) {
  16778. this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  16779. }
  16780. return this._drawCallsAlphaTestCounter;
  16781. },
  16782. enumerable: true,
  16783. configurable: true
  16784. });
  16785. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  16786. get: function () {
  16787. if (!this._drawCallsTransparentCounter) {
  16788. this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  16789. }
  16790. return this._drawCallsTransparentCounter;
  16791. },
  16792. enumerable: true,
  16793. configurable: true
  16794. });
  16795. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  16796. get: function () {
  16797. if (!this._groupRenderCounter) {
  16798. this._groupRenderCounter = new BABYLON.PerfCounter();
  16799. }
  16800. return this._groupRenderCounter;
  16801. },
  16802. enumerable: true,
  16803. configurable: true
  16804. });
  16805. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  16806. get: function () {
  16807. if (!this._updateTransparentDataCounter) {
  16808. this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  16809. }
  16810. return this._updateTransparentDataCounter;
  16811. },
  16812. enumerable: true,
  16813. configurable: true
  16814. });
  16815. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  16816. get: function () {
  16817. if (!this._updateCachedStateCounter) {
  16818. this._updateCachedStateCounter = new BABYLON.PerfCounter();
  16819. }
  16820. return this._updateCachedStateCounter;
  16821. },
  16822. enumerable: true,
  16823. configurable: true
  16824. });
  16825. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  16826. get: function () {
  16827. if (!this._updateLayoutCounter) {
  16828. this._updateLayoutCounter = new BABYLON.PerfCounter();
  16829. }
  16830. return this._updateLayoutCounter;
  16831. },
  16832. enumerable: true,
  16833. configurable: true
  16834. });
  16835. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  16836. get: function () {
  16837. if (!this._updatePositioningCounter) {
  16838. this._updatePositioningCounter = new BABYLON.PerfCounter();
  16839. }
  16840. return this._updatePositioningCounter;
  16841. },
  16842. enumerable: true,
  16843. configurable: true
  16844. });
  16845. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  16846. get: function () {
  16847. if (!this._updateLocalTransformCounter) {
  16848. this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  16849. }
  16850. return this._updateLocalTransformCounter;
  16851. },
  16852. enumerable: true,
  16853. configurable: true
  16854. });
  16855. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  16856. get: function () {
  16857. if (!this._updateGlobalTransformCounter) {
  16858. this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  16859. }
  16860. return this._updateGlobalTransformCounter;
  16861. },
  16862. enumerable: true,
  16863. configurable: true
  16864. });
  16865. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  16866. get: function () {
  16867. if (!this._boundingInfoRecomputeCounter) {
  16868. this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  16869. }
  16870. return this._boundingInfoRecomputeCounter;
  16871. },
  16872. enumerable: true,
  16873. configurable: true
  16874. });
  16875. Object.defineProperty(Canvas2D.prototype, "layoutBoundingInfoUpdateCounter", {
  16876. get: function () {
  16877. if (!this._layoutBoundingInfoUpdateCounter) {
  16878. this._layoutBoundingInfoUpdateCounter = new BABYLON.PerfCounter();
  16879. }
  16880. return this._layoutBoundingInfoUpdateCounter;
  16881. },
  16882. enumerable: true,
  16883. configurable: true
  16884. });
  16885. Object.defineProperty(Canvas2D.prototype, "canvasRenderTimeCounter", {
  16886. get: function () {
  16887. if (!this._canvasRenderTimeCounter) {
  16888. this._canvasRenderTimeCounter = new BABYLON.PerfCounter();
  16889. }
  16890. return this._canvasRenderTimeCounter;
  16891. },
  16892. enumerable: true,
  16893. configurable: true
  16894. });
  16895. Object.defineProperty(Canvas2D, "instances", {
  16896. get: function () {
  16897. return Canvas2D_1._INSTANCES;
  16898. },
  16899. enumerable: true,
  16900. configurable: true
  16901. });
  16902. Object.defineProperty(Canvas2D.prototype, "primitiveCollisionManager", {
  16903. get: function () {
  16904. return this._primitiveCollisionManager;
  16905. },
  16906. enumerable: true,
  16907. configurable: true
  16908. });
  16909. Canvas2D.prototype._canvasPreInit = function (settings) {
  16910. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D_1.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  16911. this._cachingStrategy = cachingStrategy;
  16912. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  16913. };
  16914. Canvas2D.prototype._setupInteraction = function (enable) {
  16915. var _this = this;
  16916. // No change detection
  16917. if (enable === this._interactionEnabled) {
  16918. return;
  16919. }
  16920. // Set the new state
  16921. this._interactionEnabled = enable;
  16922. // ScreenSpace mode
  16923. if (this._isScreenSpace) {
  16924. // Disable interaction
  16925. if (!enable) {
  16926. if (this._scenePrePointerObserver) {
  16927. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  16928. this._scenePrePointerObserver = null;
  16929. }
  16930. return;
  16931. }
  16932. // Enable Interaction
  16933. // Register the observable
  16934. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  16935. if (_this.isVisible === false) {
  16936. return;
  16937. }
  16938. var hs = 1 / _this.engine.getHardwareScalingLevel();
  16939. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  16940. _this._handlePointerEventForInteraction(e, localPos, s);
  16941. });
  16942. }
  16943. else {
  16944. var scene = this.scene;
  16945. if (enable) {
  16946. scene.constantlyUpdateMeshUnderPointer = true;
  16947. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  16948. if (_this.isVisible === false) {
  16949. return;
  16950. }
  16951. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  16952. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  16953. _this._handlePointerEventForInteraction(e, localPos, s);
  16954. }
  16955. else if (_this._actualIntersectionList && _this._actualIntersectionList.length > 0) {
  16956. _this._handlePointerEventForInteraction(e, null, s);
  16957. }
  16958. });
  16959. }
  16960. else {
  16961. if (this._scenePointerObserver) {
  16962. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  16963. this._scenePointerObserver = null;
  16964. }
  16965. }
  16966. }
  16967. };
  16968. /**
  16969. * Internal method, you should use the Prim2DBase version instead
  16970. */
  16971. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  16972. if (this.isPointerCaptured(pointerId)) {
  16973. return false;
  16974. }
  16975. // Try to capture the pointer on the HTML side
  16976. try {
  16977. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  16978. }
  16979. catch (e) {
  16980. }
  16981. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  16982. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  16983. this._capturedPointers.add(pointerId.toString(), primitive);
  16984. return true;
  16985. };
  16986. /**
  16987. * Internal method, you should use the Prim2DBase version instead
  16988. */
  16989. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  16990. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  16991. return false;
  16992. }
  16993. // Try to release the pointer on the HTML side
  16994. try {
  16995. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  16996. }
  16997. catch (e) {
  16998. }
  16999. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  17000. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  17001. this._capturedPointers.remove(pointerId.toString());
  17002. return true;
  17003. };
  17004. /**
  17005. * Determine if the given pointer is captured or not
  17006. * @param pointerId the Id of the pointer
  17007. * @return true if it's captured, false otherwise
  17008. */
  17009. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  17010. return this._capturedPointers.contains(pointerId.toString());
  17011. };
  17012. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  17013. // Avoid unnecessary lookup
  17014. if (this._capturedPointers.count === 0) {
  17015. return null;
  17016. }
  17017. return this._capturedPointers.get(pointerId.toString());
  17018. };
  17019. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  17020. // Dispose check
  17021. if (this.isDisposed) {
  17022. return;
  17023. }
  17024. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  17025. if (localPosition) {
  17026. if (!this._updatePointerInfo(eventData, localPosition)) {
  17027. return;
  17028. }
  17029. }
  17030. else {
  17031. this._primPointerInfo.canvasPointerPos = null;
  17032. }
  17033. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  17034. // Make sure the intersection list is up to date, we maintain this list either in response of a mouse event (here) or before rendering the canvas.
  17035. // Why before rendering the canvas? because some primitives may move and get away/under the mouse cursor (which is not moving). So we need to update at both location in order to always have an accurate list, which is needed for the hover state change.
  17036. this._updateIntersectionList(localPosition ? this._primPointerInfo.canvasPointerPos : null, capturedPrim !== null, true);
  17037. // Update the over status, same as above, it's could be done here or during rendering, but will be performed only once per render frame
  17038. this._updateOverStatus(true);
  17039. // Check if we have nothing to raise
  17040. if (!this._actualOverPrimitive && !capturedPrim) {
  17041. return;
  17042. }
  17043. // Update the relatedTarget info with the over primitive or the captured one (if any)
  17044. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  17045. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  17046. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  17047. // Analyze the pointer event type and fire proper events on the primitive
  17048. var skip = false;
  17049. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  17050. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData);
  17051. }
  17052. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  17053. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData);
  17054. }
  17055. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  17056. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData);
  17057. }
  17058. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  17059. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData);
  17060. }
  17061. eventState.skipNextObservers = skip;
  17062. };
  17063. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  17064. var s = this.scale;
  17065. var pii = this._primPointerInfo;
  17066. pii.cancelBubble = false;
  17067. if (!pii.canvasPointerPos) {
  17068. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  17069. }
  17070. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  17071. if (!camera || !camera.viewport) {
  17072. return false;
  17073. }
  17074. var engine = this._scene.getEngine();
  17075. if (this._isScreenSpace) {
  17076. var cameraViewport = camera.viewport;
  17077. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17078. // Moving coordinates to local viewport world
  17079. var x = localPosition.x - viewport.x;
  17080. var y = localPosition.y - viewport.y;
  17081. pii.canvasPointerPos.x = (x - this.actualPosition.x) / s;
  17082. pii.canvasPointerPos.y = (engine.getRenderHeight() - y - this.actualPosition.y) / s;
  17083. }
  17084. else {
  17085. pii.canvasPointerPos.x = localPosition.x / s;
  17086. pii.canvasPointerPos.y = localPosition.y / s;
  17087. }
  17088. //console.log(`UpdatePointerInfo for ${this.id}, X:${pii.canvasPointerPos.x}, Y:${pii.canvasPointerPos.y}`);
  17089. pii.mouseWheelDelta = 0;
  17090. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  17091. var event = eventData.event;
  17092. if (event.wheelDelta) {
  17093. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  17094. }
  17095. else if (event.detail) {
  17096. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  17097. }
  17098. }
  17099. else {
  17100. var pe = eventData.event;
  17101. pii.ctrlKey = pe.ctrlKey;
  17102. pii.altKey = pe.altKey;
  17103. pii.shiftKey = pe.shiftKey;
  17104. pii.metaKey = pe.metaKey;
  17105. pii.button = pe.button;
  17106. pii.buttons = pe.buttons;
  17107. pii.pointerId = pe.pointerId;
  17108. pii.width = pe.width;
  17109. pii.height = pe.height;
  17110. pii.presssure = pe.pressure;
  17111. pii.tilt.x = pe.tiltX;
  17112. pii.tilt.y = pe.tiltY;
  17113. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  17114. }
  17115. return true;
  17116. };
  17117. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture, force) {
  17118. if (!force && (this.scene.getRenderId() === this._intersectionRenderId)) {
  17119. return;
  17120. }
  17121. var ii = Canvas2D_1._interInfo;
  17122. var outCase = mouseLocalPos == null;
  17123. if (!outCase) {
  17124. // A little safe guard, it might happens than the event is triggered before the first render and nothing is computed, this simple check will make sure everything will be fine
  17125. if (!this._globalTransform) {
  17126. this.updateCachedStates(true);
  17127. }
  17128. ii.pickPosition.x = mouseLocalPos.x;
  17129. ii.pickPosition.y = mouseLocalPos.y;
  17130. ii.findFirstOnly = false;
  17131. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  17132. if (!isCapture && !this.levelBoundingInfo.doesIntersect(ii.pickPosition)) {
  17133. // Reset intersection info as we don't hit anything
  17134. ii.intersectedPrimitives = new Array();
  17135. ii.topMostIntersectedPrimitive = null;
  17136. }
  17137. else {
  17138. // The pointer is inside the Canvas, do an intersection test
  17139. this.intersect(ii);
  17140. // Sort primitives to get them from top to bottom
  17141. ii.intersectedPrimitives = ii.intersectedPrimitives.sort(function (a, b) { return a.prim.actualZOffset - b.prim.actualZOffset; });
  17142. }
  17143. }
  17144. {
  17145. // Update prev/actual intersection info, fire "overPrim" property change if needed
  17146. this._previousIntersectionList = this._actualIntersectionList;
  17147. this._actualIntersectionList = outCase ? new Array() : ii.intersectedPrimitives;
  17148. this._previousOverPrimitive = this._actualOverPrimitive;
  17149. this._actualOverPrimitive = outCase ? null : ii.topMostIntersectedPrimitive;
  17150. var prev = (this._previousOverPrimitive != null) ? this._previousOverPrimitive.prim : null;
  17151. var actual = (this._actualOverPrimitive != null) ? this._actualOverPrimitive.prim : null;
  17152. if (prev !== actual) {
  17153. this.onPropertyChanged("overPrim", this._previousOverPrimitive ? this._previousOverPrimitive.prim : null, this._actualOverPrimitive ? this._actualOverPrimitive.prim : null);
  17154. }
  17155. }
  17156. this._intersectionRenderId = this.scene.getRenderId();
  17157. };
  17158. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  17159. Canvas2D.prototype._updateOverStatus = function (force) {
  17160. if ((!force && (this.scene.getRenderId() === this._hoverStatusRenderId)) || !this._actualIntersectionList) {
  17161. return;
  17162. }
  17163. if (this._previousIntersectionList == null) {
  17164. this._previousIntersectionList = [];
  17165. }
  17166. // Detect a change of over
  17167. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  17168. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  17169. if (prevPrim !== actualPrim) {
  17170. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  17171. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  17172. // See the NOTE section of: https://www.w3.org/TR/pointerevents/#setting-pointer-capture
  17173. if (capturedPrim) {
  17174. if (capturedPrim === prevPrim) {
  17175. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  17176. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  17177. }
  17178. else if (capturedPrim === actualPrim) {
  17179. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  17180. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  17181. }
  17182. }
  17183. else {
  17184. var _loop_1 = function (prev) {
  17185. if (!BABYLON.Tools.first(this_1._actualIntersectionList, function (pii) { return pii.prim === prev.prim; })) {
  17186. this_1._primPointerInfo.updateRelatedTarget(prev.prim, prev.intersectionLocation);
  17187. this_1._bubbleNotifyPrimPointerObserver(prev.prim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  17188. }
  17189. };
  17190. var this_1 = this;
  17191. // Check for Out & Leave
  17192. for (var _i = 0, _a = this._previousIntersectionList; _i < _a.length; _i++) {
  17193. var prev = _a[_i];
  17194. _loop_1(prev);
  17195. }
  17196. var _loop_2 = function (actual) {
  17197. if (!BABYLON.Tools.first(this_2._previousIntersectionList, function (pii) { return pii.prim === actual.prim; })) {
  17198. this_2._primPointerInfo.updateRelatedTarget(actual.prim, actual.intersectionLocation);
  17199. this_2._bubbleNotifyPrimPointerObserver(actual.prim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  17200. }
  17201. };
  17202. var this_2 = this;
  17203. // Check for Over & Enter
  17204. for (var _b = 0, _c = this._actualIntersectionList; _b < _c.length; _b++) {
  17205. var actual = _c[_b];
  17206. _loop_2(actual);
  17207. }
  17208. }
  17209. }
  17210. this._hoverStatusRenderId = this.scene.getRenderId();
  17211. };
  17212. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  17213. if (this._primPointerInfo.isCaptured) {
  17214. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  17215. }
  17216. else {
  17217. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  17218. var pii = _a[_i];
  17219. if (pii.prim === prim) {
  17220. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  17221. return;
  17222. }
  17223. }
  17224. }
  17225. };
  17226. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  17227. if (!this._notifDebugMode) {
  17228. return;
  17229. }
  17230. var debug = "";
  17231. for (var i = 0; i < prim.hierarchyDepth; i++) {
  17232. debug += " ";
  17233. }
  17234. var pii = this._primPointerInfo;
  17235. debug += "[RID:" + this.scene.getRenderId() + "] [" + prim.hierarchyDepth + "] event:" + BABYLON.PrimitivePointerInfo.getEventTypeName(mask) + ", id: " + prim.id + " (" + BABYLON.Tools.getClassName(prim) + "), primPos: " + pii.primitivePointerPos.toString() + ", canvasPos: " + pii.canvasPointerPos.toString() + ", relatedTarget: " + pii.relatedTarget.id;
  17236. console.log(debug);
  17237. };
  17238. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  17239. var ppi = this._primPointerInfo;
  17240. var event = eventData ? eventData.event : null;
  17241. var cur = prim;
  17242. while (cur && !cur.isDisposed) {
  17243. this._updatePrimPointerPos(cur);
  17244. // For the first level we have to fire Enter or Leave for corresponding Over or Out
  17245. if (cur === prim) {
  17246. // Fire the proper notification
  17247. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  17248. this._debugExecObserver(prim, BABYLON.PrimitivePointerInfo.PointerEnter);
  17249. prim._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  17250. }
  17251. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  17252. this._debugExecObserver(prim, BABYLON.PrimitivePointerInfo.PointerLeave);
  17253. prim._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  17254. }
  17255. }
  17256. // Exec the observers
  17257. this._debugExecObserver(cur, mask);
  17258. if (!cur._pointerEventObservable.notifyObservers(ppi, mask) && eventData instanceof BABYLON.PointerInfoPre) {
  17259. eventData.skipOnPointerObservable = true;
  17260. return false;
  17261. }
  17262. this._triggerActionManager(cur, ppi, mask, event);
  17263. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  17264. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  17265. if (ppi.cancelBubble) {
  17266. return false;
  17267. }
  17268. // Loop to the parent
  17269. cur = cur.parent;
  17270. }
  17271. return true;
  17272. };
  17273. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  17274. var _this = this;
  17275. // A little safe guard, it might happens than the event is triggered before the first render and nothing is computed, this simple check will make sure everything will be fine
  17276. if (!this._globalTransform) {
  17277. this.updateCachedStates(true);
  17278. }
  17279. // Process Trigger related to PointerDown
  17280. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  17281. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  17282. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  17283. this._pickStartingTime = new Date().getTime();
  17284. this._pickedDownPrim = null;
  17285. if (prim.actionManager) {
  17286. this._pickedDownPrim = prim;
  17287. if (prim.actionManager.hasPickTriggers) {
  17288. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  17289. switch (eventData.button) {
  17290. case 0:
  17291. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  17292. break;
  17293. case 1:
  17294. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  17295. break;
  17296. case 2:
  17297. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  17298. break;
  17299. }
  17300. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  17301. }
  17302. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17303. window.setTimeout(function () {
  17304. var ppi = _this._primPointerInfo;
  17305. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  17306. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null, true);
  17307. _this._updateOverStatus(false);
  17308. var ii = new BABYLON.IntersectInfo2D();
  17309. ii.pickPosition = ppi.canvasPointerPos.clone();
  17310. ii.findFirstOnly = false;
  17311. _this.intersect(ii);
  17312. if (ii.isPrimIntersected(prim) !== null) {
  17313. if (prim.actionManager) {
  17314. if (_this._pickStartingTime !== 0 && ((new Date().getTime() - _this._pickStartingTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(_this._pickStartingPosition.x - ii.pickPosition.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._pickStartingPosition.y - ii.pickPosition.y) < BABYLON.ActionManager.DragMovementThreshold)) {
  17315. _this._pickStartingTime = 0;
  17316. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  17317. }
  17318. }
  17319. }
  17320. }, BABYLON.ActionManager.LongPressDelay);
  17321. }
  17322. }
  17323. }
  17324. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  17325. this._pickStartingTime = 0;
  17326. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  17327. if (prim.actionManager) {
  17328. // OnPickUpTrigger
  17329. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  17330. // OnPickTrigger
  17331. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  17332. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  17333. }
  17334. }
  17335. // OnPickOutTrigger
  17336. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  17337. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  17338. }
  17339. }
  17340. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  17341. if (prim.actionManager) {
  17342. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  17343. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  17344. }
  17345. }
  17346. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  17347. if (prim.actionManager) {
  17348. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  17349. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  17350. }
  17351. }
  17352. };
  17353. /**
  17354. * Don't forget to call the dispose method when you're done with the Canvas instance.
  17355. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  17356. */
  17357. Canvas2D.prototype.dispose = function () {
  17358. if (!_super.prototype.dispose.call(this)) {
  17359. return false;
  17360. }
  17361. if (this._profilingCanvas) {
  17362. this._profilingCanvas.dispose();
  17363. this._profilingCanvas = null;
  17364. }
  17365. if (this.interactionEnabled) {
  17366. this._setupInteraction(false);
  17367. }
  17368. if (this._renderingGroupObserver) {
  17369. this._scene.onRenderingGroupObservable.remove(this._renderingGroupObserver);
  17370. this._renderingGroupObserver = null;
  17371. }
  17372. if (this._beforeRenderObserver) {
  17373. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  17374. this._beforeRenderObserver = null;
  17375. }
  17376. if (this._afterRenderObserver) {
  17377. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  17378. this._afterRenderObserver = null;
  17379. }
  17380. if (this._groupCacheMaps) {
  17381. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  17382. this._groupCacheMaps = null;
  17383. }
  17384. // Unregister this instance
  17385. var index = Canvas2D_1._INSTANCES.indexOf(this);
  17386. if (index > -1) {
  17387. Canvas2D_1._INSTANCES.splice(index, 1);
  17388. }
  17389. return true;
  17390. };
  17391. Object.defineProperty(Canvas2D.prototype, "scene", {
  17392. /**
  17393. * Accessor to the Scene that owns the Canvas
  17394. * @returns The instance of the Scene object
  17395. */
  17396. get: function () {
  17397. return this._scene;
  17398. },
  17399. enumerable: true,
  17400. configurable: true
  17401. });
  17402. Object.defineProperty(Canvas2D.prototype, "engine", {
  17403. /**
  17404. * Accessor to the Engine that drives the Scene used by this Canvas
  17405. * @returns The instance of the Engine object
  17406. */
  17407. get: function () {
  17408. return this._engine;
  17409. },
  17410. enumerable: true,
  17411. configurable: true
  17412. });
  17413. Object.defineProperty(Canvas2D.prototype, "renderObservable", {
  17414. /**
  17415. * And observable called during the Canvas rendering process.
  17416. * This observable is called twice per render, each time with a different mask:
  17417. * - 1: before render is executed
  17418. * - 2: after render is executed
  17419. */
  17420. get: function () {
  17421. if (!this._renderObservable) {
  17422. this._renderObservable = new BABYLON.Observable();
  17423. }
  17424. return this._renderObservable;
  17425. },
  17426. enumerable: true,
  17427. configurable: true
  17428. });
  17429. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  17430. /**
  17431. * Accessor of the Caching Strategy used by this Canvas.
  17432. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  17433. * @returns the value corresponding to the used strategy.
  17434. */
  17435. get: function () {
  17436. return this._cachingStrategy;
  17437. },
  17438. enumerable: true,
  17439. configurable: true
  17440. });
  17441. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  17442. /**
  17443. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  17444. * @returns {}
  17445. */
  17446. get: function () {
  17447. return this._isScreenSpace;
  17448. },
  17449. enumerable: true,
  17450. configurable: true
  17451. });
  17452. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  17453. /**
  17454. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  17455. */
  17456. get: function () {
  17457. return this._worldSpaceNode;
  17458. },
  17459. set: function (val) {
  17460. this._worldSpaceNode = val;
  17461. },
  17462. enumerable: true,
  17463. configurable: true
  17464. });
  17465. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  17466. /**
  17467. * Check if the WebGL Instanced Array extension is supported or not
  17468. */
  17469. get: function () {
  17470. return this._supprtInstancedArray;
  17471. },
  17472. enumerable: true,
  17473. configurable: true
  17474. });
  17475. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  17476. /**
  17477. * Property that defines the fill object used to draw the background of the Canvas.
  17478. * Note that Canvas with a Caching Strategy of
  17479. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  17480. */
  17481. get: function () {
  17482. if (!this._background || !this._background.isVisible) {
  17483. return null;
  17484. }
  17485. return this._background.fill;
  17486. },
  17487. set: function (value) {
  17488. this.checkBackgroundAvailability();
  17489. if (value === this._background.fill) {
  17490. return;
  17491. }
  17492. this._background.fill = value;
  17493. this._background.levelVisible = true;
  17494. },
  17495. enumerable: true,
  17496. configurable: true
  17497. });
  17498. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  17499. /**
  17500. * Property that defines the border object used to draw the background of the Canvas.
  17501. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  17502. */
  17503. get: function () {
  17504. if (!this._background || !this._background.isVisible) {
  17505. return null;
  17506. }
  17507. return this._background.border;
  17508. },
  17509. set: function (value) {
  17510. this.checkBackgroundAvailability();
  17511. if (value === this._background.border) {
  17512. return;
  17513. }
  17514. this._background.border = value;
  17515. this._background.levelVisible = true;
  17516. },
  17517. enumerable: true,
  17518. configurable: true
  17519. });
  17520. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  17521. /**
  17522. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  17523. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  17524. */
  17525. get: function () {
  17526. if (!this._background || !this._background.isVisible) {
  17527. return null;
  17528. }
  17529. return this._background.borderThickness;
  17530. },
  17531. set: function (value) {
  17532. this.checkBackgroundAvailability();
  17533. if (value === this._background.borderThickness) {
  17534. return;
  17535. }
  17536. this._background.borderThickness = value;
  17537. },
  17538. enumerable: true,
  17539. configurable: true
  17540. });
  17541. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  17542. /**
  17543. * You can set the roundRadius of the background
  17544. * @returns The current roundRadius
  17545. */
  17546. get: function () {
  17547. if (!this._background || !this._background.isVisible) {
  17548. return null;
  17549. }
  17550. return this._background.roundRadius;
  17551. },
  17552. set: function (value) {
  17553. this.checkBackgroundAvailability();
  17554. if (value === this._background.roundRadius) {
  17555. return;
  17556. }
  17557. this._background.roundRadius = value;
  17558. this._background.levelVisible = true;
  17559. },
  17560. enumerable: true,
  17561. configurable: true
  17562. });
  17563. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  17564. /**
  17565. * Enable/Disable interaction for this Canvas
  17566. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  17567. */
  17568. get: function () {
  17569. return this._interactionEnabled;
  17570. },
  17571. set: function (enable) {
  17572. this._setupInteraction(enable);
  17573. },
  17574. enumerable: true,
  17575. configurable: true
  17576. });
  17577. Object.defineProperty(Canvas2D.prototype, "fitRenderingDevice", {
  17578. get: function () {
  17579. return this._fitRenderingDevice;
  17580. },
  17581. enumerable: true,
  17582. configurable: true
  17583. });
  17584. Object.defineProperty(Canvas2D.prototype, "designSize", {
  17585. get: function () {
  17586. return this._designSize;
  17587. },
  17588. enumerable: true,
  17589. configurable: true
  17590. });
  17591. Object.defineProperty(Canvas2D.prototype, "designSizeUseHorizAxis", {
  17592. get: function () {
  17593. return this._designUseHorizAxis;
  17594. },
  17595. enumerable: true,
  17596. configurable: true
  17597. });
  17598. Object.defineProperty(Canvas2D.prototype, "designSizeUseHorizeAxis", {
  17599. set: function (value) {
  17600. this._designUseHorizAxis = value;
  17601. },
  17602. enumerable: true,
  17603. configurable: true
  17604. });
  17605. Object.defineProperty(Canvas2D.prototype, "overPrim", {
  17606. /**
  17607. * Return
  17608. */
  17609. get: function () {
  17610. if (this._actualIntersectionList && this._actualIntersectionList.length > 0) {
  17611. return this._actualIntersectionList[0].prim;
  17612. }
  17613. return null;
  17614. },
  17615. enumerable: true,
  17616. configurable: true
  17617. });
  17618. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  17619. /**
  17620. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  17621. * @returns {}
  17622. */
  17623. get: function () {
  17624. return this.__engineData;
  17625. },
  17626. enumerable: true,
  17627. configurable: true
  17628. });
  17629. Object.defineProperty(Canvas2D.prototype, "unitScaleFactor", {
  17630. get: function () {
  17631. return this._unitScaleFactor;
  17632. },
  17633. enumerable: true,
  17634. configurable: true
  17635. });
  17636. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  17637. if (this._profilingCanvas) {
  17638. return this._profilingCanvas;
  17639. }
  17640. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  17641. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D_1.CACHESTRATEGY_DONTCACHE, children: [
  17642. new BABYLON.Rectangle2D({
  17643. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  17644. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "12pt Lucida Console", fontSignedDistanceField: true })
  17645. ]
  17646. })
  17647. ]
  17648. });
  17649. this._profileInfoText = canvas.findById("ProfileInfoText");
  17650. this._profilingCanvas = canvas;
  17651. return canvas;
  17652. };
  17653. Canvas2D.prototype.checkBackgroundAvailability = function () {
  17654. if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_TOPLEVELGROUPS) {
  17655. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  17656. }
  17657. };
  17658. Canvas2D.prototype._initPerfMetrics = function () {
  17659. this.drawCallsOpaqueCounter.fetchNewFrame();
  17660. this.drawCallsAlphaTestCounter.fetchNewFrame();
  17661. this.drawCallsTransparentCounter.fetchNewFrame();
  17662. this.groupRenderCounter.fetchNewFrame();
  17663. this.updateTransparentDataCounter.fetchNewFrame();
  17664. this.updateCachedStateCounter.fetchNewFrame();
  17665. this.updateLayoutCounter.fetchNewFrame();
  17666. this.updatePositioningCounter.fetchNewFrame();
  17667. this.updateLocalTransformCounter.fetchNewFrame();
  17668. this.updateGlobalTransformCounter.fetchNewFrame();
  17669. this.boundingInfoRecomputeCounter.fetchNewFrame();
  17670. this.layoutBoundingInfoUpdateCounter.fetchNewFrame();
  17671. this.canvasRenderTimeCounter.beginMonitoring();
  17672. };
  17673. Canvas2D.prototype._fetchPerfMetrics = function () {
  17674. this.drawCallsOpaqueCounter.addCount(0, true);
  17675. this.drawCallsAlphaTestCounter.addCount(0, true);
  17676. this.drawCallsTransparentCounter.addCount(0, true);
  17677. this.groupRenderCounter.addCount(0, true);
  17678. this.updateTransparentDataCounter.addCount(0, true);
  17679. this.updateCachedStateCounter.addCount(0, true);
  17680. this.updateLayoutCounter.addCount(0, true);
  17681. this.updatePositioningCounter.addCount(0, true);
  17682. this.updateLocalTransformCounter.addCount(0, true);
  17683. this.updateGlobalTransformCounter.addCount(0, true);
  17684. this.boundingInfoRecomputeCounter.addCount(0, true);
  17685. this.layoutBoundingInfoUpdateCounter.addCount(0, true);
  17686. this.canvasRenderTimeCounter.endMonitoring(true);
  17687. };
  17688. Canvas2D.prototype._updateProfileCanvas = function () {
  17689. if (this._profileInfoText == null) {
  17690. return;
  17691. }
  17692. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  17693. var p = "Render Time: avg:" + format(this.canvasRenderTimeCounter.lastSecAverage) + "ms " + format(this.canvasRenderTimeCounter.current) + "ms\n" +
  17694. "Draw Calls:\n" +
  17695. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  17696. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  17697. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  17698. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  17699. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  17700. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  17701. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  17702. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  17703. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  17704. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  17705. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n") +
  17706. (" - LayoutBoundingInfo Recompute: " + this.layoutBoundingInfoUpdateCounter.current + ", (avg:" + format(this.layoutBoundingInfoUpdateCounter.lastSecAverage) + ", t:" + format(this.layoutBoundingInfoUpdateCounter.total) + ")");
  17707. this._profileInfoText.text = p;
  17708. };
  17709. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  17710. switch (renderMode) {
  17711. case BABYLON.Render2DContext.RenderModeOpaque:
  17712. this._drawCallsOpaqueCounter.addCount(count, false);
  17713. return;
  17714. case BABYLON.Render2DContext.RenderModeAlphaTest:
  17715. this._drawCallsAlphaTestCounter.addCount(count, false);
  17716. return;
  17717. case BABYLON.Render2DContext.RenderModeTransparent:
  17718. this._drawCallsTransparentCounter.addCount(count, false);
  17719. return;
  17720. }
  17721. };
  17722. Canvas2D.prototype._addGroupRenderCount = function (count) {
  17723. if (this._groupRenderCounter) {
  17724. this._groupRenderCounter.addCount(count, false);
  17725. }
  17726. };
  17727. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  17728. if (this._updateTransparentDataCounter) {
  17729. this._updateTransparentDataCounter.addCount(count, false);
  17730. }
  17731. };
  17732. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  17733. if (this._updateCachedStateCounter) {
  17734. this._updateCachedStateCounter.addCount(count, false);
  17735. }
  17736. };
  17737. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  17738. if (this._updateLayoutCounter) {
  17739. this._updateLayoutCounter.addCount(count, false);
  17740. }
  17741. };
  17742. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  17743. if (this._updatePositioningCounter) {
  17744. this._updatePositioningCounter.addCount(count, false);
  17745. }
  17746. };
  17747. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  17748. if (this._updateLocalTransformCounter) {
  17749. this._updateLocalTransformCounter.addCount(count, false);
  17750. }
  17751. };
  17752. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  17753. if (this._updateGlobalTransformCounter) {
  17754. this._updateGlobalTransformCounter.addCount(count, false);
  17755. }
  17756. };
  17757. Canvas2D.prototype.addLayoutBoundingInfoUpdateCounter = function (count) {
  17758. if (this._layoutBoundingInfoUpdateCounter) {
  17759. this._layoutBoundingInfoUpdateCounter.addCount(count, false);
  17760. }
  17761. };
  17762. Canvas2D.prototype._updateTrackedNodes = function () {
  17763. // Get the used camera
  17764. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  17765. // Compute some matrix stuff
  17766. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D_1._m);
  17767. var rh = this.engine.getRenderHeight();
  17768. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  17769. var tmpVec3 = Canvas2D_1._tmpVec3;
  17770. var tmpMtx = Canvas2D_1._tmpMtx;
  17771. // Compute the screen position of each group that track a given scene node
  17772. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  17773. var group = _a[_i];
  17774. if (group.isDisposed) {
  17775. continue;
  17776. }
  17777. var node = group.trackedNode;
  17778. var worldMtx = node.getWorldMatrix();
  17779. if (group.trackedNodeOffset) {
  17780. BABYLON.Vector3.TransformCoordinatesToRef(group.trackedNodeOffset, worldMtx, tmpVec3);
  17781. tmpMtx.copyFrom(worldMtx);
  17782. worldMtx = tmpMtx;
  17783. worldMtx.setTranslation(tmpVec3);
  17784. }
  17785. var proj = BABYLON.Vector3.Project(Canvas2D_1._v, worldMtx, Canvas2D_1._m, v);
  17786. // Set the visibility state accordingly, if the position is outside the frustum (well on the Z planes only...) set the group to hidden
  17787. group.levelVisible = proj.z >= 0 && proj.z < 1.0;
  17788. var s = this.scale;
  17789. group.x = Math.round(proj.x / s);
  17790. group.y = Math.round((rh - proj.y) / s);
  17791. }
  17792. // If it's a WorldSpaceCanvas and it's tracking a node, let's update the WSC transformation data
  17793. if (this._trackNode) {
  17794. var rot = null;
  17795. var scale = null;
  17796. var worldmtx = this._trackNode.getWorldMatrix();
  17797. var pos = worldmtx.getTranslation().add(this._trackNodeOffset);
  17798. var wsc = this;
  17799. var wsn = wsc.worldSpaceCanvasNode;
  17800. if (this._trackNodeBillboard) {
  17801. var viewMtx = cam.getViewMatrix().clone().invert();
  17802. viewMtx.decompose(Canvas2D_1.tS, Canvas2D_1.tR, Canvas2D_1.tT);
  17803. rot = Canvas2D_1.tR.clone();
  17804. }
  17805. worldmtx.decompose(Canvas2D_1.tS, Canvas2D_1.tR, Canvas2D_1.tT);
  17806. var mtx = BABYLON.Matrix.Compose(Canvas2D_1.tS, Canvas2D_1.tR, BABYLON.Vector3.Zero());
  17807. pos = worldmtx.getTranslation().add(BABYLON.Vector3.TransformCoordinates(this._trackNodeOffset, mtx));
  17808. if (Canvas2D_1.tS.lengthSquared() !== 1) {
  17809. scale = Canvas2D_1.tS.clone();
  17810. }
  17811. if (!this._trackNodeBillboard) {
  17812. rot = Canvas2D_1.tR.clone();
  17813. }
  17814. if (wsn instanceof BABYLON.AbstractMesh) {
  17815. wsn.position = pos;
  17816. wsn.rotationQuaternion = rot;
  17817. if (scale) {
  17818. wsn.scaling = scale;
  17819. }
  17820. }
  17821. else {
  17822. throw new Error("Can't Track another Scene Node Type than AbstractMesh right now, call me lazy!");
  17823. }
  17824. }
  17825. };
  17826. /**
  17827. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  17828. */
  17829. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  17830. this._updateCanvasState(forceRecompute);
  17831. };
  17832. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  17833. if (this._globalTransformStep < 2) {
  17834. return;
  17835. }
  17836. var n = this.worldSpaceCanvasNode;
  17837. var bi = n.getBoundingInfo().boundingBox;
  17838. var v = bi.vectorsWorld;
  17839. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  17840. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D_1._m);
  17841. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  17842. var projPoints = new Array(4);
  17843. for (var i = 0; i < 4; i++) {
  17844. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D_1._mI, Canvas2D_1._m, vp);
  17845. }
  17846. var left = projPoints[3].subtract(projPoints[0]).length();
  17847. var top = projPoints[3].subtract(projPoints[1]).length();
  17848. var right = projPoints[1].subtract(projPoints[2]).length();
  17849. var bottom = projPoints[2].subtract(projPoints[0]).length();
  17850. var w = Math.round(Math.max(top, bottom));
  17851. var h = Math.round(Math.max(right, left));
  17852. var isW = w > h;
  17853. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  17854. var edge = Math.max(w, h);
  17855. if (edge < 256) {
  17856. edge = 256;
  17857. }
  17858. else {
  17859. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  17860. }
  17861. // Clip values if needed
  17862. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  17863. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  17864. if (newScale !== this.scale) {
  17865. var scale = newScale;
  17866. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  17867. this._setRenderingScale(scale);
  17868. }
  17869. };
  17870. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  17871. // Check if the update has already been made for this render Frame
  17872. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  17873. return;
  17874. }
  17875. // Detect a change of HWRendering scale
  17876. var hwsl = this.engine.getHardwareScalingLevel();
  17877. this._curHWScale = hwsl;
  17878. // Detect a change of rendering size
  17879. var renderingSizeChanged = false;
  17880. var newWidth = this.engine.getRenderWidth() * hwsl;
  17881. if (newWidth !== this._renderingSize.width) {
  17882. renderingSizeChanged = true;
  17883. }
  17884. this._renderingSize.width = newWidth;
  17885. var newHeight = this.engine.getRenderHeight() * hwsl;
  17886. if (newHeight !== this._renderingSize.height) {
  17887. renderingSizeChanged = true;
  17888. }
  17889. this._renderingSize.height = newHeight;
  17890. var prevCLS = Canvas2D_1._pCLS;
  17891. prevCLS.copyFrom(this._canvasLevelScale);
  17892. // If there's a design size, update the scale according to the renderingSize
  17893. if (this._designSize) {
  17894. var scale = void 0;
  17895. if (this._designUseHorizAxis) {
  17896. scale = this._renderingSize.width / (this._designSize.width * hwsl);
  17897. }
  17898. else {
  17899. scale = this._renderingSize.height / (this._designSize.height * hwsl);
  17900. }
  17901. this.size = this._designSize.clone();
  17902. this._canvasLevelScale.copyFromFloats(scale, scale, 1);
  17903. }
  17904. else {
  17905. var ratio = 1 / this._curHWScale;
  17906. this._canvasLevelScale.copyFromFloats(ratio, ratio, 1);
  17907. }
  17908. if (!prevCLS.equals(this._canvasLevelScale)) {
  17909. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  17910. var child = _a[_i];
  17911. child._setFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  17912. }
  17913. this._setLayoutDirty();
  17914. }
  17915. // If the canvas fit the rendering size and it changed, update
  17916. if (renderingSizeChanged && this._fitRenderingDevice) {
  17917. this.size = this._renderingSize.clone();
  17918. if (this._background) {
  17919. this._background.size = this.size;
  17920. }
  17921. // Dirty the Layout at the Canvas level to recompute as the size changed
  17922. this._setLayoutDirty();
  17923. }
  17924. var context = new BABYLON.PrepareRender2DContext();
  17925. ++this._globalTransformProcessStep;
  17926. this._setFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  17927. this.updateCachedStates(false);
  17928. this._prepareGroupRender(context);
  17929. this._updateRenderId = this.scene.getRenderId();
  17930. };
  17931. /**
  17932. * Method that renders the Canvas, you should not invoke
  17933. */
  17934. Canvas2D.prototype._render = function () {
  17935. this._initPerfMetrics();
  17936. if (this._renderObservable && this._renderObservable.hasObservers()) {
  17937. this._renderObservable.notifyObservers(this, Canvas2D_1.RENDEROBSERVABLE_PRE);
  17938. }
  17939. this._updateCanvasState(false);
  17940. this._updateTrackedNodes();
  17941. // Nothing to do is the Canvas is not visible
  17942. if (this.isVisible === false) {
  17943. return;
  17944. }
  17945. if (!this._isScreenSpace) {
  17946. this._updateAdaptiveSizeWorldCanvas();
  17947. }
  17948. this._updateCanvasState(false);
  17949. if (this._primitiveCollisionManager) {
  17950. this._primitiveCollisionManager._update();
  17951. }
  17952. if (this._primPointerInfo.canvasPointerPos) {
  17953. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false, false);
  17954. this._updateOverStatus(false);
  17955. }
  17956. this.engine.setState(false, undefined, true);
  17957. this._groupRender();
  17958. if (!this._isScreenSpace) {
  17959. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  17960. this.worldSpaceCacheChanged();
  17961. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  17962. }
  17963. }
  17964. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  17965. if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  17966. this._cachedCanvasGroup._renderCachedCanvas();
  17967. }
  17968. this._fetchPerfMetrics();
  17969. this._updateProfileCanvas();
  17970. if (this._renderObservable && this._renderObservable.hasObservers()) {
  17971. this._renderObservable.notifyObservers(this, Canvas2D_1.RENDEROBSERVABLE_POST);
  17972. }
  17973. };
  17974. /**
  17975. * Internal method that allocate a cache for the given group.
  17976. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  17977. * @param group The group to allocate the cache of.
  17978. * @return custom type with the PackedRect instance giving information about the cache location into the texture and also the MapTexture instance that stores the cache.
  17979. */
  17980. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  17981. if (useMipMap === void 0) { useMipMap = false; }
  17982. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  17983. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  17984. var rd = group._renderableData;
  17985. var noResizeScale = rd._noResizeOnScale;
  17986. var isCanvas = parent == null;
  17987. var scale;
  17988. if (noResizeScale) {
  17989. scale = isCanvas ? Canvas2D_1._unS : group.parent.actualScale;
  17990. }
  17991. else {
  17992. scale = group.actualScale;
  17993. }
  17994. // Determine size
  17995. var size = group.actualSize;
  17996. size = new BABYLON.Size(Math.ceil(size.width * scale.x), Math.ceil(size.height * scale.y));
  17997. var originalSize = size.clone();
  17998. if (minSize) {
  17999. size.width = Math.max(minSize.width, size.width);
  18000. size.height = Math.max(minSize.height, size.height);
  18001. }
  18002. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  18003. // Try to find a spot in one of the cached texture
  18004. var res = null;
  18005. var map;
  18006. for (var _i = 0, mapArray_1 = mapArray; _i < mapArray_1.length; _i++) {
  18007. var _map = mapArray_1[_i];
  18008. map = _map;
  18009. var node = map.allocateRect(size);
  18010. if (node) {
  18011. res = { node: node, texture: map };
  18012. break;
  18013. }
  18014. }
  18015. // Couldn't find a map that could fit the rect, create a new map for it
  18016. if (!res) {
  18017. var mapSize = new BABYLON.Size(Canvas2D_1._groupTextureCacheSize, Canvas2D_1._groupTextureCacheSize);
  18018. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  18019. if (size.width > mapSize.width || size.height > mapSize.height) {
  18020. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  18021. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  18022. }
  18023. var id = "groupsMapChache" + this._mapCounter++ + "forCanvas" + this.id;
  18024. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  18025. map.hasAlpha = true;
  18026. map.anisotropicFilteringLevel = 4;
  18027. mapArray.splice(0, 0, map);
  18028. var node = map.allocateRect(size);
  18029. res = { node: node, texture: map };
  18030. }
  18031. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  18032. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  18033. if (group !== this || this._isScreenSpace) {
  18034. var node = res.node;
  18035. // Special case if the canvas is entirely cached: create a group that will have a single sprite it will be rendered specifically at the very end of the rendering process
  18036. var sprite = void 0;
  18037. if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_CANVAS) {
  18038. if (this._cachedCanvasGroup) {
  18039. this._cachedCanvasGroup.dispose();
  18040. }
  18041. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  18042. sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: originalSize, spriteLocation: node.pos });
  18043. sprite.zOrder = 1;
  18044. sprite.origin = BABYLON.Vector2.Zero();
  18045. }
  18046. else {
  18047. sprite = new BABYLON.Sprite2D(map, { parent: parent, id: "__cachedSpriteOfGroup__" + group.id, x: group.actualPosition.x, y: group.actualPosition.y, spriteSize: originalSize, spriteLocation: node.pos, dontInheritParentScale: true });
  18048. sprite.origin = group.origin.clone();
  18049. sprite.addExternalData("__cachedGroup__", group);
  18050. sprite.pointerEventObservable.add(function (e, s) {
  18051. if (group.pointerEventObservable !== null) {
  18052. group.pointerEventObservable.notifyObservers(e, s.mask);
  18053. }
  18054. });
  18055. res.sprite = sprite;
  18056. }
  18057. if (sprite && noResizeScale) {
  18058. var relScale = isCanvas ? group.actualScale : group.actualScale.divide(group.parent.actualScale);
  18059. sprite.scaleX = relScale.x;
  18060. sprite.scaleY = relScale.y;
  18061. }
  18062. }
  18063. return res;
  18064. };
  18065. /**
  18066. * Internal method used to register a Scene Node to track position for the given group
  18067. * Do not invoke this method, for internal purpose only.
  18068. * @param group the group to track its associated Scene Node
  18069. */
  18070. Canvas2D.prototype._registerTrackedNode = function (group) {
  18071. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  18072. return;
  18073. }
  18074. if (!this._trackedGroups) {
  18075. this._trackedGroups = new Array();
  18076. }
  18077. this._trackedGroups.push(group);
  18078. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  18079. };
  18080. /**
  18081. * Internal method used to unregister a tracked Scene Node
  18082. * Do not invoke this method, it's for internal purpose only.
  18083. * @param group the group to unregister its tracked Scene Node from.
  18084. */
  18085. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  18086. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  18087. return;
  18088. }
  18089. var i = this._trackedGroups.indexOf(group);
  18090. if (i !== -1) {
  18091. this._trackedGroups.splice(i, 1);
  18092. }
  18093. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  18094. };
  18095. /**
  18096. * Get a Solid Color Brush instance matching the given color.
  18097. * @param color The color to retrieve
  18098. * @return A shared instance of the SolidColorBrush2D class that use the given color
  18099. */
  18100. Canvas2D.GetSolidColorBrush = function (color) {
  18101. return Canvas2D_1._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  18102. };
  18103. /**
  18104. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  18105. * @param color The color to retrieve
  18106. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  18107. */
  18108. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  18109. return Canvas2D_1._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  18110. };
  18111. /**
  18112. * Get a Gradient Color Brush
  18113. * @param color1 starting color
  18114. * @param color2 engine color
  18115. * @param translation translation vector to apply. default is [0;0]
  18116. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  18117. * @param scale scaling factor to apply. default is 1.
  18118. */
  18119. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  18120. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  18121. if (rotation === void 0) { rotation = 0; }
  18122. if (scale === void 0) { scale = 1; }
  18123. return Canvas2D_1._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  18124. };
  18125. /**
  18126. * Create a solid or gradient brush from a string value.
  18127. * @param brushString should be either
  18128. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  18129. * - "gradient: #FF808080, #FFFFFFF[, [10:20], 180, 1]" for color1, color2, translation, rotation (degree), scale. The last three are optionals, but if specified must be is this order. "gradient:" can be omitted.
  18130. */
  18131. Canvas2D.GetBrushFromString = function (brushString) {
  18132. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  18133. brushString = brushString.trim();
  18134. var split = brushString.split(",");
  18135. // Solid, formatted as: "[solid:]#FF808080"
  18136. if (split.length === 1) {
  18137. var value = null;
  18138. if (brushString.indexOf("solid:") === 0) {
  18139. value = brushString.substr(6).trim();
  18140. }
  18141. else if (brushString.indexOf("#") === 0) {
  18142. value = brushString;
  18143. }
  18144. else {
  18145. return null;
  18146. }
  18147. return Canvas2D_1.GetSolidColorBrushFromHex(value);
  18148. }
  18149. else {
  18150. if (split[0].indexOf("gradient:") === 0) {
  18151. split[0] = split[0].substr(9).trim();
  18152. }
  18153. try {
  18154. var start = BABYLON.Color4.FromHexString(split[0].trim());
  18155. var end = BABYLON.Color4.FromHexString(split[1].trim());
  18156. var t = BABYLON.Vector2.Zero();
  18157. if (split.length > 2) {
  18158. var v = split[2].trim();
  18159. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  18160. return null;
  18161. }
  18162. var sep = v.indexOf(":");
  18163. var x = parseFloat(v.substr(1, sep));
  18164. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  18165. t = new BABYLON.Vector2(x, y);
  18166. }
  18167. var r = 0;
  18168. if (split.length > 3) {
  18169. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  18170. }
  18171. var s = 1;
  18172. if (split.length > 4) {
  18173. s = parseFloat(split[4].trim());
  18174. }
  18175. return Canvas2D_1.GetGradientColorBrush(start, end, t, r, s);
  18176. }
  18177. catch (e) {
  18178. return null;
  18179. }
  18180. }
  18181. };
  18182. return Canvas2D;
  18183. }(BABYLON.Group2D));
  18184. /**
  18185. * In this strategy only the direct children groups of the Canvas will be cached, their whole content (whatever the sub groups they have) into a single bitmap.
  18186. * This strategy doesn't allow primitives added directly as children of the Canvas.
  18187. * You typically want to use this strategy of a screenSpace fullscreen canvas: you don't want a bitmap cache taking the whole screen resolution but still want the main contents (say UI in the topLeft and rightBottom for instance) to be efficiently cached.
  18188. */
  18189. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  18190. /**
  18191. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  18192. * This strategy is typically used if the canvas has some groups that are frequently animated. Unchanged ones will have a steady cache and the others will be refreshed when they change, reducing the redraw operation count to their content only.
  18193. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  18194. * Note that in this mode the Canvas itself is not cached, it only contains the sprites of its direct children group to render, there's no point to cache the whole canvas, sprites will be rendered pretty efficiently, the memory cost would be too great for the value of it.
  18195. */
  18196. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  18197. /**
  18198. * In this strategy the whole canvas is cached into a single bitmap containing every primitives it owns, at the exception of the ones that are owned by a group having the DONTCACHEOVERRIDE behavior (these primitives will be directly drawn to the viewport at each render for screenSpace Canvas or be part of the Canvas cache bitmap for worldSpace Canvas).
  18199. */
  18200. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  18201. /**
  18202. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  18203. * Use this strategy if memory is a concern above rendering performances and/or if the canvas is frequently animated (hence reducing the benefits of caching).
  18204. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  18205. */
  18206. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  18207. /**
  18208. * Observable Mask to be notified before rendering is made
  18209. */
  18210. Canvas2D.RENDEROBSERVABLE_PRE = 1;
  18211. /**
  18212. * Observable Mask to be notified after rendering is made
  18213. */
  18214. Canvas2D.RENDEROBSERVABLE_POST = 2;
  18215. Canvas2D._INSTANCES = [];
  18216. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  18217. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  18218. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  18219. Canvas2D._m = BABYLON.Matrix.Identity();
  18220. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  18221. Canvas2D.tS = BABYLON.Vector3.Zero();
  18222. Canvas2D.tT = BABYLON.Vector3.Zero();
  18223. Canvas2D.tR = BABYLON.Quaternion.Identity();
  18224. Canvas2D._tmpMtx = BABYLON.Matrix.Identity();
  18225. Canvas2D._tmpVec3 = BABYLON.Vector3.Zero();
  18226. Canvas2D._pCLS = BABYLON.Vector3.Zero();
  18227. /**
  18228. * Define the default size used for both the width and height of a MapTexture to allocate.
  18229. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  18230. */
  18231. Canvas2D._groupTextureCacheSize = 1024;
  18232. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  18233. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  18234. __decorate([
  18235. BABYLON.logMethod("==========CANVAS RENDER===============")
  18236. ], Canvas2D.prototype, "_render", null);
  18237. Canvas2D = Canvas2D_1 = __decorate([
  18238. BABYLON.className("Canvas2D", "BABYLON")
  18239. ], Canvas2D);
  18240. BABYLON.Canvas2D = Canvas2D;
  18241. var WorldSpaceCanvas2D = (function (_super) {
  18242. __extends(WorldSpaceCanvas2D, _super);
  18243. /**
  18244. * Create a new 2D WorldSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a world transformation information to place it in the world space.
  18245. * This kind of canvas can't have its Primitives directly drawn in the Viewport, they need to be cached in a bitmap at some point, as a consequence the DONT_CACHE strategy is unavailable. For now only CACHESTRATEGY_CANVAS is supported, but the remaining strategies will be soon.
  18246. * @param scene the Scene that owns the Canvas
  18247. * @param size the dimension of the Canvas in World Space
  18248. * @param settings a combination of settings, possible ones are
  18249. * - children: an array of direct children primitives
  18250. * - id: a text identifier, for information purpose only, default is null.
  18251. * - unitScaleFactor: if specified the created canvas will be with a width of size.width*unitScaleFactor and a height of size.height.unitScaleFactor. If not specified, the unit of 1 is used. You can use this setting when you're dealing with a 3D world with small coordinates and you need a Canvas having bigger coordinates (typically to display text with better quality).
  18252. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  18253. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  18254. * - trackNode: if you want the WorldSpaceCanvas to track the position/rotation/scale of a given Scene Node, use this setting to specify the Node to track
  18255. * - trackNodeOffset: if you use trackNode you may want to specify a 3D Offset to apply to shift the Canvas
  18256. * - trackNodeBillboard: if true the WorldSpaceCanvas will always face the screen
  18257. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  18258. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  18259. * - enableInteraction: if true the pointer events will be listened and rerouted to the appropriate primitives of the Canvas2D through the Prim2DBase.onPointerEventObservable observable property. Default is false (the opposite of ScreenSpace).
  18260. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  18261. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  18262. * - backgroundFill: the brush to use to create a background fill for the canvas. can be a string value (see Canvas2D.GetBrushFromString) or a IBrush2D instance.
  18263. * - backgroundBorder: the brush to use to create a background border for the canvas. can be a string value (see Canvas2D.GetBrushFromString) or a IBrush2D instance.
  18264. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  18265. * - customWorldSpaceNode: if specified the Canvas will be rendered in this given Node. But it's the responsibility of the caller to set the "worldSpaceToNodeLocal" property to compute the hit of the mouse ray into the node (in world coordinate system) as well as rendering the cached bitmap in the node itself. The properties cachedRect and cachedTexture of Group2D will give you what you need to do that.
  18266. * - maxAdaptiveCanvasSize: set the max size (width and height) of the bitmap that will contain the cached version of the WorldSpace Canvas. Default is 1024 or less if it's not supported. In any case the value you give will be clipped by the maximum that WebGL supports on the running device. You can set any size, more than 1024 if you want, but testing proved it's a good max value for non "retina" like screens.
  18267. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  18268. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  18269. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  18270. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  18271. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  18272. */
  18273. function WorldSpaceCanvas2D(scene, size, settings) {
  18274. var _this;
  18275. BABYLON.Prim2DBase._isCanvasInit = true;
  18276. var s = settings;
  18277. s.isScreenSpace = false;
  18278. if (settings.unitScaleFactor != null) {
  18279. s.size = size.multiplyByFloats(settings.unitScaleFactor, settings.unitScaleFactor);
  18280. }
  18281. else {
  18282. s.size = size.clone();
  18283. }
  18284. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  18285. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  18286. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  18287. }
  18288. _this = _super.call(this, scene, settings) || this;
  18289. BABYLON.Prim2DBase._isCanvasInit = false;
  18290. _this._unitScaleFactor = (settings.unitScaleFactor != null) ? settings.unitScaleFactor : 1;
  18291. _this._renderableData._useMipMap = true;
  18292. _this._renderableData._anisotropicLevel = 8;
  18293. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  18294. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  18295. //}
  18296. _this._trackNode = (settings.trackNode != null) ? settings.trackNode : null;
  18297. _this._trackNodeOffset = (settings.trackNodeOffset != null) ? settings.trackNodeOffset : BABYLON.Vector3.Zero();
  18298. _this._trackNodeBillboard = (settings.trackNodeBillboard != null) ? settings.trackNodeBillboard : true;
  18299. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  18300. _this._customWorldSpaceNode = !createWorldSpaceNode;
  18301. var id = settings ? settings.id || null : null;
  18302. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  18303. var capMaxTextSize = _this.engine.getCaps().maxRenderTextureSize;
  18304. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 1K if allowed otherwise the max allowed
  18305. if (settings.maxAdaptiveCanvasSize == null) {
  18306. _this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  18307. }
  18308. else {
  18309. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  18310. _this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  18311. }
  18312. if (createWorldSpaceNode) {
  18313. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, _this);
  18314. var vertexData = BABYLON.VertexData.CreatePlane({
  18315. width: size.width,
  18316. height: size.height,
  18317. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  18318. });
  18319. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  18320. _this.applyCachedTexture(vertexData, mtl);
  18321. vertexData.applyToMesh(plane, true);
  18322. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  18323. mtl.disableLighting = true;
  18324. mtl.useAlphaFromDiffuseTexture = true;
  18325. if (settings && settings.sideOrientation) {
  18326. mtl.backFaceCulling = (settings.sideOrientation === BABYLON.Mesh.DEFAULTSIDE || settings.sideOrientation === BABYLON.Mesh.FRONTSIDE);
  18327. }
  18328. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  18329. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  18330. plane.material = mtl;
  18331. _this._worldSpaceNode = plane;
  18332. }
  18333. else {
  18334. _this._worldSpaceNode = settings.customWorldSpaceNode;
  18335. _this.applyCachedTexture(null, null);
  18336. }
  18337. _this.propertyChanged.add(function (e, st) {
  18338. if (e.propertyName !== "isVisible") {
  18339. return;
  18340. }
  18341. var mesh = _this._worldSpaceNode;
  18342. if (mesh) {
  18343. mesh.isVisible = e.newValue;
  18344. }
  18345. }, BABYLON.Prim2DBase.isVisibleProperty.flagId);
  18346. return _this;
  18347. }
  18348. WorldSpaceCanvas2D.prototype.dispose = function () {
  18349. if (!_super.prototype.dispose.call(this)) {
  18350. return false;
  18351. }
  18352. if (!this._customWorldSpaceNode && this._worldSpaceNode) {
  18353. this._worldSpaceNode.dispose();
  18354. this._worldSpaceNode = null;
  18355. }
  18356. };
  18357. Object.defineProperty(WorldSpaceCanvas2D.prototype, "trackNode", {
  18358. get: function () {
  18359. return this._trackNode;
  18360. },
  18361. set: function (value) {
  18362. if (this._trackNode === value) {
  18363. return;
  18364. }
  18365. this._trackNode = value;
  18366. },
  18367. enumerable: true,
  18368. configurable: true
  18369. });
  18370. Object.defineProperty(WorldSpaceCanvas2D.prototype, "trackNodeOffset", {
  18371. get: function () {
  18372. return this._trackNodeOffset;
  18373. },
  18374. set: function (value) {
  18375. if (!this._trackNodeOffset) {
  18376. this._trackNodeOffset = value.clone();
  18377. }
  18378. else {
  18379. this._trackNodeOffset.copyFrom(value);
  18380. }
  18381. },
  18382. enumerable: true,
  18383. configurable: true
  18384. });
  18385. Object.defineProperty(WorldSpaceCanvas2D.prototype, "trackNodeBillboard", {
  18386. get: function () {
  18387. return this._trackNodeBillboard;
  18388. },
  18389. set: function (value) {
  18390. this._trackNodeBillboard = value;
  18391. },
  18392. enumerable: true,
  18393. configurable: true
  18394. });
  18395. return WorldSpaceCanvas2D;
  18396. }(Canvas2D));
  18397. WorldSpaceCanvas2D = __decorate([
  18398. BABYLON.className("WorldSpaceCanvas2D", "BABYLON")
  18399. ], WorldSpaceCanvas2D);
  18400. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  18401. var ScreenSpaceCanvas2D = (function (_super) {
  18402. __extends(ScreenSpaceCanvas2D, _super);
  18403. /**
  18404. * Create a new 2D ScreenSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a position relative to the bottom/left corner of the screen.
  18405. * ScreenSpace Canvas will be drawn in the Viewport as a 2D Layer lying to the top of the 3D Scene. Typically used for traditional UI.
  18406. * All caching strategies will be available.
  18407. * PLEASE NOTE: the origin of a Screen Space Canvas is set to [0;0] (bottom/left) which is different than the default origin of a Primitive which is centered [0.5;0.5]
  18408. * @param scene the Scene that owns the Canvas
  18409. * @param settings a combination of settings, possible ones are
  18410. * - children: an array of direct children primitives
  18411. * - id: a text identifier, for information purpose only
  18412. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  18413. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  18414. * - position: the position of the canvas, relative from the bottom/left of the scene's viewport. Alternatively you can set the x and y properties directly. Default value is [0, 0]
  18415. * - width: the width of the Canvas. you can alternatively use the size setting.
  18416. * - height: the height of the Canvas. you can alternatively use the size setting.
  18417. * - size: the Size of the canvas. Alternatively the width and height properties can be set. If null two behaviors depend on the cachingStrategy: if it's CACHESTRATEGY_CACHECANVAS then it will always auto-fit the rendering device, in all the other modes it will fit the content of the Canvas
  18418. * - renderingPhase: you can specify for which camera and which renderGroup this canvas will render to enable interleaving of 3D/2D content through the use of renderinGroup. As a rendering Group is rendered for each camera, you have to specify in the scope of which camera you want the canvas' render to be made. Default behavior will render the Canvas at the very end of the render loop.
  18419. * - designSize: if you want to set the canvas content based on fixed coordinates whatever the final canvas dimension would be, set this. For instance a designSize of 360*640 will give you the possibility to specify all the children element in this frame. The Canvas' true size will be the HTMLCanvas' size: for instance it could be 720*1280, then a uniform scale of 2 will be applied on the Canvas to keep the absolute coordinates working as expecting. If the ratios of the designSize and the true Canvas size are not the same, then the scale is computed following the designUseHorizAxis member by using either the size of the horizontal axis or the vertical axis.
  18420. * - designUseHorizAxis: you can set this member if you use designSize to specify which axis is priority to compute the scale when the ratio of the canvas' size is different from the designSize's one.
  18421. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  18422. * - enableInteraction: if true the pointer events will be listened and rerouted to the appropriate primitives of the Canvas2D through the Prim2DBase.onPointerEventObservable observable property. Default is true.
  18423. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  18424. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  18425. * - backgroundFill: the brush to use to create a background fill for the canvas. can be a string value (see BABYLON.Canvas2D.GetBrushFromString) or a IBrush2D instance.
  18426. * - backgroundBorder: the brush to use to create a background border for the canvas. can be a string value (see BABYLON.Canvas2D.GetBrushFromString) or a IBrush2D instance.
  18427. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  18428. * - customWorldSpaceNode: if specified the Canvas will be rendered in this given Node. But it's the responsibility of the caller to set the "worldSpaceToNodeLocal" property to compute the hit of the mouse ray into the node (in world coordinate system) as well as rendering the cached bitmap in the node itself. The properties cachedRect and cachedTexture of Group2D will give you what you need to do that.
  18429. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  18430. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  18431. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  18432. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  18433. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  18434. */
  18435. function ScreenSpaceCanvas2D(scene, settings) {
  18436. var _this;
  18437. BABYLON.Prim2DBase._isCanvasInit = true;
  18438. _this = _super.call(this, scene, settings) || this;
  18439. return _this;
  18440. }
  18441. return ScreenSpaceCanvas2D;
  18442. }(Canvas2D));
  18443. ScreenSpaceCanvas2D = __decorate([
  18444. BABYLON.className("ScreenSpaceCanvas2D", "BABYLON")
  18445. ], ScreenSpaceCanvas2D);
  18446. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  18447. var Canvas2D_1;
  18448. })(BABYLON || (BABYLON = {}));
  18449. var __extends = (this && this.__extends) || function (d, b) {
  18450. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18451. function __() { this.constructor = d; }
  18452. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  18453. };
  18454. var BABYLON;
  18455. (function (BABYLON) {
  18456. /**
  18457. * This is the class that is used to display a World Space Canvas into a 3D scene
  18458. */
  18459. var WorldSpaceCanvas2DNode = (function (_super) {
  18460. __extends(WorldSpaceCanvas2DNode, _super);
  18461. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  18462. var _this = _super.call(this, name, scene) || this;
  18463. _this._canvas = canvas;
  18464. return _this;
  18465. }
  18466. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  18467. _super.prototype.dispose.call(this);
  18468. if (this._canvas) {
  18469. this._canvas.dispose();
  18470. this._canvas = null;
  18471. }
  18472. };
  18473. return WorldSpaceCanvas2DNode;
  18474. }(BABYLON.Mesh));
  18475. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  18476. })(BABYLON || (BABYLON = {}));
  18477. var __extends = (this && this.__extends) || function (d, b) {
  18478. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18479. function __() { this.constructor = d; }
  18480. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  18481. };
  18482. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  18483. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  18484. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  18485. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  18486. return c > 3 && r && Object.defineProperty(target, key, r), r;
  18487. };
  18488. var BABYLON;
  18489. (function (BABYLON) {
  18490. var Command = (function () {
  18491. function Command(execute, canExecute) {
  18492. if (!execute) {
  18493. throw Error("At least an execute lambda must be given at Command creation time");
  18494. }
  18495. this._canExecuteChanged = null;
  18496. this._lastCanExecuteResult = null;
  18497. this.execute = execute;
  18498. this.canExecute = canExecute;
  18499. }
  18500. Command.prototype.canExecute = function (parameter) {
  18501. var res = true;
  18502. if (this._canExecute) {
  18503. res = this._canExecute(parameter);
  18504. }
  18505. if (res !== this._lastCanExecuteResult) {
  18506. if (this._canExecuteChanged && this._canExecuteChanged.hasObservers()) {
  18507. this._canExecuteChanged.notifyObservers(null);
  18508. }
  18509. this._lastCanExecuteResult = res;
  18510. }
  18511. return res;
  18512. };
  18513. Command.prototype.execute = function (parameter) {
  18514. this._execute(parameter);
  18515. };
  18516. Object.defineProperty(Command.prototype, "canExecuteChanged", {
  18517. get: function () {
  18518. if (!this._canExecuteChanged) {
  18519. this._canExecuteChanged = new BABYLON.Observable();
  18520. }
  18521. return this._canExecuteChanged;
  18522. },
  18523. enumerable: true,
  18524. configurable: true
  18525. });
  18526. return Command;
  18527. }());
  18528. BABYLON.Command = Command;
  18529. var UIElement = (function (_super) {
  18530. __extends(UIElement, _super);
  18531. function UIElement(settings) {
  18532. var _this = _super.call(this) || this;
  18533. if (!settings) {
  18534. throw Error("A settings object must be passed with at least either a parent or owner parameter");
  18535. }
  18536. var type = BABYLON.Tools.getFullClassName(_this);
  18537. _this._ownerWindow = null;
  18538. _this._parent = null;
  18539. _this._visualPlaceholder = null;
  18540. _this._visualTemplateRoot = null;
  18541. _this._visualChildrenPlaceholder = null;
  18542. _this._hierarchyDepth = 0;
  18543. _this._renderingTemplateName = (settings.templateName != null) ? settings.templateName : GUIManager.DefaultTemplateName;
  18544. _this._style = (settings.styleName != null) ? GUIManager.getStyle(type, settings.styleName) : null;
  18545. _this._flags = 0;
  18546. _this._id = (settings.id != null) ? settings.id : null;
  18547. _this._uid = null;
  18548. _this._width = (settings.width != null) ? settings.width : null;
  18549. _this._height = (settings.height != null) ? settings.height : null;
  18550. _this._minWidth = (settings.minWidth != null) ? settings.minWidth : 0;
  18551. _this._minHeight = (settings.minHeight != null) ? settings.minHeight : 0;
  18552. _this._maxWidth = (settings.maxWidth != null) ? settings.maxWidth : Number.MAX_VALUE;
  18553. _this._maxHeight = (settings.maxHeight != null) ? settings.maxHeight : Number.MAX_VALUE;
  18554. _this._margin = null;
  18555. _this._padding = null;
  18556. _this._marginAlignment = null;
  18557. _this._setFlags(UIElement.flagIsVisible | UIElement.flagIsEnabled);
  18558. // Default Margin Alignment for UIElement is stretch for horizontal/vertical and not left/bottom (which is the default for Canvas2D Primitives)
  18559. //this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  18560. //this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  18561. // Set the layout/margin stuffs
  18562. if (settings.marginTop) {
  18563. _this.margin.setTop(settings.marginTop);
  18564. }
  18565. if (settings.marginLeft) {
  18566. _this.margin.setLeft(settings.marginLeft);
  18567. }
  18568. if (settings.marginRight) {
  18569. _this.margin.setRight(settings.marginRight);
  18570. }
  18571. if (settings.marginBottom) {
  18572. _this.margin.setBottom(settings.marginBottom);
  18573. }
  18574. if (settings.margin) {
  18575. if (typeof settings.margin === "string") {
  18576. _this.margin.fromString(settings.margin);
  18577. }
  18578. else {
  18579. _this.margin.fromUniformPixels(settings.margin);
  18580. }
  18581. }
  18582. if (settings.marginHAlignment) {
  18583. _this.marginAlignment.horizontal = settings.marginHAlignment;
  18584. }
  18585. if (settings.marginVAlignment) {
  18586. _this.marginAlignment.vertical = settings.marginVAlignment;
  18587. }
  18588. if (settings.marginAlignment) {
  18589. _this.marginAlignment.fromString(settings.marginAlignment);
  18590. }
  18591. if (settings.paddingTop) {
  18592. _this.padding.setTop(settings.paddingTop);
  18593. }
  18594. if (settings.paddingLeft) {
  18595. _this.padding.setLeft(settings.paddingLeft);
  18596. }
  18597. if (settings.paddingRight) {
  18598. _this.padding.setRight(settings.paddingRight);
  18599. }
  18600. if (settings.paddingBottom) {
  18601. _this.padding.setBottom(settings.paddingBottom);
  18602. }
  18603. if (settings.padding) {
  18604. _this.padding.fromString(settings.padding);
  18605. }
  18606. if (settings.paddingHAlignment) {
  18607. _this.paddingAlignment.horizontal = settings.paddingHAlignment;
  18608. }
  18609. if (settings.paddingVAlignment) {
  18610. _this.paddingAlignment.vertical = settings.paddingVAlignment;
  18611. }
  18612. if (settings.paddingAlignment) {
  18613. _this.paddingAlignment.fromString(settings.paddingAlignment);
  18614. }
  18615. if (settings.parent != null) {
  18616. _this._parent = settings.parent;
  18617. _this._hierarchyDepth = _this._parent._hierarchyDepth + 1;
  18618. }
  18619. return _this;
  18620. }
  18621. Object.defineProperty(UIElement, "enabledState", {
  18622. get: function () {
  18623. return UIElement._enableState;
  18624. },
  18625. enumerable: true,
  18626. configurable: true
  18627. });
  18628. Object.defineProperty(UIElement, "disabledState", {
  18629. get: function () {
  18630. return UIElement._disabledState;
  18631. },
  18632. enumerable: true,
  18633. configurable: true
  18634. });
  18635. Object.defineProperty(UIElement, "mouseOverState", {
  18636. get: function () {
  18637. return UIElement._mouseOverState;
  18638. },
  18639. enumerable: true,
  18640. configurable: true
  18641. });
  18642. UIElement.prototype.dispose = function () {
  18643. if (this.isDisposed) {
  18644. return false;
  18645. }
  18646. if (this._renderingTemplate) {
  18647. this._renderingTemplate.detach();
  18648. this._renderingTemplate = null;
  18649. }
  18650. _super.prototype.dispose.call(this);
  18651. // Don't set to null, it may upset somebody...
  18652. this.animations.splice(0);
  18653. return true;
  18654. };
  18655. /**
  18656. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  18657. * Look at Sprite2D for more information
  18658. */
  18659. UIElement.prototype.getAnimatables = function () {
  18660. return new Array();
  18661. };
  18662. // TODO
  18663. // PROPERTIES
  18664. // Style
  18665. // Id
  18666. // Parent/Children
  18667. // ActualWidth/Height, MinWidth/Height, MaxWidth/Height,
  18668. // Alignment/Margin
  18669. // Visibility, IsVisible
  18670. // IsEnabled (is false, control is disabled, no interaction and a specific render state)
  18671. // CacheMode of Visual Elements
  18672. // Focusable/IsFocused
  18673. // IsPointerCaptured, CapturePointer, IsPointerDirectlyOver, IsPointerOver. De-correlate mouse, stylus, touch?
  18674. // ContextMenu
  18675. // Cursor
  18676. // DesiredSize
  18677. // IsInputEnable ?
  18678. // Opacity, OpacityMask ?
  18679. // SnapToDevicePixels
  18680. // Tag
  18681. // ToolTip
  18682. // METHODS
  18683. // BringIntoView (for scrollable content, to move the scroll to bring the given element visible in the parent's area)
  18684. // Capture/ReleaseCapture (mouse, touch, stylus)
  18685. // Focus
  18686. // PointFrom/ToScreen to translate coordinates
  18687. // EVENTS
  18688. // ContextMenuOpening/Closing/Changed
  18689. // DragEnter/LeaveOver, Drop
  18690. // Got/LostFocus
  18691. // IsEnabledChanged
  18692. // IsPointerOver/DirectlyOverChanged
  18693. // IsVisibleChanged
  18694. // KeyDown/Up
  18695. // LayoutUpdated ?
  18696. // Pointer related events
  18697. // SizeChanged
  18698. // ToolTipOpening/Closing
  18699. UIElement.prototype.findById = function (id) {
  18700. if (this._id === id) {
  18701. return this;
  18702. }
  18703. var children = this._getChildren();
  18704. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  18705. var child = children_1[_i];
  18706. var r = child.findById(id);
  18707. if (r != null) {
  18708. return r;
  18709. }
  18710. }
  18711. };
  18712. Object.defineProperty(UIElement.prototype, "ownerWindow", {
  18713. get: function () {
  18714. return this._ownerWindow;
  18715. },
  18716. enumerable: true,
  18717. configurable: true
  18718. });
  18719. Object.defineProperty(UIElement.prototype, "style", {
  18720. get: function () {
  18721. if (!this.style) {
  18722. return GUIManager.DefaultStyleName;
  18723. }
  18724. return this._style.name;
  18725. },
  18726. set: function (value) {
  18727. if (this._style && (this._style.name === value)) {
  18728. return;
  18729. }
  18730. var newStyle = null;
  18731. if (value) {
  18732. newStyle = GUIManager.getStyle(BABYLON.Tools.getFullClassName(this), value);
  18733. if (!newStyle) {
  18734. throw Error("Couldn't find Style " + value + " for UIElement " + BABYLON.Tools.getFullClassName(this));
  18735. }
  18736. }
  18737. if (this._style) {
  18738. this._style.removeStyle(this);
  18739. }
  18740. if (newStyle) {
  18741. newStyle.applyStyle(this);
  18742. }
  18743. this._style = newStyle;
  18744. },
  18745. enumerable: true,
  18746. configurable: true
  18747. });
  18748. Object.defineProperty(UIElement.prototype, "id", {
  18749. /**
  18750. * A string that identifies the UIElement.
  18751. * The id is optional and there's possible collision with other UIElement's id as the uniqueness is not supported.
  18752. */
  18753. get: function () {
  18754. return this._id;
  18755. },
  18756. set: function (value) {
  18757. if (this._id === value) {
  18758. return;
  18759. }
  18760. this._id = value;
  18761. },
  18762. enumerable: true,
  18763. configurable: true
  18764. });
  18765. Object.defineProperty(UIElement.prototype, "uid", {
  18766. /**
  18767. * Return a unique id automatically generated.
  18768. * This property is mainly used for serialization to ensure a perfect way of identifying a UIElement
  18769. */
  18770. get: function () {
  18771. if (!this._uid) {
  18772. this._uid = BABYLON.Tools.RandomId();
  18773. }
  18774. return this._uid;
  18775. },
  18776. enumerable: true,
  18777. configurable: true
  18778. });
  18779. Object.defineProperty(UIElement.prototype, "hierarchyDepth", {
  18780. get: function () {
  18781. return this._hierarchyDepth;
  18782. },
  18783. enumerable: true,
  18784. configurable: true
  18785. });
  18786. Object.defineProperty(UIElement.prototype, "parent", {
  18787. get: function () {
  18788. return this._parent;
  18789. },
  18790. set: function (value) {
  18791. this._parent = value;
  18792. },
  18793. enumerable: true,
  18794. configurable: true
  18795. });
  18796. Object.defineProperty(UIElement.prototype, "width", {
  18797. get: function () {
  18798. return this._width;
  18799. },
  18800. set: function (value) {
  18801. this._width = value;
  18802. },
  18803. enumerable: true,
  18804. configurable: true
  18805. });
  18806. Object.defineProperty(UIElement.prototype, "height", {
  18807. get: function () {
  18808. return this._height;
  18809. },
  18810. set: function (value) {
  18811. this._height = value;
  18812. },
  18813. enumerable: true,
  18814. configurable: true
  18815. });
  18816. Object.defineProperty(UIElement.prototype, "minWidth", {
  18817. get: function () {
  18818. return this._minWidth;
  18819. },
  18820. set: function (value) {
  18821. this._minWidth = value;
  18822. },
  18823. enumerable: true,
  18824. configurable: true
  18825. });
  18826. Object.defineProperty(UIElement.prototype, "minHheight", {
  18827. get: function () {
  18828. return this._minHeight;
  18829. },
  18830. enumerable: true,
  18831. configurable: true
  18832. });
  18833. Object.defineProperty(UIElement.prototype, "minHeight", {
  18834. set: function (value) {
  18835. this._minHeight = value;
  18836. },
  18837. enumerable: true,
  18838. configurable: true
  18839. });
  18840. Object.defineProperty(UIElement.prototype, "maxWidth", {
  18841. get: function () {
  18842. return this._maxWidth;
  18843. },
  18844. set: function (value) {
  18845. this._maxWidth = value;
  18846. },
  18847. enumerable: true,
  18848. configurable: true
  18849. });
  18850. Object.defineProperty(UIElement.prototype, "maxHeight", {
  18851. get: function () {
  18852. return this._maxHeight;
  18853. },
  18854. set: function (value) {
  18855. this._maxHeight = value;
  18856. },
  18857. enumerable: true,
  18858. configurable: true
  18859. });
  18860. Object.defineProperty(UIElement.prototype, "actualWidth", {
  18861. get: function () {
  18862. return this._actualWidth;
  18863. },
  18864. set: function (value) {
  18865. this._actualWidth = value;
  18866. },
  18867. enumerable: true,
  18868. configurable: true
  18869. });
  18870. Object.defineProperty(UIElement.prototype, "actualHeight", {
  18871. get: function () {
  18872. return this._actualHeight;
  18873. },
  18874. set: function (value) {
  18875. this._actualHeight = value;
  18876. },
  18877. enumerable: true,
  18878. configurable: true
  18879. });
  18880. Object.defineProperty(UIElement.prototype, "margin", {
  18881. get: function () {
  18882. var _this = this;
  18883. if (!this._margin) {
  18884. this._margin = new BABYLON.PrimitiveThickness(function () {
  18885. if (!_this.parent) {
  18886. return null;
  18887. }
  18888. return _this.parent.margin;
  18889. });
  18890. }
  18891. return this._margin;
  18892. },
  18893. set: function (value) {
  18894. this.margin.copyFrom(value);
  18895. },
  18896. enumerable: true,
  18897. configurable: true
  18898. });
  18899. Object.defineProperty(UIElement.prototype, "_hasMargin", {
  18900. get: function () {
  18901. return (this._margin !== null && !this._margin.isDefault) || (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  18902. },
  18903. enumerable: true,
  18904. configurable: true
  18905. });
  18906. Object.defineProperty(UIElement.prototype, "padding", {
  18907. get: function () {
  18908. var _this = this;
  18909. if (!this._padding) {
  18910. this._padding = new BABYLON.PrimitiveThickness(function () {
  18911. if (!_this.parent) {
  18912. return null;
  18913. }
  18914. return _this.parent.padding;
  18915. });
  18916. }
  18917. return this._padding;
  18918. },
  18919. set: function (value) {
  18920. this.padding.copyFrom(value);
  18921. },
  18922. enumerable: true,
  18923. configurable: true
  18924. });
  18925. Object.defineProperty(UIElement.prototype, "_hasPadding", {
  18926. get: function () {
  18927. return this._padding !== null && !this._padding.isDefault;
  18928. },
  18929. enumerable: true,
  18930. configurable: true
  18931. });
  18932. Object.defineProperty(UIElement.prototype, "marginAlignment", {
  18933. get: function () {
  18934. if (!this._marginAlignment) {
  18935. this._marginAlignment = new BABYLON.PrimitiveAlignment();
  18936. }
  18937. return this._marginAlignment;
  18938. },
  18939. set: function (value) {
  18940. this.marginAlignment.copyFrom(value);
  18941. },
  18942. enumerable: true,
  18943. configurable: true
  18944. });
  18945. Object.defineProperty(UIElement.prototype, "_hasMarginAlignment", {
  18946. /**
  18947. * Check if there a marginAlignment specified (non null and not default)
  18948. */
  18949. get: function () {
  18950. return (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  18951. },
  18952. enumerable: true,
  18953. configurable: true
  18954. });
  18955. Object.defineProperty(UIElement.prototype, "paddingAlignment", {
  18956. get: function () {
  18957. if (!this._paddingAlignment) {
  18958. this._paddingAlignment = new BABYLON.PrimitiveAlignment();
  18959. }
  18960. return this._paddingAlignment;
  18961. },
  18962. set: function (value) {
  18963. this.paddingAlignment.copyFrom(value);
  18964. },
  18965. enumerable: true,
  18966. configurable: true
  18967. });
  18968. Object.defineProperty(UIElement.prototype, "_hasPaddingAlignment", {
  18969. /**
  18970. * Check if there a marginAlignment specified (non null and not default)
  18971. */
  18972. get: function () {
  18973. return (this._paddingAlignment !== null && !this._paddingAlignment.isDefault);
  18974. },
  18975. enumerable: true,
  18976. configurable: true
  18977. });
  18978. Object.defineProperty(UIElement.prototype, "isVisible", {
  18979. get: function () {
  18980. return this._isFlagSet(UIElement.flagIsVisible);
  18981. },
  18982. set: function (value) {
  18983. if (this.isVisible === value) {
  18984. return;
  18985. }
  18986. this._visualPlaceholder.levelVisible = value;
  18987. this._changeFlags(UIElement.flagIsVisible, value);
  18988. },
  18989. enumerable: true,
  18990. configurable: true
  18991. });
  18992. Object.defineProperty(UIElement.prototype, "isEnabled", {
  18993. get: function () {
  18994. return this._isFlagSet(UIElement.flagIsEnabled);
  18995. },
  18996. set: function (value) {
  18997. this._changeFlags(UIElement.flagIsEnabled, value);
  18998. },
  18999. enumerable: true,
  19000. configurable: true
  19001. });
  19002. Object.defineProperty(UIElement.prototype, "isFocused", {
  19003. get: function () {
  19004. return this._isFlagSet(UIElement.flagIsFocus);
  19005. },
  19006. set: function (value) {
  19007. // If the UIElement doesn't accept focus, set it on its parent
  19008. if (!this.isFocusable) {
  19009. var p = this.parent;
  19010. if (!p) {
  19011. return;
  19012. }
  19013. p.isFocused = value;
  19014. }
  19015. // If the focus is being set, notify the Focus Manager
  19016. if (value) {
  19017. this.ownerWindow.focusManager.setFocusOn(this, this.getFocusScope());
  19018. }
  19019. this._changeFlags(UIElement.flagIsFocus, value);
  19020. },
  19021. enumerable: true,
  19022. configurable: true
  19023. });
  19024. Object.defineProperty(UIElement.prototype, "isMouseOver", {
  19025. get: function () {
  19026. return this._isFlagSet(UIElement.flagIsMouseOver);
  19027. },
  19028. set: function (value) {
  19029. this._changeFlags(UIElement.flagIsMouseOver, value);
  19030. },
  19031. enumerable: true,
  19032. configurable: true
  19033. });
  19034. Object.defineProperty(UIElement.prototype, "isFocusScope", {
  19035. get: function () {
  19036. return this._isFlagSet(UIElement.flagIsFocusScope);
  19037. },
  19038. set: function (value) {
  19039. this._changeFlags(UIElement.flagIsFocusScope, value);
  19040. },
  19041. enumerable: true,
  19042. configurable: true
  19043. });
  19044. Object.defineProperty(UIElement.prototype, "isFocusable", {
  19045. get: function () {
  19046. return this._isFlagSet(UIElement.flagIsFocusable);
  19047. },
  19048. set: function (value) {
  19049. this._changeFlags(UIElement.flagIsFocusable, value);
  19050. },
  19051. enumerable: true,
  19052. configurable: true
  19053. });
  19054. // Look for the nearest parent which is the focus scope. Should always return something as the Window UIElement which is the root of all UI Tree is focus scope (unless the user disable it)
  19055. UIElement.prototype.getFocusScope = function () {
  19056. if (this.isFocusScope) {
  19057. return this;
  19058. }
  19059. var p = this.parent;
  19060. if (!p) {
  19061. return null;
  19062. }
  19063. return p.getFocusScope();
  19064. };
  19065. /**
  19066. * Check if a given flag is set
  19067. * @param flag the flag value
  19068. * @return true if set, false otherwise
  19069. */
  19070. UIElement.prototype._isFlagSet = function (flag) {
  19071. return (this._flags & flag) !== 0;
  19072. };
  19073. /**
  19074. * Check if all given flags are set
  19075. * @param flags the flags ORed
  19076. * @return true if all the flags are set, false otherwise
  19077. */
  19078. UIElement.prototype._areAllFlagsSet = function (flags) {
  19079. return (this._flags & flags) === flags;
  19080. };
  19081. /**
  19082. * Check if at least one flag of the given flags is set
  19083. * @param flags the flags ORed
  19084. * @return true if at least one flag is set, false otherwise
  19085. */
  19086. UIElement.prototype._areSomeFlagsSet = function (flags) {
  19087. return (this._flags & flags) !== 0;
  19088. };
  19089. /**
  19090. * Clear the given flags
  19091. * @param flags the flags to clear
  19092. */
  19093. UIElement.prototype._clearFlags = function (flags) {
  19094. this._flags &= ~flags;
  19095. };
  19096. /**
  19097. * Set the given flags to true state
  19098. * @param flags the flags ORed to set
  19099. * @return the flags state before this call
  19100. */
  19101. UIElement.prototype._setFlags = function (flags) {
  19102. var cur = this._flags;
  19103. this._flags |= flags;
  19104. return cur;
  19105. };
  19106. /**
  19107. * Change the state of the given flags
  19108. * @param flags the flags ORed to change
  19109. * @param state true to set them, false to clear them
  19110. */
  19111. UIElement.prototype._changeFlags = function (flags, state) {
  19112. if (state) {
  19113. this._flags |= flags;
  19114. }
  19115. else {
  19116. this._flags &= ~flags;
  19117. }
  19118. };
  19119. UIElement.prototype._assignTemplate = function (templateName) {
  19120. if (!templateName) {
  19121. templateName = GUIManager.DefaultTemplateName;
  19122. }
  19123. var className = BABYLON.Tools.getFullClassName(this);
  19124. if (!className) {
  19125. throw Error("Couldn't access class name of this UIElement, you have to decorate the type with the className decorator");
  19126. }
  19127. var factory = GUIManager.getRenderingTemplate(className, templateName);
  19128. if (!factory) {
  19129. throw Error("Couldn't get the renderingTemplate " + templateName + " of class " + className);
  19130. }
  19131. this._renderingTemplateName = templateName;
  19132. this._renderingTemplate = factory();
  19133. this._renderingTemplate.attach(this);
  19134. };
  19135. UIElement.prototype._createVisualTree = function () {
  19136. var parentPrim = this.ownerWindow.canvas;
  19137. if (this.parent) {
  19138. parentPrim = this.parent.visualChildrenPlaceholder;
  19139. }
  19140. if (!this._renderingTemplate) {
  19141. this._assignTemplate(this._renderingTemplateName);
  19142. }
  19143. this._visualPlaceholder = new BABYLON.Group2D({ parent: parentPrim, id: "GUI " + BABYLON.Tools.getClassName(this) + " RootGroup of " + this.id });
  19144. var p = this._visualPlaceholder;
  19145. p.addExternalData("_GUIOwnerElement_", this);
  19146. p.dataSource = this;
  19147. p.createSimpleDataBinding(BABYLON.Prim2DBase.widthProperty, "width", BABYLON.DataBinding.MODE_ONEWAY);
  19148. p.createSimpleDataBinding(BABYLON.Prim2DBase.heightProperty, "height", BABYLON.DataBinding.MODE_ONEWAY);
  19149. p.createSimpleDataBinding(BABYLON.Prim2DBase.actualWidthProperty, "actualWidth", BABYLON.DataBinding.MODE_ONEWAYTOSOURCE);
  19150. p.createSimpleDataBinding(BABYLON.Prim2DBase.actualHeightProperty, "actualHeight", BABYLON.DataBinding.MODE_ONEWAYTOSOURCE);
  19151. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "margin", BABYLON.DataBinding.MODE_ONEWAY);
  19152. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "marginAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  19153. this.createVisualTree();
  19154. };
  19155. UIElement.prototype._patchUIElement = function (ownerWindow, parent) {
  19156. if (ownerWindow) {
  19157. if (!this._ownerWindow) {
  19158. ownerWindow._registerVisualToBuild(this);
  19159. }
  19160. this._ownerWindow = ownerWindow;
  19161. }
  19162. this._parent = parent;
  19163. if (parent) {
  19164. this._hierarchyDepth = parent.hierarchyDepth + 1;
  19165. }
  19166. var children = this._getChildren();
  19167. if (children) {
  19168. for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
  19169. var curChild = children_2[_i];
  19170. curChild._patchUIElement(ownerWindow, this);
  19171. }
  19172. }
  19173. };
  19174. // Overload the SmartPropertyBase's method to provide the additional logic of returning the parent's dataSource if there's no dataSource specified at this level.
  19175. UIElement.prototype._getDataSource = function () {
  19176. var levelDS = _super.prototype._getDataSource.call(this);
  19177. if (levelDS != null) {
  19178. return levelDS;
  19179. }
  19180. var p = this.parent;
  19181. if (p != null) {
  19182. return p.dataSource;
  19183. }
  19184. return null;
  19185. };
  19186. UIElement.prototype.createVisualTree = function () {
  19187. var res = this._renderingTemplate.createVisualTree(this, this._visualPlaceholder);
  19188. this._visualTemplateRoot = res.root;
  19189. this._visualChildrenPlaceholder = res.contentPlaceholder;
  19190. };
  19191. Object.defineProperty(UIElement.prototype, "visualPlaceholder", {
  19192. get: function () {
  19193. return this._visualPlaceholder;
  19194. },
  19195. enumerable: true,
  19196. configurable: true
  19197. });
  19198. Object.defineProperty(UIElement.prototype, "visualTemplateRoot", {
  19199. get: function () {
  19200. return this._visualTemplateRoot;
  19201. },
  19202. enumerable: true,
  19203. configurable: true
  19204. });
  19205. Object.defineProperty(UIElement.prototype, "visualChildrenPlaceholder", {
  19206. get: function () {
  19207. return this._visualChildrenPlaceholder;
  19208. },
  19209. enumerable: true,
  19210. configurable: true
  19211. });
  19212. Object.defineProperty(UIElement.prototype, "_position", {
  19213. get: function () { return null; } // TODO use abstract keyword when TS 2.0 will be approved
  19214. ,
  19215. enumerable: true,
  19216. configurable: true
  19217. });
  19218. return UIElement;
  19219. }(BABYLON.SmartPropertyBase));
  19220. UIElement.UIELEMENT_PROPCOUNT = 16;
  19221. UIElement.flagVisualToBuild = 0x0000001;
  19222. UIElement.flagIsVisible = 0x0000002;
  19223. UIElement.flagIsFocus = 0x0000004;
  19224. UIElement.flagIsFocusScope = 0x0000008;
  19225. UIElement.flagIsFocusable = 0x0000010;
  19226. UIElement.flagIsEnabled = 0x0000020;
  19227. UIElement.flagIsMouseOver = 0x0000040;
  19228. UIElement._enableState = "Enabled";
  19229. UIElement._disabledState = "Disabled";
  19230. UIElement._mouseOverState = "MouseOver";
  19231. __decorate([
  19232. BABYLON.dependencyProperty(0, function (pi) { return UIElement.parentProperty = pi; })
  19233. ], UIElement.prototype, "parent", null);
  19234. __decorate([
  19235. BABYLON.dependencyProperty(1, function (pi) { return UIElement.widthProperty = pi; })
  19236. ], UIElement.prototype, "width", null);
  19237. __decorate([
  19238. BABYLON.dependencyProperty(2, function (pi) { return UIElement.heightProperty = pi; })
  19239. ], UIElement.prototype, "height", null);
  19240. __decorate([
  19241. BABYLON.dependencyProperty(3, function (pi) { return UIElement.minWidthProperty = pi; })
  19242. ], UIElement.prototype, "minWidth", null);
  19243. __decorate([
  19244. BABYLON.dependencyProperty(4, function (pi) { return UIElement.minHeightProperty = pi; })
  19245. ], UIElement.prototype, "minHheight", null);
  19246. __decorate([
  19247. BABYLON.dependencyProperty(5, function (pi) { return UIElement.maxWidthProperty = pi; })
  19248. ], UIElement.prototype, "maxWidth", null);
  19249. __decorate([
  19250. BABYLON.dependencyProperty(6, function (pi) { return UIElement.maxHeightProperty = pi; })
  19251. ], UIElement.prototype, "maxHeight", null);
  19252. __decorate([
  19253. BABYLON.dependencyProperty(7, function (pi) { return UIElement.actualWidthProperty = pi; })
  19254. ], UIElement.prototype, "actualWidth", null);
  19255. __decorate([
  19256. BABYLON.dependencyProperty(8, function (pi) { return UIElement.actualHeightProperty = pi; })
  19257. ], UIElement.prototype, "actualHeight", null);
  19258. __decorate([
  19259. BABYLON.dynamicLevelProperty(9, function (pi) { return UIElement.marginProperty = pi; })
  19260. ], UIElement.prototype, "margin", null);
  19261. __decorate([
  19262. BABYLON.dynamicLevelProperty(10, function (pi) { return UIElement.paddingProperty = pi; })
  19263. ], UIElement.prototype, "padding", null);
  19264. __decorate([
  19265. BABYLON.dynamicLevelProperty(11, function (pi) { return UIElement.marginAlignmentProperty = pi; })
  19266. ], UIElement.prototype, "marginAlignment", null);
  19267. __decorate([
  19268. BABYLON.dynamicLevelProperty(12, function (pi) { return UIElement.paddingAlignmentProperty = pi; })
  19269. ], UIElement.prototype, "paddingAlignment", null);
  19270. __decorate([
  19271. BABYLON.dynamicLevelProperty(13, function (pi) { return UIElement.isEnabledProperty = pi; })
  19272. ], UIElement.prototype, "isEnabled", null);
  19273. __decorate([
  19274. BABYLON.dynamicLevelProperty(14, function (pi) { return UIElement.isFocusedProperty = pi; })
  19275. ], UIElement.prototype, "isFocused", null);
  19276. __decorate([
  19277. BABYLON.dynamicLevelProperty(15, function (pi) { return UIElement.isMouseOverProperty = pi; })
  19278. ], UIElement.prototype, "isMouseOver", null);
  19279. BABYLON.UIElement = UIElement;
  19280. var UIElementStyle = (function () {
  19281. function UIElementStyle() {
  19282. }
  19283. Object.defineProperty(UIElementStyle.prototype, "name", {
  19284. get: function () { return null; } // TODO use abstract keyword when TS 2.0 will be approved
  19285. ,
  19286. enumerable: true,
  19287. configurable: true
  19288. });
  19289. return UIElementStyle;
  19290. }());
  19291. BABYLON.UIElementStyle = UIElementStyle;
  19292. var GUIManager = (function () {
  19293. function GUIManager() {
  19294. }
  19295. /////////////////////////////////////////////////////////////////////////////////////////////////////
  19296. // DATA TEMPLATE MANAGER
  19297. GUIManager.registerDataTemplate = function (className, factory) {
  19298. };
  19299. // DATA TEMPLATE MANAGER
  19300. /////////////////////////////////////////////////////////////////////////////////////////////////////
  19301. /////////////////////////////////////////////////////////////////////////////////////////////////////
  19302. // STYLE MANAGER
  19303. GUIManager.getStyle = function (uiElType, styleName) {
  19304. var styles = GUIManager.stylesByUIElement.get(uiElType);
  19305. if (!styles) {
  19306. throw Error("The type " + uiElType + " is unknown, no style were registered for it.");
  19307. }
  19308. var style = styles.get(styleName);
  19309. if (!style) {
  19310. throw Error("Couldn't find Template " + styleName + " of UIElement type " + uiElType);
  19311. }
  19312. return style;
  19313. };
  19314. GUIManager.registerStyle = function (uiElType, templateName, style) {
  19315. var templates = GUIManager.stylesByUIElement.getOrAddWithFactory(uiElType, function () { return new BABYLON.StringDictionary(); });
  19316. if (templates.contains(templateName)) {
  19317. templates[templateName] = style;
  19318. }
  19319. else {
  19320. templates.add(templateName, style);
  19321. }
  19322. };
  19323. Object.defineProperty(GUIManager, "DefaultStyleName", {
  19324. get: function () {
  19325. return GUIManager._defaultStyleName;
  19326. },
  19327. set: function (value) {
  19328. GUIManager._defaultStyleName = value;
  19329. },
  19330. enumerable: true,
  19331. configurable: true
  19332. });
  19333. // STYLE MANAGER
  19334. /////////////////////////////////////////////////////////////////////////////////////////////////////
  19335. /////////////////////////////////////////////////////////////////////////////////////////////////////
  19336. // RENDERING TEMPLATE MANAGER
  19337. GUIManager.getRenderingTemplate = function (uiElType, templateName) {
  19338. var templates = GUIManager.renderingTemplatesByUIElement.get(uiElType);
  19339. if (!templates) {
  19340. throw Error("The type " + uiElType + " is unknown, no Rendering Template were registered for it.");
  19341. }
  19342. var templateFactory = templates.get(templateName);
  19343. if (!templateFactory) {
  19344. throw Error("Couldn't find Template " + templateName + " of UI Element type " + uiElType);
  19345. }
  19346. return templateFactory;
  19347. };
  19348. GUIManager.registerRenderingTemplate = function (uiElType, templateName, factory) {
  19349. var templates = GUIManager.renderingTemplatesByUIElement.getOrAddWithFactory(uiElType, function () { return new BABYLON.StringDictionary(); });
  19350. if (templates.contains(templateName)) {
  19351. templates[templateName] = factory;
  19352. }
  19353. else {
  19354. templates.add(templateName, factory);
  19355. }
  19356. };
  19357. Object.defineProperty(GUIManager, "DefaultTemplateName", {
  19358. get: function () {
  19359. return GUIManager._defaultTemplateName;
  19360. },
  19361. set: function (value) {
  19362. GUIManager._defaultTemplateName = value;
  19363. },
  19364. enumerable: true,
  19365. configurable: true
  19366. });
  19367. return GUIManager;
  19368. }());
  19369. GUIManager.stylesByUIElement = new BABYLON.StringDictionary();
  19370. GUIManager.renderingTemplatesByUIElement = new BABYLON.StringDictionary();
  19371. // RENDERING TEMPLATE MANAGER
  19372. /////////////////////////////////////////////////////////////////////////////////////////////////////
  19373. GUIManager._defaultTemplateName = "Default";
  19374. GUIManager._defaultStyleName = "Default";
  19375. BABYLON.GUIManager = GUIManager;
  19376. var UIElementRenderingTemplateBase = (function () {
  19377. function UIElementRenderingTemplateBase() {
  19378. }
  19379. UIElementRenderingTemplateBase.prototype.attach = function (owner) {
  19380. this._owner = owner;
  19381. };
  19382. UIElementRenderingTemplateBase.prototype.detach = function () {
  19383. };
  19384. Object.defineProperty(UIElementRenderingTemplateBase.prototype, "owner", {
  19385. get: function () {
  19386. return this._owner;
  19387. },
  19388. enumerable: true,
  19389. configurable: true
  19390. });
  19391. return UIElementRenderingTemplateBase;
  19392. }());
  19393. BABYLON.UIElementRenderingTemplateBase = UIElementRenderingTemplateBase;
  19394. function registerWindowRenderingTemplate(uiElType, templateName, factory) {
  19395. return function () {
  19396. GUIManager.registerRenderingTemplate(uiElType, templateName, factory);
  19397. };
  19398. }
  19399. BABYLON.registerWindowRenderingTemplate = registerWindowRenderingTemplate;
  19400. })(BABYLON || (BABYLON = {}));
  19401. var __extends = (this && this.__extends) || function (d, b) {
  19402. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19403. function __() { this.constructor = d; }
  19404. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  19405. };
  19406. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19407. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19408. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19409. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19410. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19411. };
  19412. var BABYLON;
  19413. (function (BABYLON) {
  19414. var StackPanel = StackPanel_1 = (function (_super) {
  19415. __extends(StackPanel, _super);
  19416. function StackPanel(settings) {
  19417. var _this;
  19418. if (!settings) {
  19419. settings = {};
  19420. }
  19421. _this = _super.call(this, settings) || this;
  19422. _this.isOrientationHorizontal = (settings.isOrientationHorizontal == null) ? true : settings.isOrientationHorizontal;
  19423. _this._children = new Array();
  19424. if (settings.children != null) {
  19425. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  19426. var child = _a[_i];
  19427. _this._children.push(child);
  19428. }
  19429. }
  19430. return _this;
  19431. }
  19432. Object.defineProperty(StackPanel.prototype, "isOrientationHorizontal", {
  19433. get: function () {
  19434. return this._isOrientationHorizontal;
  19435. },
  19436. set: function (value) {
  19437. this._isOrientationHorizontal = value;
  19438. },
  19439. enumerable: true,
  19440. configurable: true
  19441. });
  19442. StackPanel.prototype.createVisualTree = function () {
  19443. _super.prototype.createVisualTree.call(this);
  19444. // A StackPanel Control has a Group2D, child of the visualPlaceHolder, which is the Children placeholder.
  19445. // The Children UIElement Tree will be create inside this placeholder.
  19446. this._childrenPlaceholder = new BABYLON.Group2D({ parent: this._visualPlaceholder, id: "StackPanel Children Placeholder of " + this.id });
  19447. var p = this._childrenPlaceholder;
  19448. p.layoutEngine = this.isOrientationHorizontal ? BABYLON.StackPanelLayoutEngine.Horizontal : BABYLON.StackPanelLayoutEngine.Vertical;
  19449. // The UIElement padding properties (padding and paddingAlignment) are bound to the Group2D Children placeholder, we bound to the Margin properties as the Group2D acts as an inner element already, so margin of inner is padding.
  19450. p.dataSource = this;
  19451. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "padding", BABYLON.DataBinding.MODE_ONEWAY);
  19452. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "paddingAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  19453. // The UIElement set the childrenPlaceholder with the visual returned by the renderingTemplate.
  19454. // But it's not the case for a StackPanel, the placeholder of UIElement Children (the content)
  19455. this._visualChildrenPlaceholder = this._childrenPlaceholder;
  19456. };
  19457. Object.defineProperty(StackPanel.prototype, "children", {
  19458. get: function () {
  19459. return this._children;
  19460. },
  19461. enumerable: true,
  19462. configurable: true
  19463. });
  19464. StackPanel.prototype._getChildren = function () {
  19465. return this.children;
  19466. };
  19467. return StackPanel;
  19468. }(BABYLON.UIElement));
  19469. StackPanel.STACKPANEL_PROPCOUNT = BABYLON.UIElement.UIELEMENT_PROPCOUNT + 3;
  19470. __decorate([
  19471. BABYLON.dependencyProperty(StackPanel_1.STACKPANEL_PROPCOUNT + 0, function (pi) { return StackPanel_1.orientationHorizontalProperty = pi; })
  19472. ], StackPanel.prototype, "isOrientationHorizontal", null);
  19473. StackPanel = StackPanel_1 = __decorate([
  19474. BABYLON.className("StackPanel", "BABYLON")
  19475. ], StackPanel);
  19476. BABYLON.StackPanel = StackPanel;
  19477. var DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate_1 = (function (_super) {
  19478. __extends(DefaultStackPanelRenderingTemplate, _super);
  19479. function DefaultStackPanelRenderingTemplate() {
  19480. return _super.apply(this, arguments) || this;
  19481. }
  19482. DefaultStackPanelRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  19483. return { root: visualPlaceholder, contentPlaceholder: visualPlaceholder };
  19484. };
  19485. DefaultStackPanelRenderingTemplate.prototype.attach = function (owner) {
  19486. _super.prototype.attach.call(this, owner);
  19487. };
  19488. return DefaultStackPanelRenderingTemplate;
  19489. }(BABYLON.UIElementRenderingTemplateBase));
  19490. DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate_1 = __decorate([
  19491. BABYLON.registerWindowRenderingTemplate("BABYLON.StackPanel", "Default", function () { return new DefaultStackPanelRenderingTemplate_1(); })
  19492. ], DefaultStackPanelRenderingTemplate);
  19493. BABYLON.DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate;
  19494. var StackPanel_1, DefaultStackPanelRenderingTemplate_1;
  19495. })(BABYLON || (BABYLON = {}));
  19496. var __extends = (this && this.__extends) || function (d, b) {
  19497. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19498. function __() { this.constructor = d; }
  19499. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  19500. };
  19501. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19502. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19503. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19504. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19505. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19506. };
  19507. var BABYLON;
  19508. (function (BABYLON) {
  19509. var Control = Control_1 = (function (_super) {
  19510. __extends(Control, _super);
  19511. function Control(settings) {
  19512. return _super.call(this, settings) || this;
  19513. }
  19514. Object.defineProperty(Control.prototype, "background", {
  19515. get: function () {
  19516. if (!this._background) {
  19517. this._background = new BABYLON.ObservableStringDictionary(false);
  19518. }
  19519. return this._background;
  19520. },
  19521. set: function (value) {
  19522. this.background.copyFrom(value);
  19523. },
  19524. enumerable: true,
  19525. configurable: true
  19526. });
  19527. Object.defineProperty(Control.prototype, "border", {
  19528. get: function () {
  19529. return this._border;
  19530. },
  19531. set: function (value) {
  19532. this._border = value;
  19533. },
  19534. enumerable: true,
  19535. configurable: true
  19536. });
  19537. Object.defineProperty(Control.prototype, "borderThickness", {
  19538. get: function () {
  19539. return this._borderThickness;
  19540. },
  19541. set: function (value) {
  19542. this._borderThickness = value;
  19543. },
  19544. enumerable: true,
  19545. configurable: true
  19546. });
  19547. Object.defineProperty(Control.prototype, "fontName", {
  19548. get: function () {
  19549. return this._fontName;
  19550. },
  19551. set: function (value) {
  19552. this._fontName = value;
  19553. },
  19554. enumerable: true,
  19555. configurable: true
  19556. });
  19557. Object.defineProperty(Control.prototype, "foreground", {
  19558. get: function () {
  19559. return this._foreground;
  19560. },
  19561. set: function (value) {
  19562. this._foreground = value;
  19563. },
  19564. enumerable: true,
  19565. configurable: true
  19566. });
  19567. return Control;
  19568. }(BABYLON.UIElement));
  19569. Control.CONTROL_PROPCOUNT = BABYLON.UIElement.UIELEMENT_PROPCOUNT + 5;
  19570. __decorate([
  19571. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 0, function (pi) { return Control_1.backgroundProperty = pi; })
  19572. ], Control.prototype, "background", null);
  19573. __decorate([
  19574. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 1, function (pi) { return Control_1.borderProperty = pi; })
  19575. ], Control.prototype, "border", null);
  19576. __decorate([
  19577. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 2, function (pi) { return Control_1.borderThicknessProperty = pi; })
  19578. ], Control.prototype, "borderThickness", null);
  19579. __decorate([
  19580. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 3, function (pi) { return Control_1.fontNameProperty = pi; })
  19581. ], Control.prototype, "fontName", null);
  19582. __decorate([
  19583. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 4, function (pi) { return Control_1.foregroundProperty = pi; })
  19584. ], Control.prototype, "foreground", null);
  19585. Control = Control_1 = __decorate([
  19586. BABYLON.className("Control", "BABYLON")
  19587. ], Control);
  19588. BABYLON.Control = Control;
  19589. var Control_1;
  19590. })(BABYLON || (BABYLON = {}));
  19591. var __extends = (this && this.__extends) || function (d, b) {
  19592. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19593. function __() { this.constructor = d; }
  19594. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  19595. };
  19596. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19597. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19598. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19599. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19600. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19601. };
  19602. var BABYLON;
  19603. (function (BABYLON) {
  19604. var ContentControl = ContentControl_1 = (function (_super) {
  19605. __extends(ContentControl, _super);
  19606. function ContentControl(settings) {
  19607. var _this;
  19608. if (!settings) {
  19609. settings = {};
  19610. }
  19611. _this = _super.call(this, settings) || this;
  19612. if (settings.content != null) {
  19613. _this._content = settings.content;
  19614. }
  19615. return _this;
  19616. }
  19617. ContentControl.prototype.dispose = function () {
  19618. if (this.isDisposed) {
  19619. return false;
  19620. }
  19621. if (this.content && this.content.dispose) {
  19622. this.content.dispose();
  19623. this.content = null;
  19624. }
  19625. if (this.__contentUIElement) {
  19626. this.__contentUIElement.dispose();
  19627. this.__contentUIElement = null;
  19628. }
  19629. _super.prototype.dispose.call(this);
  19630. return true;
  19631. };
  19632. Object.defineProperty(ContentControl.prototype, "content", {
  19633. get: function () {
  19634. return this._content;
  19635. },
  19636. set: function (value) {
  19637. this._content = value;
  19638. },
  19639. enumerable: true,
  19640. configurable: true
  19641. });
  19642. Object.defineProperty(ContentControl.prototype, "_contentUIElement", {
  19643. get: function () {
  19644. if (!this.__contentUIElement) {
  19645. this._buildContentUIElement();
  19646. }
  19647. return this.__contentUIElement;
  19648. },
  19649. enumerable: true,
  19650. configurable: true
  19651. });
  19652. ContentControl.prototype._createVisualTree = function () {
  19653. // Base implementation will create the Group2D for the Visual Placeholder and its Visual Tree
  19654. _super.prototype._createVisualTree.call(this);
  19655. // A Content Control has a Group2D, child of the visualPlaceHolder, which is the Content placeholder.
  19656. // The Content UIElement Tree will be create inside this placeholder.
  19657. this._contentPlaceholder = new BABYLON.Group2D({ parent: this._visualPlaceholder, id: "ContentControl Content Placeholder of " + this.id });
  19658. var p = this._contentPlaceholder;
  19659. // The UIElement padding properties (padding and paddingAlignment) are bound to the Group2D Content placeholder, we bound to the Margin properties as the Group2D acts as an inner element already, so margin of inner is padding.
  19660. p.dataSource = this;
  19661. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "padding", BABYLON.DataBinding.MODE_ONEWAY);
  19662. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "paddingAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  19663. // The UIElement set the childrenPlaceholder with the visual returned by the renderingTemplate.
  19664. // But it's not the case for a ContentControl, the placeholder of UIElement Children (the content)
  19665. this._visualChildrenPlaceholder = this._contentPlaceholder;
  19666. };
  19667. ContentControl.prototype._buildContentUIElement = function () {
  19668. var c = this._content;
  19669. this.__contentUIElement = null;
  19670. // Already a UIElement
  19671. if (c instanceof BABYLON.UIElement) {
  19672. this.__contentUIElement = c;
  19673. }
  19674. else if ((typeof c === "string") || (typeof c === "boolean") || (typeof c === "number")) {
  19675. var l = new BABYLON.Label({ parent: this, id: "Content of " + this.id });
  19676. var binding = new BABYLON.DataBinding();
  19677. binding.propertyPathName = "content";
  19678. binding.stringFormat = function (v) { return "" + v; };
  19679. binding.dataSource = this;
  19680. l.createDataBinding(BABYLON.Label.textProperty, binding);
  19681. this.__contentUIElement = l;
  19682. }
  19683. else {
  19684. }
  19685. if (this.__contentUIElement) {
  19686. this.__contentUIElement._patchUIElement(this.ownerWindow, this);
  19687. }
  19688. };
  19689. ContentControl.prototype._getChildren = function () {
  19690. var children = new Array();
  19691. if (this.content) {
  19692. children.push(this._contentUIElement);
  19693. }
  19694. return children;
  19695. };
  19696. return ContentControl;
  19697. }(BABYLON.Control));
  19698. ContentControl.CONTENTCONTROL_PROPCOUNT = BABYLON.Control.CONTROL_PROPCOUNT + 2;
  19699. __decorate([
  19700. BABYLON.dependencyProperty(BABYLON.Control.CONTROL_PROPCOUNT + 0, function (pi) { return ContentControl_1.contentProperty = pi; })
  19701. ], ContentControl.prototype, "content", null);
  19702. ContentControl = ContentControl_1 = __decorate([
  19703. BABYLON.className("ContentControl", "BABYLON")
  19704. ], ContentControl);
  19705. BABYLON.ContentControl = ContentControl;
  19706. var ContentControl_1;
  19707. })(BABYLON || (BABYLON = {}));
  19708. var __extends = (this && this.__extends) || function (d, b) {
  19709. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19710. function __() { this.constructor = d; }
  19711. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  19712. };
  19713. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19714. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19715. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19716. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19717. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19718. };
  19719. var BABYLON;
  19720. (function (BABYLON) {
  19721. var FocusScopeData = (function () {
  19722. function FocusScopeData(focusScope) {
  19723. this.focusScope = focusScope;
  19724. this.focusedElement = null;
  19725. }
  19726. return FocusScopeData;
  19727. }());
  19728. var FocusManager = (function () {
  19729. function FocusManager() {
  19730. this._focusScopes = new BABYLON.StringDictionary();
  19731. this._rootScope = new FocusScopeData(null);
  19732. this._activeScope = null;
  19733. }
  19734. FocusManager.prototype.setFocusOn = function (el, focusScope) {
  19735. var fsd = (focusScope != null) ? this._focusScopes.getOrAddWithFactory(focusScope.uid, function (k) { return new FocusScopeData(focusScope); }) : this._rootScope;
  19736. if (fsd.focusedElement !== el) {
  19737. // Remove focus from current
  19738. if (fsd.focusedElement) {
  19739. fsd.focusedElement.isFocused = false;
  19740. }
  19741. fsd.focusedElement = el;
  19742. }
  19743. if (this._activeScope !== fsd) {
  19744. this._activeScope = fsd;
  19745. }
  19746. };
  19747. return FocusManager;
  19748. }());
  19749. BABYLON.FocusManager = FocusManager;
  19750. var GUISceneData = (function () {
  19751. function GUISceneData(scene) {
  19752. this.scene = scene;
  19753. this.screenSpaceCanvas = new BABYLON.ScreenSpaceCanvas2D(scene, { id: "GUI Canvas", cachingStrategy: BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE });
  19754. this.focusManager = new FocusManager();
  19755. }
  19756. return GUISceneData;
  19757. }());
  19758. var Window = Window_1 = (function (_super) {
  19759. __extends(Window, _super);
  19760. function Window(scene, settings) {
  19761. var _this;
  19762. if (!settings) {
  19763. settings = {};
  19764. }
  19765. _this = _super.call(this, settings) || this;
  19766. // Per default a Window is focus scope
  19767. _this.isFocusScope = true;
  19768. _this.isActive = false;
  19769. if (!_this._UIElementVisualToBuildList) {
  19770. _this._UIElementVisualToBuildList = new Array();
  19771. }
  19772. // Patch the owner and also the parent property through the whole tree
  19773. _this._patchUIElement(_this, null);
  19774. // Screen Space UI
  19775. if (!settings.worldPosition && !settings.worldRotation) {
  19776. _this._sceneData = Window_1.getSceneData(scene);
  19777. _this._canvas = _this._sceneData.screenSpaceCanvas;
  19778. _this._isWorldSpaceCanvas = false;
  19779. _this._left = (settings.left != null) ? settings.left : 0;
  19780. _this._bottom = (settings.bottom != null) ? settings.bottom : 0;
  19781. }
  19782. else {
  19783. var w = (settings.width == null) ? 100 : settings.width;
  19784. var h = (settings.height == null) ? 100 : settings.height;
  19785. var wpos = (settings.worldPosition == null) ? BABYLON.Vector3.Zero() : settings.worldPosition;
  19786. var wrot = (settings.worldRotation == null) ? BABYLON.Quaternion.Identity() : settings.worldRotation;
  19787. _this._canvas = new BABYLON.WorldSpaceCanvas2D(scene, new BABYLON.Size(w, h), { id: "GUI Canvas", cachingStrategy: BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE, worldPosition: wpos, worldRotation: wrot });
  19788. _this._isWorldSpaceCanvas = true;
  19789. }
  19790. _this._renderObserver = _this._canvas.renderObservable.add(function (e, s) { return _this._canvasPreRender(); }, BABYLON.Canvas2D.RENDEROBSERVABLE_PRE);
  19791. _this._disposeObserver = _this._canvas.disposeObservable.add(function (e, s) { return _this._canvasDisposed(); });
  19792. _this._canvas.propertyChanged.add(function (e, s) {
  19793. if (e.propertyName === "overPrim") {
  19794. _this._overPrimChanged(e.oldValue, e.newValue);
  19795. }
  19796. });
  19797. _this._mouseOverUIElement = null;
  19798. return _this;
  19799. }
  19800. Object.defineProperty(Window.prototype, "canvas", {
  19801. get: function () {
  19802. return this._canvas;
  19803. },
  19804. enumerable: true,
  19805. configurable: true
  19806. });
  19807. Object.defineProperty(Window.prototype, "left", {
  19808. get: function () {
  19809. return this._left;
  19810. },
  19811. set: function (value) {
  19812. var old = new BABYLON.Vector2(this._left, this._bottom);
  19813. this._left = value;
  19814. this.onPropertyChanged("_position", old, this._position);
  19815. },
  19816. enumerable: true,
  19817. configurable: true
  19818. });
  19819. Object.defineProperty(Window.prototype, "bottom", {
  19820. get: function () {
  19821. return this._bottom;
  19822. },
  19823. set: function (value) {
  19824. var old = new BABYLON.Vector2(this._left, this._bottom);
  19825. this._bottom = value;
  19826. this.onPropertyChanged("_position", old, this._position);
  19827. },
  19828. enumerable: true,
  19829. configurable: true
  19830. });
  19831. Object.defineProperty(Window.prototype, "position", {
  19832. get: function () {
  19833. return this._position;
  19834. },
  19835. set: function (value) {
  19836. this._left = value.x;
  19837. this._bottom = value.y;
  19838. },
  19839. enumerable: true,
  19840. configurable: true
  19841. });
  19842. Object.defineProperty(Window.prototype, "isActive", {
  19843. get: function () {
  19844. return this._isActive;
  19845. },
  19846. set: function (value) {
  19847. this._isActive = value;
  19848. },
  19849. enumerable: true,
  19850. configurable: true
  19851. });
  19852. Object.defineProperty(Window.prototype, "focusManager", {
  19853. get: function () {
  19854. return this._sceneData.focusManager;
  19855. },
  19856. enumerable: true,
  19857. configurable: true
  19858. });
  19859. Object.defineProperty(Window.prototype, "_position", {
  19860. get: function () {
  19861. return new BABYLON.Vector2(this.left, this.bottom);
  19862. },
  19863. enumerable: true,
  19864. configurable: true
  19865. });
  19866. Window.prototype.createVisualTree = function () {
  19867. _super.prototype.createVisualTree.call(this);
  19868. var p = this._visualPlaceholder;
  19869. p.createSimpleDataBinding(BABYLON.Group2D.positionProperty, "position");
  19870. };
  19871. Window.prototype._registerVisualToBuild = function (uiel) {
  19872. if (uiel._isFlagSet(BABYLON.UIElement.flagVisualToBuild)) {
  19873. return;
  19874. }
  19875. if (!this._UIElementVisualToBuildList) {
  19876. this._UIElementVisualToBuildList = new Array();
  19877. }
  19878. this._UIElementVisualToBuildList.push(uiel);
  19879. uiel._setFlags(BABYLON.UIElement.flagVisualToBuild);
  19880. };
  19881. Window.prototype._overPrimChanged = function (oldPrim, newPrim) {
  19882. var curOverEl = this._mouseOverUIElement;
  19883. var newOverEl = null;
  19884. var curGroup = newPrim ? newPrim.traverseUp(function (p) { return p instanceof BABYLON.Group2D; }) : null;
  19885. while (curGroup) {
  19886. var uiel = curGroup.getExternalData("_GUIOwnerElement_");
  19887. if (uiel) {
  19888. newOverEl = uiel;
  19889. break;
  19890. }
  19891. curGroup = curGroup.parent ? curGroup.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D; }) : null;
  19892. }
  19893. if (curOverEl === newOverEl) {
  19894. return;
  19895. }
  19896. if (curOverEl) {
  19897. curOverEl.isMouseOver = false;
  19898. }
  19899. if (newOverEl) {
  19900. newOverEl.isMouseOver = true;
  19901. }
  19902. this._mouseOverUIElement = newOverEl;
  19903. };
  19904. Window.prototype._canvasPreRender = function () {
  19905. // Check if we have visual to create
  19906. if (this._UIElementVisualToBuildList.length > 0) {
  19907. // Sort the UI Element to get the highest (so lowest hierarchy depth) in the hierarchy tree first
  19908. var sortedElementList = this._UIElementVisualToBuildList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  19909. for (var _i = 0, sortedElementList_1 = sortedElementList; _i < sortedElementList_1.length; _i++) {
  19910. var el = sortedElementList_1[_i];
  19911. el._createVisualTree();
  19912. }
  19913. this._UIElementVisualToBuildList.splice(0);
  19914. }
  19915. };
  19916. Window.prototype._canvasDisposed = function () {
  19917. this._canvas.disposeObservable.remove(this._disposeObserver);
  19918. this._canvas.renderObservable.remove(this._renderObserver);
  19919. };
  19920. Window.getSceneData = function (scene) {
  19921. return Window_1._sceneData.getOrAddWithFactory(scene.uid, function (k) { return new GUISceneData(scene); });
  19922. };
  19923. return Window;
  19924. }(BABYLON.ContentControl));
  19925. Window.WINDOW_PROPCOUNT = BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 4;
  19926. Window._sceneData = new BABYLON.StringDictionary();
  19927. __decorate([
  19928. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 0, function (pi) { return Window_1.leftProperty = pi; })
  19929. ], Window.prototype, "left", null);
  19930. __decorate([
  19931. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 1, function (pi) { return Window_1.bottomProperty = pi; })
  19932. ], Window.prototype, "bottom", null);
  19933. __decorate([
  19934. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 2, function (pi) { return Window_1.positionProperty = pi; })
  19935. ], Window.prototype, "position", null);
  19936. __decorate([
  19937. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 3, function (pi) { return Window_1.isActiveProperty = pi; })
  19938. ], Window.prototype, "isActive", null);
  19939. Window = Window_1 = __decorate([
  19940. BABYLON.className("Window", "BABYLON")
  19941. ], Window);
  19942. BABYLON.Window = Window;
  19943. var DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate_1 = (function (_super) {
  19944. __extends(DefaultWindowRenderingTemplate, _super);
  19945. function DefaultWindowRenderingTemplate() {
  19946. return _super.apply(this, arguments) || this;
  19947. }
  19948. DefaultWindowRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  19949. var r = new BABYLON.Rectangle2D({ parent: visualPlaceholder, fill: "#808080FF" });
  19950. return { root: r, contentPlaceholder: r };
  19951. };
  19952. return DefaultWindowRenderingTemplate;
  19953. }(BABYLON.UIElementRenderingTemplateBase));
  19954. DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate_1 = __decorate([
  19955. BABYLON.registerWindowRenderingTemplate("BABYLON.Window", "Default", function () { return new DefaultWindowRenderingTemplate_1(); })
  19956. ], DefaultWindowRenderingTemplate);
  19957. BABYLON.DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate;
  19958. var Window_1, DefaultWindowRenderingTemplate_1;
  19959. })(BABYLON || (BABYLON = {}));
  19960. var __extends = (this && this.__extends) || function (d, b) {
  19961. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19962. function __() { this.constructor = d; }
  19963. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  19964. };
  19965. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19966. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19967. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19968. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19969. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19970. };
  19971. var BABYLON;
  19972. (function (BABYLON) {
  19973. var Label = Label_1 = (function (_super) {
  19974. __extends(Label, _super);
  19975. function Label(settings) {
  19976. var _this;
  19977. if (!settings) {
  19978. settings = {};
  19979. }
  19980. _this = _super.call(this, settings) || this;
  19981. if (settings.text != null) {
  19982. _this.text = settings.text;
  19983. }
  19984. return _this;
  19985. }
  19986. Object.defineProperty(Label.prototype, "_position", {
  19987. get: function () {
  19988. return BABYLON.Vector2.Zero();
  19989. },
  19990. enumerable: true,
  19991. configurable: true
  19992. });
  19993. Label.prototype._getChildren = function () {
  19994. return Label_1._emptyArray;
  19995. };
  19996. Label.prototype.createVisualTree = function () {
  19997. _super.prototype.createVisualTree.call(this);
  19998. var p = this._visualChildrenPlaceholder;
  19999. };
  20000. Object.defineProperty(Label.prototype, "text", {
  20001. get: function () {
  20002. return this._text;
  20003. },
  20004. set: function (value) {
  20005. this._text = value;
  20006. },
  20007. enumerable: true,
  20008. configurable: true
  20009. });
  20010. return Label;
  20011. }(BABYLON.Control));
  20012. Label._emptyArray = new Array();
  20013. __decorate([
  20014. BABYLON.dependencyProperty(BABYLON.Control.CONTROL_PROPCOUNT + 0, function (pi) { return Label_1.textProperty = pi; })
  20015. ], Label.prototype, "text", null);
  20016. Label = Label_1 = __decorate([
  20017. BABYLON.className("Label", "BABYLON")
  20018. ], Label);
  20019. BABYLON.Label = Label;
  20020. var DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate_1 = (function (_super) {
  20021. __extends(DefaultLabelRenderingTemplate, _super);
  20022. function DefaultLabelRenderingTemplate() {
  20023. return _super.apply(this, arguments) || this;
  20024. }
  20025. DefaultLabelRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  20026. var r = new BABYLON.Text2D("", { parent: visualPlaceholder });
  20027. r.createSimpleDataBinding(BABYLON.Text2D.textProperty, "text");
  20028. r.dataSource = owner;
  20029. return { root: r, contentPlaceholder: r };
  20030. };
  20031. return DefaultLabelRenderingTemplate;
  20032. }(BABYLON.UIElementRenderingTemplateBase));
  20033. DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate_1 = __decorate([
  20034. BABYLON.registerWindowRenderingTemplate("BABYLON.Label", "Default", function () { return new DefaultLabelRenderingTemplate_1(); })
  20035. ], DefaultLabelRenderingTemplate);
  20036. BABYLON.DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate;
  20037. var Label_1, DefaultLabelRenderingTemplate_1;
  20038. })(BABYLON || (BABYLON = {}));
  20039. var __extends = (this && this.__extends) || function (d, b) {
  20040. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20041. function __() { this.constructor = d; }
  20042. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  20043. };
  20044. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  20045. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  20046. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  20047. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  20048. return c > 3 && r && Object.defineProperty(target, key, r), r;
  20049. };
  20050. var BABYLON;
  20051. (function (BABYLON) {
  20052. var Button = Button_1 = (function (_super) {
  20053. __extends(Button, _super);
  20054. function Button(settings) {
  20055. var _this;
  20056. if (!settings) {
  20057. settings = {};
  20058. }
  20059. _this = _super.call(this, settings) || this;
  20060. if (settings.paddingAlignment == null) {
  20061. _this.paddingAlignment.horizontal = BABYLON.PrimitiveAlignment.AlignCenter;
  20062. _this.paddingAlignment.vertical = BABYLON.PrimitiveAlignment.AlignCenter;
  20063. }
  20064. _this._normalStateBackground = new BABYLON.ObservableStringDictionary(false);
  20065. _this._normalStateBorder = new BABYLON.ObservableStringDictionary(false);
  20066. _this._defaultStateBackground = new BABYLON.ObservableStringDictionary(false);
  20067. _this._defaultStateBorder = new BABYLON.ObservableStringDictionary(false);
  20068. _this._normalStateBackground.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#337AB7FF"));
  20069. _this._normalStateBackground.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#7BA9D0FF"));
  20070. _this._normalStateBackground.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#286090FF"));
  20071. _this._normalStateBackground.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#1E496EFF"));
  20072. _this._normalStateBorder.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#2E6DA4FF"));
  20073. _this._normalStateBorder.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#77A0C4FF"));
  20074. _this._normalStateBorder.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#204D74FF"));
  20075. _this._normalStateBorder.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#2E5D9EFF"));
  20076. _this._defaultStateBackground.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"));
  20077. _this._defaultStateBackground.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"));
  20078. _this._defaultStateBackground.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#E6E6E6FF"));
  20079. _this._defaultStateBackground.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#D4D4D4FF"));
  20080. _this._defaultStateBorder.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#CCCCCCFF"));
  20081. _this._defaultStateBorder.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#DEDEDEFF"));
  20082. _this._defaultStateBorder.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#ADADADFF"));
  20083. _this._defaultStateBorder.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#6C8EC5FF"));
  20084. return _this;
  20085. }
  20086. Object.defineProperty(Button, "pushedState", {
  20087. get: function () {
  20088. return Button_1._pushedState;
  20089. },
  20090. enumerable: true,
  20091. configurable: true
  20092. });
  20093. Object.defineProperty(Button.prototype, "isPushed", {
  20094. get: function () {
  20095. return this._isPushed;
  20096. },
  20097. set: function (value) {
  20098. this._isPushed = value;
  20099. },
  20100. enumerable: true,
  20101. configurable: true
  20102. });
  20103. Object.defineProperty(Button.prototype, "isDefault", {
  20104. get: function () {
  20105. return this._isDefault;
  20106. },
  20107. set: function (value) {
  20108. this._isDefault = value;
  20109. },
  20110. enumerable: true,
  20111. configurable: true
  20112. });
  20113. Object.defineProperty(Button.prototype, "isOutline", {
  20114. get: function () {
  20115. return this._isOutline;
  20116. },
  20117. set: function (value) {
  20118. this._isOutline = value;
  20119. },
  20120. enumerable: true,
  20121. configurable: true
  20122. });
  20123. Object.defineProperty(Button.prototype, "clickObservable", {
  20124. get: function () {
  20125. if (!this._clickObservable) {
  20126. this._clickObservable = new BABYLON.Observable();
  20127. }
  20128. return this._clickObservable;
  20129. },
  20130. enumerable: true,
  20131. configurable: true
  20132. });
  20133. Button.prototype._raiseClick = function () {
  20134. if (this._clickObservable && this._clickObservable.hasObservers()) {
  20135. this._clickObservable.notifyObservers(this);
  20136. }
  20137. };
  20138. Button.prototype.createVisualTree = function () {
  20139. var _this = this;
  20140. _super.prototype.createVisualTree.call(this);
  20141. var p = this._visualPlaceholder;
  20142. p.pointerEventObservable.add(function (e, s) {
  20143. // check if input must be discarded
  20144. if (!_this.isVisible || !_this.isEnabled) {
  20145. return;
  20146. }
  20147. // We reject an event coming from the placeholder because it means it's on an empty spot, so it's not valid.
  20148. if (e.relatedTarget === _this._visualPlaceholder) {
  20149. return;
  20150. }
  20151. if (s.mask === BABYLON.PrimitivePointerInfo.PointerUp) {
  20152. _this._raiseClick();
  20153. _this.isPushed = false;
  20154. }
  20155. else if (s.mask === BABYLON.PrimitivePointerInfo.PointerDown) {
  20156. _this.isPushed = true;
  20157. _this.isFocused = true;
  20158. }
  20159. }, BABYLON.PrimitivePointerInfo.PointerUp | BABYLON.PrimitivePointerInfo.PointerDown);
  20160. };
  20161. Object.defineProperty(Button.prototype, "normalStateBackground", {
  20162. get: function () {
  20163. return this._normalStateBackground;
  20164. },
  20165. enumerable: true,
  20166. configurable: true
  20167. });
  20168. Object.defineProperty(Button.prototype, "defaultStateBackground", {
  20169. get: function () {
  20170. return this._defaultStateBackground;
  20171. },
  20172. enumerable: true,
  20173. configurable: true
  20174. });
  20175. Object.defineProperty(Button.prototype, "normalStateBorder", {
  20176. get: function () {
  20177. return this._normalStateBorder;
  20178. },
  20179. enumerable: true,
  20180. configurable: true
  20181. });
  20182. Object.defineProperty(Button.prototype, "defaultStateBorder", {
  20183. get: function () {
  20184. return this._defaultStateBorder;
  20185. },
  20186. enumerable: true,
  20187. configurable: true
  20188. });
  20189. return Button;
  20190. }(BABYLON.ContentControl));
  20191. Button.BUTTON_PROPCOUNT = BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 3;
  20192. Button._pushedState = "Pushed";
  20193. __decorate([
  20194. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 0, function (pi) { return Button_1.isPushedProperty = pi; })
  20195. ], Button.prototype, "isPushed", null);
  20196. __decorate([
  20197. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 1, function (pi) { return Button_1.isDefaultProperty = pi; })
  20198. ], Button.prototype, "isDefault", null);
  20199. __decorate([
  20200. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 2, function (pi) { return Button_1.isOutlineProperty = pi; })
  20201. ], Button.prototype, "isOutline", null);
  20202. Button = Button_1 = __decorate([
  20203. BABYLON.className("Button", "BABYLON")
  20204. ], Button);
  20205. BABYLON.Button = Button;
  20206. var DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate_1 = (function (_super) {
  20207. __extends(DefaultButtonRenderingTemplate, _super);
  20208. function DefaultButtonRenderingTemplate() {
  20209. return _super.apply(this, arguments) || this;
  20210. }
  20211. DefaultButtonRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  20212. this._rect = new BABYLON.Rectangle2D({ parent: visualPlaceholder, fill: "#FF8080FF", border: "#FF8080FF", roundRadius: 10, borderThickness: 2 });
  20213. this.stateChange();
  20214. return { root: this._rect, contentPlaceholder: this._rect };
  20215. };
  20216. DefaultButtonRenderingTemplate.prototype.attach = function (owner) {
  20217. var _this = this;
  20218. _super.prototype.attach.call(this, owner);
  20219. this.owner.propertyChanged.add(function (e, s) { return _this.stateChange(); }, BABYLON.UIElement.isEnabledProperty.flagId |
  20220. BABYLON.UIElement.isFocusedProperty.flagId |
  20221. BABYLON.UIElement.isMouseOverProperty.flagId |
  20222. Button.isDefaultProperty.flagId |
  20223. Button.isOutlineProperty.flagId |
  20224. Button.isPushedProperty.flagId);
  20225. // Register for brush change and update the Visual
  20226. var button = owner;
  20227. button.normalStateBackground.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  20228. button.normalStateBorder.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  20229. button.defaultStateBackground.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  20230. button.defaultStateBorder.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  20231. };
  20232. DefaultButtonRenderingTemplate.prototype.stateChange = function () {
  20233. //console.log("state changed");
  20234. var b = this.owner;
  20235. var state = BABYLON.UIElement.enabledState;
  20236. var bg = b.isDefault ? b.defaultStateBackground.get(state) : b.normalStateBackground.get(state);
  20237. var bd = b.isDefault ? b.defaultStateBorder.get(state) : b.normalStateBorder.get(state);
  20238. if (b.isPushed) {
  20239. state = Button.pushedState;
  20240. if (b.isDefault) {
  20241. bg = b.defaultStateBackground.get(state);
  20242. bd = b.defaultStateBorder.get(state);
  20243. }
  20244. else {
  20245. bg = b.normalStateBackground.get(state);
  20246. bd = b.normalStateBorder.get(state);
  20247. }
  20248. }
  20249. else if (b.isMouseOver) {
  20250. state = BABYLON.UIElement.mouseOverState;
  20251. if (b.isDefault) {
  20252. bg = b.defaultStateBackground.get(state);
  20253. bd = b.defaultStateBorder.get(state);
  20254. }
  20255. else {
  20256. bg = b.normalStateBackground.get(state);
  20257. bd = b.normalStateBorder.get(state);
  20258. }
  20259. }
  20260. else if (!b.isEnabled) {
  20261. state = BABYLON.UIElement.disabledState;
  20262. if (b.isDefault) {
  20263. bg = b.defaultStateBackground.get(state);
  20264. bd = b.defaultStateBorder.get(state);
  20265. }
  20266. else {
  20267. bg = b.normalStateBackground.get(state);
  20268. bd = b.normalStateBorder.get(state);
  20269. }
  20270. }
  20271. this._rect.fill = bg;
  20272. this._rect.border = bd;
  20273. };
  20274. return DefaultButtonRenderingTemplate;
  20275. }(BABYLON.UIElementRenderingTemplateBase));
  20276. DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate_1 = __decorate([
  20277. BABYLON.registerWindowRenderingTemplate("BABYLON.Button", "Default", function () { return new DefaultButtonRenderingTemplate_1(); })
  20278. ], DefaultButtonRenderingTemplate);
  20279. BABYLON.DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate;
  20280. var Button_1, DefaultButtonRenderingTemplate_1;
  20281. })(BABYLON || (BABYLON = {}));