babylon.canvas2d.js 900 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278
  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 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;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),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 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;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),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 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;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),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 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,topLeftUV.y+sizeUV.y);\nvScale9=scale9;\n}\nvScaleFactor=scaleFactor;\n#endif\nvOpacity=opacity;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),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,1.0);\n#else\nvec4 color=texture2D(diffuseSampler,vUV);\ngl_FragColor=color*vColor;\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 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;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),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);\n}\ngl_Position=pp;\n} ";
  13. var BABYLON;
  14. (function (BABYLON) {
  15. var Tri2DInfo = (function () {
  16. /**
  17. * 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
  18. */
  19. function Tri2DInfo(a, b, c) {
  20. if (a === null && b === null && c === null) {
  21. this.a = BABYLON.Vector2.Zero();
  22. this.b = BABYLON.Vector2.Zero();
  23. this.c = BABYLON.Vector2.Zero();
  24. this.center = BABYLON.Vector2.Zero();
  25. this.radius = 0;
  26. return;
  27. }
  28. this.a = a.clone();
  29. this.b = b.clone();
  30. this.c = c.clone();
  31. this._updateCenterRadius();
  32. }
  33. Tri2DInfo.Zero = function () {
  34. return new Tri2DInfo(null, null, null);
  35. };
  36. Tri2DInfo.prototype.set = function (a, b, c) {
  37. this.a.copyFrom(a);
  38. this.b.copyFrom(b);
  39. this.c.copyFrom(c);
  40. this._updateCenterRadius();
  41. };
  42. Tri2DInfo.prototype.transformInPlace = function (transform) {
  43. BABYLON.Vector2.TransformToRef(this.a, transform, this.a);
  44. BABYLON.Vector2.TransformToRef(this.b, transform, this.b);
  45. BABYLON.Vector2.TransformToRef(this.c, transform, this.c);
  46. this._updateCenterRadius();
  47. };
  48. Tri2DInfo.prototype.doesContain = function (p) {
  49. return BABYLON.Vector2.PointInTriangle(p, this.a, this.b, this.c);
  50. };
  51. Tri2DInfo.prototype._updateCenterRadius = function () {
  52. this.center.x = (this.a.x + this.b.x + this.c.x) / 3;
  53. this.center.y = (this.a.y + this.b.y + this.c.y) / 3;
  54. var la = BABYLON.Vector2.DistanceSquared(this.a, this.center);
  55. var lb = BABYLON.Vector2.DistanceSquared(this.b, this.center);
  56. var lc = BABYLON.Vector2.DistanceSquared(this.c, this.center);
  57. var rs = Math.max(Math.max(la, lb), lc);
  58. this.radius = Math.sqrt(rs);
  59. };
  60. return Tri2DInfo;
  61. }());
  62. BABYLON.Tri2DInfo = Tri2DInfo;
  63. var Tri2DArray = (function () {
  64. function Tri2DArray(count) {
  65. this._count = count;
  66. this._array = new Float32Array(9 * count);
  67. }
  68. Tri2DArray.prototype.clear = function (count) {
  69. if (this._count === count) {
  70. return;
  71. }
  72. this._count = count;
  73. this._array = new Float32Array(9 * count);
  74. };
  75. Tri2DArray.prototype.storeTriangle = function (index, a, b, c) {
  76. var center = new BABYLON.Vector2((a.x + b.x + c.x) / 3, (a.y + b.y + c.y) / 3);
  77. var la = BABYLON.Vector2.DistanceSquared(a, center);
  78. var lb = BABYLON.Vector2.DistanceSquared(b, center);
  79. var lc = BABYLON.Vector2.DistanceSquared(c, center);
  80. var rs = Math.max(Math.max(la, lb), lc);
  81. var radius = Math.sqrt(rs);
  82. var offset = index * 9;
  83. this._array[offset + 0] = a.x;
  84. this._array[offset + 1] = a.y;
  85. this._array[offset + 2] = b.x;
  86. this._array[offset + 3] = b.y;
  87. this._array[offset + 4] = c.x;
  88. this._array[offset + 5] = c.y;
  89. this._array[offset + 6] = center.x;
  90. this._array[offset + 7] = center.y;
  91. this._array[offset + 8] = radius;
  92. };
  93. /**
  94. * Store a triangle in a Tri2DInfo object
  95. * @param index the index of the triangle to store
  96. * @param tri2dInfo the instance that will contain the data, it must be already allocated with its inner object also allocated
  97. */
  98. Tri2DArray.prototype.storeToTri2DInfo = function (index, tri2dInfo) {
  99. if (index >= this._count) {
  100. throw new Error("Can't fetch the triangle at index " + index + ", max index is " + (this._count - 1));
  101. }
  102. var offset = index * 9;
  103. tri2dInfo.a.x = this._array[offset + 0];
  104. tri2dInfo.a.y = this._array[offset + 1];
  105. tri2dInfo.b.x = this._array[offset + 2];
  106. tri2dInfo.b.y = this._array[offset + 3];
  107. tri2dInfo.c.x = this._array[offset + 4];
  108. tri2dInfo.c.y = this._array[offset + 5];
  109. tri2dInfo.center.x = this._array[offset + 6];
  110. tri2dInfo.center.y = this._array[offset + 7];
  111. tri2dInfo.radius = this._array[offset + 8];
  112. };
  113. Tri2DArray.prototype.transformAndStoreToTri2DInfo = function (index, tri2dInfo, transform) {
  114. if (index >= this._count) {
  115. throw new Error("Can't fetch the triangle at index " + index + ", max index is " + (this._count - 1));
  116. }
  117. var offset = index * 9;
  118. tri2dInfo.a.x = this._array[offset + 0];
  119. tri2dInfo.a.y = this._array[offset + 1];
  120. tri2dInfo.b.x = this._array[offset + 2];
  121. tri2dInfo.b.y = this._array[offset + 3];
  122. tri2dInfo.c.x = this._array[offset + 4];
  123. tri2dInfo.c.y = this._array[offset + 5];
  124. tri2dInfo.transformInPlace(transform);
  125. };
  126. Object.defineProperty(Tri2DArray.prototype, "count", {
  127. get: function () {
  128. return this._count;
  129. },
  130. enumerable: true,
  131. configurable: true
  132. });
  133. Tri2DArray.prototype.doesContain = function (p) {
  134. Tri2DArray._checkInitStatics();
  135. var a = Tri2DArray.tempT[0];
  136. for (var i = 0; i < this.count; i++) {
  137. this.storeToTri2DInfo(i, a);
  138. if (a.doesContain(p)) {
  139. return true;
  140. }
  141. }
  142. return false;
  143. };
  144. Tri2DArray.doesIntersect = function (setA, setB, bToATransform) {
  145. Tri2DArray._checkInitStatics();
  146. var a = Tri2DArray.tempT[0];
  147. var b = Tri2DArray.tempT[1];
  148. var v0 = Tri2DArray.tempV[0];
  149. for (var curB = 0; curB < setB.count; curB++) {
  150. setB.transformAndStoreToTri2DInfo(curB, b, bToATransform);
  151. for (var curA = 0; curA < setA.count; curA++) {
  152. setA.storeToTri2DInfo(curA, a);
  153. // Fast rejection first
  154. v0.x = a.center.x - b.center.x;
  155. v0.y = a.center.y - b.center.y;
  156. if (v0.lengthSquared() > ((a.radius * a.radius) + (b.radius * b.radius))) {
  157. continue;
  158. }
  159. // Actual intersection test
  160. if (Math2D.TriangleTriangleDosIntersect(a.a, a.b, a.c, b.a, b.b, b.c)) {
  161. return true;
  162. }
  163. }
  164. }
  165. return false;
  166. };
  167. Tri2DArray._checkInitStatics = function () {
  168. if (Tri2DArray.tempT !== null) {
  169. return;
  170. }
  171. Tri2DArray.tempT = new Array(2);
  172. Tri2DArray.tempT[0] = new Tri2DInfo(null, null, null);
  173. Tri2DArray.tempT[1] = new Tri2DInfo(null, null, null);
  174. Tri2DArray.tempV = new Array(6);
  175. for (var i = 0; i < 6; i++) {
  176. Tri2DArray.tempV[i] = BABYLON.Vector2.Zero();
  177. }
  178. };
  179. return Tri2DArray;
  180. }());
  181. Tri2DArray.tempV = null;
  182. Tri2DArray.tempT = null;
  183. BABYLON.Tri2DArray = Tri2DArray;
  184. var Math2D = (function () {
  185. function Math2D() {
  186. }
  187. Math2D.Dot = function (a, b) {
  188. return a.x * b.x + a.y * b.y;
  189. };
  190. // From http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
  191. // 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/
  192. Math2D.LineLineDoesIntersect = function (segA1, segA2, segB1, segB2) {
  193. var s1_x = segA2.x - segA1.x;
  194. var s1_y = segA2.y - segA1.y;
  195. var s2_x = segB2.x - segB1.x;
  196. var s2_y = segB2.y - segB1.y;
  197. var s = (-s1_y * (segA1.x - segB1.x) + s1_x * (segA1.y - segB1.y)) / (-s2_x * s1_y + s1_x * s2_y);
  198. var t = (s2_x * (segA1.y - segB1.y) - s2_y * (segA1.x - segB1.x)) / (-s2_x * s1_y + s1_x * s2_y);
  199. if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
  200. return true;
  201. }
  202. return false;
  203. };
  204. // From http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
  205. Math2D.LineLineIntersection = function (p0, p1, p2, p3) {
  206. var s1_x = p1.x - p0.x;
  207. var s1_y = p1.y - p0.y;
  208. var s2_x = p3.x - p2.x;
  209. var s2_y = p3.y - p2.y;
  210. var s = (-s1_y * (p0.x - p2.x) + s1_x * (p0.y - p2.y)) / (-s2_x * s1_y + s1_x * s2_y);
  211. var t = (s2_x * (p0.y - p2.y) - s2_y * (p0.x - p2.x)) / (-s2_x * s1_y + s1_x * s2_y);
  212. if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
  213. return { res: true, xr: p0.x + (t * s1_x), yr: p0.y + (t * s1_y) };
  214. }
  215. return { res: false, xr: 0, yr: 0 };
  216. };
  217. // Tell me that it's slow and I'll answer: yes it is!
  218. // If you fancy to implement the SAT (Separating Axis Theorem) version: BE MY VERY WELCOMED GUEST!
  219. Math2D.TriangleTriangleDosIntersect = function (tri1A, tri1B, tri1C, tri2A, tri2B, tri2C) {
  220. if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2A, tri2B))
  221. return true;
  222. if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2A, tri2C))
  223. return true;
  224. if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2B, tri2C))
  225. return true;
  226. if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2A, tri2B))
  227. return true;
  228. if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2A, tri2C))
  229. return true;
  230. if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2B, tri2C))
  231. return true;
  232. if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2A, tri2B))
  233. return true;
  234. if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2A, tri2C))
  235. return true;
  236. if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2B, tri2C))
  237. return true;
  238. if (BABYLON.Vector2.PointInTriangle(tri2A, tri1A, tri1B, tri1C) &&
  239. BABYLON.Vector2.PointInTriangle(tri2B, tri1A, tri1B, tri1C) &&
  240. BABYLON.Vector2.PointInTriangle(tri2C, tri1A, tri1B, tri1C))
  241. return true;
  242. if (BABYLON.Vector2.PointInTriangle(tri1A, tri2A, tri2B, tri2C) &&
  243. BABYLON.Vector2.PointInTriangle(tri1B, tri2A, tri2B, tri2C) &&
  244. BABYLON.Vector2.PointInTriangle(tri1C, tri2A, tri2B, tri2C))
  245. return true;
  246. return false;
  247. };
  248. return Math2D;
  249. }());
  250. Math2D.v0 = BABYLON.Vector2.Zero();
  251. Math2D.v1 = BABYLON.Vector2.Zero();
  252. Math2D.v2 = BABYLON.Vector2.Zero();
  253. })(BABYLON || (BABYLON = {}));
  254. //# sourceMappingURL=babylon.math2D.js.map
  255. var BABYLON;
  256. (function (BABYLON) {
  257. var PropertyChangedInfo = (function () {
  258. function PropertyChangedInfo() {
  259. }
  260. return PropertyChangedInfo;
  261. }());
  262. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  263. /**
  264. * The purpose of this class is to provide a base implementation of the IPropertyChanged interface for the user to avoid rewriting a code needlessly.
  265. * 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.
  266. * 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)
  267. */
  268. var PropertyChangedBase = (function () {
  269. function PropertyChangedBase() {
  270. this._propertyChanged = null;
  271. }
  272. /**
  273. * Protected method to call when there's a change of value in a property set
  274. * @param propName the name of the concerned property
  275. * @param oldValue its old value
  276. * @param newValue its new value
  277. * @param mask an optional observable mask
  278. */
  279. PropertyChangedBase.prototype.onPropertyChanged = function (propName, oldValue, newValue, mask) {
  280. if (this.propertyChanged.hasObservers()) {
  281. var pci = PropertyChangedBase.calling ? new PropertyChangedInfo() : PropertyChangedBase.pci;
  282. pci.oldValue = oldValue;
  283. pci.newValue = newValue;
  284. pci.propertyName = propName;
  285. try {
  286. PropertyChangedBase.calling = true;
  287. this.propertyChanged.notifyObservers(pci, mask);
  288. }
  289. finally {
  290. PropertyChangedBase.calling = false;
  291. }
  292. }
  293. };
  294. Object.defineProperty(PropertyChangedBase.prototype, "propertyChanged", {
  295. /**
  296. * An observable that is triggered when a property (using of the XXXXLevelProperty decorator) has its value changing.
  297. * 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)
  298. */
  299. get: function () {
  300. if (!this._propertyChanged) {
  301. this._propertyChanged = new BABYLON.Observable();
  302. }
  303. return this._propertyChanged;
  304. },
  305. enumerable: true,
  306. configurable: true
  307. });
  308. return PropertyChangedBase;
  309. }());
  310. PropertyChangedBase.pci = new PropertyChangedInfo();
  311. PropertyChangedBase.calling = false;
  312. BABYLON.PropertyChangedBase = PropertyChangedBase;
  313. })(BABYLON || (BABYLON = {}));
  314. //# sourceMappingURL=babylon.IPropertyChanged.js.map
  315. var __extends = (this && this.__extends) || function (d, b) {
  316. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  317. function __() { this.constructor = d; }
  318. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  319. };
  320. var BABYLON;
  321. (function (BABYLON) {
  322. /**
  323. * Class for the ObservableArray.onArrayChanged observable
  324. */
  325. var ArrayChanged = (function () {
  326. function ArrayChanged() {
  327. this.action = 0;
  328. this.newItems = new Array();
  329. this.removedItems = new Array();
  330. this.changedItems = new Array();
  331. this.newStartingIndex = -1;
  332. this.removedStartingIndex = -1;
  333. }
  334. Object.defineProperty(ArrayChanged, "clearAction", {
  335. /**
  336. * The content of the array was totally cleared
  337. */
  338. get: function () {
  339. return ArrayChanged._clearAction;
  340. },
  341. enumerable: true,
  342. configurable: true
  343. });
  344. Object.defineProperty(ArrayChanged, "newItemsAction", {
  345. /**
  346. * A new item was added, the newItems field contains the key/value pairs
  347. */
  348. get: function () {
  349. return ArrayChanged._newItemsAction;
  350. },
  351. enumerable: true,
  352. configurable: true
  353. });
  354. Object.defineProperty(ArrayChanged, "removedItemsAction", {
  355. /**
  356. * An existing item was removed, the removedKey field contains its key
  357. */
  358. get: function () {
  359. return ArrayChanged._removedItemsAction;
  360. },
  361. enumerable: true,
  362. configurable: true
  363. });
  364. Object.defineProperty(ArrayChanged, "changedItemAction", {
  365. /**
  366. * One or many items in the array were changed, the
  367. */
  368. get: function () {
  369. return ArrayChanged._changedItemAction;
  370. },
  371. enumerable: true,
  372. configurable: true
  373. });
  374. Object.defineProperty(ArrayChanged, "replacedArrayAction", {
  375. /**
  376. * The array's content was totally changed
  377. * Depending on the method that used this mode the ChangedArray object may contains more information
  378. */
  379. get: function () {
  380. return ArrayChanged._replacedArrayAction;
  381. },
  382. enumerable: true,
  383. configurable: true
  384. });
  385. Object.defineProperty(ArrayChanged, "lengthChangedAction", {
  386. /**
  387. * The length of the array changed
  388. */
  389. get: function () {
  390. return ArrayChanged._lengthChangedAction;
  391. },
  392. enumerable: true,
  393. configurable: true
  394. });
  395. ArrayChanged.prototype.clear = function () {
  396. this.action = 0;
  397. this.newItems.splice(0);
  398. this.removedItems.splice(0);
  399. this.changedItems.splice(0);
  400. this.removedStartingIndex = this.removedStartingIndex = this.changedStartingIndex = 0;
  401. };
  402. return ArrayChanged;
  403. }());
  404. ArrayChanged._clearAction = 0x1;
  405. ArrayChanged._newItemsAction = 0x2;
  406. ArrayChanged._removedItemsAction = 0x4;
  407. ArrayChanged._replacedArrayAction = 0x8;
  408. ArrayChanged._lengthChangedAction = 0x10;
  409. ArrayChanged._changedItemAction = 0x20;
  410. BABYLON.ArrayChanged = ArrayChanged;
  411. var OAWatchedObjectChangedInfo = (function () {
  412. function OAWatchedObjectChangedInfo() {
  413. }
  414. return OAWatchedObjectChangedInfo;
  415. }());
  416. BABYLON.OAWatchedObjectChangedInfo = OAWatchedObjectChangedInfo;
  417. /**
  418. * This class mimics the Javascript Array and TypeScript Array<T> classes, adding new features concerning the Observable pattern.
  419. *
  420. */
  421. var ObservableArray = (function (_super) {
  422. __extends(ObservableArray, _super);
  423. /**
  424. * Create an Observable Array.
  425. * @param watchObjectsPropertyChange
  426. * @param array and optional array that will be encapsulated by this ObservableArray instance. That's right, it's NOT a copy!
  427. */
  428. function ObservableArray(watchObjectsPropertyChange, array) {
  429. var _this = _super.call(this) || this;
  430. _this.dci = new ArrayChanged();
  431. _this._callingArrayChanged = false;
  432. _this._array = (array != null) ? array : new Array();
  433. _this.dci = new ArrayChanged();
  434. _this._callingArrayChanged = false;
  435. _this._arrayChanged = null;
  436. _this._callingWatchedObjectChanged = false;
  437. _this._watchObjectsPropertyChange = watchObjectsPropertyChange;
  438. _this._watchedObjectList = _this._watchObjectsPropertyChange ? new BABYLON.StringDictionary() : null;
  439. _this._woci = new OAWatchedObjectChangedInfo();
  440. return _this;
  441. }
  442. Object.defineProperty(ObservableArray.prototype, "length", {
  443. /**
  444. * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.
  445. */
  446. get: function () {
  447. return this._array.length;
  448. },
  449. set: function (value) {
  450. if (value === this._array.length) {
  451. return;
  452. }
  453. var oldLength = this._array.length;
  454. this._array.length = value;
  455. this.onPropertyChanged("length", oldLength, this._array.length);
  456. },
  457. enumerable: true,
  458. configurable: true
  459. });
  460. ObservableArray.prototype.getAt = function (index) {
  461. return this._array[index];
  462. };
  463. ObservableArray.prototype.setAt = function (index, value) {
  464. if (index < 0) {
  465. return false;
  466. }
  467. var insertion = (index >= this._array.length) || this._array[index] === undefined;
  468. var oldLength = 0;
  469. if (insertion) {
  470. oldLength = this._array.length;
  471. }
  472. else if (this._watchObjectsPropertyChange) {
  473. this._removeWatchedElement(this._array[index]);
  474. }
  475. this._array[index] = value;
  476. if (this._watchObjectsPropertyChange) {
  477. this._addWatchedElement(value);
  478. }
  479. if (insertion) {
  480. this.onPropertyChanged("length", oldLength, this._array.length);
  481. }
  482. var ac = this.getArrayChangedObject();
  483. if (ac) {
  484. ac.action = insertion ? ArrayChanged.newItemsAction : ArrayChanged.changedItemAction;
  485. if (insertion) {
  486. ac.newItems.splice(0, ac.newItems.length, { index: index, value: value });
  487. ac.newStartingIndex = index;
  488. ac.changedItems.splice(0);
  489. }
  490. else {
  491. ac.newItems.splice(0);
  492. ac.changedStartingIndex = index;
  493. ac.changedItems.splice(0, ac.changedItems.length, { index: index, value: value });
  494. }
  495. ac.removedItems.splice(0);
  496. ac.removedStartingIndex = -1;
  497. this.callArrayChanged(ac);
  498. }
  499. };
  500. /**
  501. * Returns a string representation of an array.
  502. */
  503. ObservableArray.prototype.toString = function () {
  504. return this._array.toString();
  505. };
  506. ObservableArray.prototype.toLocaleString = function () {
  507. return this._array.toLocaleString();
  508. };
  509. /**
  510. * Appends new elements to an array, and returns the new length of the array.
  511. * @param items New elements of the Array.
  512. */
  513. ObservableArray.prototype.push = function () {
  514. var items = [];
  515. for (var _i = 0; _i < arguments.length; _i++) {
  516. items[_i] = arguments[_i];
  517. }
  518. var oldLength = this._array.length;
  519. var n = (_a = this._array).push.apply(_a, items);
  520. if (this._watchObjectsPropertyChange) {
  521. this._addWatchedElement.apply(this, items);
  522. }
  523. this.onPropertyChanged("length", oldLength, this._array.length);
  524. var ac = this.getArrayChangedObject();
  525. if (ac) {
  526. ac.action = ArrayChanged.newItemsAction;
  527. ac.newStartingIndex = oldLength;
  528. this.feedNotifArray.apply(this, [ac.newItems, oldLength].concat(items));
  529. this.callArrayChanged(ac);
  530. }
  531. return n;
  532. var _a;
  533. };
  534. /**
  535. * Removes the last element from an array and returns it.
  536. */
  537. ObservableArray.prototype.pop = function () {
  538. var firstRemove = this._array.length - 1;
  539. var res = this._array.pop();
  540. if (res && this._watchObjectsPropertyChange) {
  541. this._removeWatchedElement(res);
  542. }
  543. if (firstRemove !== -1) {
  544. this.onPropertyChanged("length", this._array.length + 1, this._array.length);
  545. var ac = this.getArrayChangedObject();
  546. if (ac) {
  547. ac.action = ArrayChanged.removedItemsAction;
  548. ac.removedStartingIndex = firstRemove;
  549. this.feedNotifArray(ac.removedItems, firstRemove, res);
  550. }
  551. }
  552. return res;
  553. };
  554. /**
  555. * Combines two or more arrays.
  556. * @param items Additional items to add to the end of array1.
  557. */
  558. ObservableArray.prototype.concat = function () {
  559. var items = [];
  560. for (var _i = 0; _i < arguments.length; _i++) {
  561. items[_i] = arguments[_i];
  562. }
  563. return new ObservableArray(this._watchObjectsPropertyChange, (_a = this._array).concat.apply(_a, items));
  564. var _a;
  565. };
  566. /**
  567. * Adds all the elements of an array separated by the specified separator string.
  568. * @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.
  569. */
  570. ObservableArray.prototype.join = function (separator) {
  571. return this._array.join(separator);
  572. };
  573. /**
  574. * Reverses the elements in an Array.
  575. * The arrayChanged action is
  576. */
  577. ObservableArray.prototype.reverse = function () {
  578. var res = this._array.reverse();
  579. var ac = this.getArrayChangedObject();
  580. ac.action = ArrayChanged.replacedArrayAction;
  581. return res;
  582. };
  583. /**
  584. * Removes the first element from an array and returns it, shift all subsequents element one element before.
  585. * The ArrayChange action is replacedArrayAction, the whole array changes and must be reevaluate as such, the removed element is in removedItems.
  586. *
  587. */
  588. ObservableArray.prototype.shift = function () {
  589. var oldLength = this._array.length;
  590. var res = this._array.shift();
  591. if (this._watchedObjectChanged && res != null) {
  592. this._removeWatchedElement(res);
  593. }
  594. if (oldLength !== 0) {
  595. this.onPropertyChanged("length", oldLength, this._array.length);
  596. var ac = this.getArrayChangedObject();
  597. if (ac) {
  598. ac.action = ArrayChanged.replacedArrayAction;
  599. ac.removedItems.splice(0, ac.removedItems.length, { index: 0, value: res });
  600. ac.newItems.splice(0);
  601. ac.changedItems.splice(0);
  602. ac.removedStartingIndex = 0;
  603. this.callArrayChanged(ac);
  604. }
  605. }
  606. return res;
  607. };
  608. /**
  609. * Returns a section of an array.
  610. * @param start The beginning of the specified portion of the array.
  611. * @param end The end of the specified portion of the array.
  612. */
  613. ObservableArray.prototype.slice = function (start, end) {
  614. return new ObservableArray(this._watchObjectsPropertyChange, this._array.slice(start, end));
  615. };
  616. /**
  617. * Sorts an array.
  618. * @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.
  619. * On the contrary of the Javascript Array's implementation, this method returns nothing
  620. */
  621. ObservableArray.prototype.sort = function (compareFn) {
  622. var oldLength = this._array.length;
  623. this._array.sort(compareFn);
  624. if (oldLength !== 0) {
  625. var ac = this.getArrayChangedObject();
  626. if (ac) {
  627. ac.clear();
  628. ac.action = ArrayChanged.replacedArrayAction;
  629. this.callArrayChanged(ac);
  630. }
  631. }
  632. };
  633. /**
  634. * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
  635. * @param start The zero-based location in the array from which to start removing elements.
  636. * @param deleteCount The number of elements to remove.
  637. * @param items Elements to insert into the array in place of the deleted elements.
  638. */
  639. ObservableArray.prototype.splice = function (start, deleteCount) {
  640. var items = [];
  641. for (var _i = 2; _i < arguments.length; _i++) {
  642. items[_i - 2] = arguments[_i];
  643. }
  644. var oldLength = this._array.length;
  645. if (this._watchObjectsPropertyChange) {
  646. for (var i = start; i < start + deleteCount; i++) {
  647. var val = this._array[i];
  648. if (this._watchObjectsPropertyChange && val != null) {
  649. this._removeWatchedElement(val);
  650. }
  651. }
  652. }
  653. var res = (_a = this._array).splice.apply(_a, [start, deleteCount].concat(items));
  654. if (this._watchObjectsPropertyChange) {
  655. this._addWatchedElement.apply(this, items);
  656. }
  657. if (oldLength !== this._array.length) {
  658. this.onPropertyChanged("length", oldLength, this._array.length);
  659. }
  660. var ac = this.getArrayChangedObject();
  661. if (ac) {
  662. ac.clear();
  663. ac.action = ArrayChanged.replacedArrayAction;
  664. this.callArrayChanged(ac);
  665. }
  666. return res;
  667. var _a;
  668. };
  669. /**
  670. * Inserts new elements at the start of an array.
  671. * @param items Elements to insert at the start of the Array.
  672. * The ChangedArray action is replacedArrayAction, newItems contains the list of the added items
  673. */
  674. ObservableArray.prototype.unshift = function () {
  675. var items = [];
  676. for (var _i = 0; _i < arguments.length; _i++) {
  677. items[_i] = arguments[_i];
  678. }
  679. var oldLength = this._array.length;
  680. var res = (_a = this._array).unshift.apply(_a, items);
  681. if (this._watchObjectsPropertyChange) {
  682. this._addWatchedElement.apply(this, items);
  683. }
  684. this.onPropertyChanged("length", oldLength, this._array.length);
  685. var ac = this.getArrayChangedObject();
  686. if (ac) {
  687. ac.clear();
  688. ac.action = ArrayChanged.replacedArrayAction;
  689. ac.newStartingIndex = 0, this.feedNotifArray.apply(this, [ac.newItems, 0].concat(items));
  690. this.callArrayChanged(ac);
  691. }
  692. return res;
  693. var _a;
  694. };
  695. /**
  696. * Returns the index of the first occurrence of a value in an array.
  697. * @param searchElement The value to locate in the array.
  698. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
  699. */
  700. ObservableArray.prototype.indexOf = function (searchElement, fromIndex) {
  701. return this._array.indexOf(searchElement, fromIndex);
  702. };
  703. /**
  704. * Returns the index of the last occurrence of a specified value in an array.
  705. * @param searchElement The value to locate in the array.
  706. * @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.
  707. */
  708. ObservableArray.prototype.lastIndexOf = function (searchElement, fromIndex) {
  709. return this._array.lastIndexOf(searchElement, fromIndex);
  710. };
  711. /**
  712. * Determines whether all the members of an array satisfy the specified test.
  713. * @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.
  714. * @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.
  715. */
  716. ObservableArray.prototype.every = function (callbackfn, thisArg) {
  717. return this._array.every(callbackfn, thisArg);
  718. };
  719. /**
  720. * Determines whether the specified callback function returns true for any element of an array.
  721. * @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.
  722. * @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.
  723. */
  724. ObservableArray.prototype.some = function (callbackfn, thisArg) {
  725. return this._array.some(callbackfn, thisArg);
  726. };
  727. /**
  728. * Performs the specified action for each element in an array.
  729. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
  730. * @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.
  731. */
  732. ObservableArray.prototype.forEach = function (callbackfn, thisArg) {
  733. return this._array.forEach(callbackfn, thisArg);
  734. };
  735. /**
  736. * Calls a defined callback function on each element of an array, and returns an array that contains the results.
  737. * @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.
  738. * @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.
  739. */
  740. ObservableArray.prototype.map = function (callbackfn, thisArg) {
  741. return this._array.map(callbackfn, thisArg);
  742. };
  743. /**
  744. * Returns the elements of an array that meet the condition specified in a callback function.
  745. * @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.
  746. * @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.
  747. */
  748. ObservableArray.prototype.filter = function (callbackfn, thisArg) {
  749. return this._array.filter(callbackfn, thisArg);
  750. };
  751. /**
  752. * 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.
  753. * @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.
  754. * @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.
  755. */
  756. ObservableArray.prototype.reduce = function (callbackfn, initialValue) {
  757. return this._array.reduce(callbackfn);
  758. };
  759. /**
  760. * 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.
  761. * @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.
  762. * @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.
  763. */
  764. ObservableArray.prototype.reduceRight = function (callbackfn, initialValue) {
  765. return this._array.reduceRight(callbackfn);
  766. };
  767. Object.defineProperty(ObservableArray.prototype, "arrayChanged", {
  768. get: function () {
  769. if (!this._arrayChanged) {
  770. this._arrayChanged = new BABYLON.Observable();
  771. }
  772. return this._arrayChanged;
  773. },
  774. enumerable: true,
  775. configurable: true
  776. });
  777. ObservableArray.prototype.getArrayChangedObject = function () {
  778. if (this._arrayChanged && this._arrayChanged.hasObservers()) {
  779. var ac = this._callingArrayChanged ? new ArrayChanged() : this.dci;
  780. return ac;
  781. }
  782. return null;
  783. };
  784. ObservableArray.prototype.feedNotifArray = function (array, startindIndex) {
  785. var items = [];
  786. for (var _i = 2; _i < arguments.length; _i++) {
  787. items[_i - 2] = arguments[_i];
  788. }
  789. array.splice(0);
  790. for (var i = 0; i < items.length; i++) {
  791. var value = this._array[i + startindIndex];
  792. if (value !== undefined) {
  793. array.push({ index: i + startindIndex, value: value });
  794. }
  795. }
  796. };
  797. ObservableArray.prototype.callArrayChanged = function (ac) {
  798. try {
  799. this._callingArrayChanged = true;
  800. this.arrayChanged.notifyObservers(ac, ac.action);
  801. }
  802. finally {
  803. this._callingArrayChanged = false;
  804. }
  805. };
  806. Object.defineProperty(ObservableArray.prototype, "watchedObjectChanged", {
  807. get: function () {
  808. if (!this._watchedObjectChanged) {
  809. this._watchedObjectChanged = new BABYLON.Observable();
  810. }
  811. return this._watchedObjectChanged;
  812. },
  813. enumerable: true,
  814. configurable: true
  815. });
  816. ObservableArray.prototype._addWatchedElement = function () {
  817. var _this = this;
  818. var items = [];
  819. for (var _i = 0; _i < arguments.length; _i++) {
  820. items[_i] = arguments[_i];
  821. }
  822. var _loop_1 = function (curItem) {
  823. if (curItem["propertyChanged"]) {
  824. var key_1 = curItem["__ObsArrayObjID__"];
  825. // The object may already be part of another ObsArray, so there already be a valid ID
  826. if (!key_1) {
  827. key_1 = BABYLON.Tools.RandomId();
  828. curItem["__ObsArrayObjID__"] = key_1;
  829. }
  830. this_1._watchedObjectList.add(key_1, curItem.propertyChanged.add(function (e, d) {
  831. _this.onWatchedObjectChanged(key_1, curItem, e);
  832. }));
  833. }
  834. };
  835. var this_1 = this;
  836. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  837. var curItem = items_1[_a];
  838. _loop_1(curItem);
  839. }
  840. };
  841. ObservableArray.prototype._removeWatchedElement = function () {
  842. var items = [];
  843. for (var _i = 0; _i < arguments.length; _i++) {
  844. items[_i] = arguments[_i];
  845. }
  846. for (var _a = 0, items_2 = items; _a < items_2.length; _a++) {
  847. var curItem = items_2[_a];
  848. var key = curItem["__ObsArrayObjID__"];
  849. if (key != null) {
  850. var observer = this._watchedObjectList.getAndRemove(key);
  851. curItem.propertyChanged.remove(observer);
  852. }
  853. }
  854. };
  855. ObservableArray.prototype.onWatchedObjectChanged = function (key, object, propChanged) {
  856. if (this._watchedObjectChanged && this._watchedObjectChanged.hasObservers()) {
  857. var woci = this._callingWatchedObjectChanged ? new OAWatchedObjectChangedInfo() : this._woci;
  858. woci.object = object;
  859. woci.propertyChanged = propChanged;
  860. try {
  861. this._callingWatchedObjectChanged = true;
  862. this.watchedObjectChanged.notifyObservers(woci);
  863. }
  864. finally {
  865. this._callingWatchedObjectChanged = false;
  866. }
  867. }
  868. };
  869. return ObservableArray;
  870. }(BABYLON.PropertyChangedBase));
  871. BABYLON.ObservableArray = ObservableArray;
  872. })(BABYLON || (BABYLON = {}));
  873. //# sourceMappingURL=babylon.observableArray.js.map
  874. var __extends = (this && this.__extends) || function (d, b) {
  875. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  876. function __() { this.constructor = d; }
  877. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  878. };
  879. var BABYLON;
  880. (function (BABYLON) {
  881. /**
  882. * Class for the ObservableStringDictionary.onDictionaryChanged observable
  883. */
  884. var DictionaryChanged = (function () {
  885. function DictionaryChanged() {
  886. }
  887. Object.defineProperty(DictionaryChanged, "clearAction", {
  888. /**
  889. * The content of the dictionary was totally cleared
  890. */
  891. get: function () {
  892. return DictionaryChanged._clearAction;
  893. },
  894. enumerable: true,
  895. configurable: true
  896. });
  897. Object.defineProperty(DictionaryChanged, "newItemAction", {
  898. /**
  899. * A new item was added, the newItem field contains the key/value pair
  900. */
  901. get: function () {
  902. return DictionaryChanged._newItemAction;
  903. },
  904. enumerable: true,
  905. configurable: true
  906. });
  907. Object.defineProperty(DictionaryChanged, "removedItemAction", {
  908. /**
  909. * An existing item was removed, the removedKey field contains its key
  910. */
  911. get: function () {
  912. return DictionaryChanged._removedItemAction;
  913. },
  914. enumerable: true,
  915. configurable: true
  916. });
  917. Object.defineProperty(DictionaryChanged, "itemValueChangedAction", {
  918. /**
  919. * An existing item had a value change, the changedItem field contains the key/value
  920. */
  921. get: function () {
  922. return DictionaryChanged._itemValueChangedAction;
  923. },
  924. enumerable: true,
  925. configurable: true
  926. });
  927. Object.defineProperty(DictionaryChanged, "replacedAction", {
  928. /**
  929. * The dictionary's content was reset and replaced by the content of another dictionary.
  930. * DictionaryChanged<T> contains no further information about this action
  931. */
  932. get: function () {
  933. return DictionaryChanged._replacedAction;
  934. },
  935. enumerable: true,
  936. configurable: true
  937. });
  938. return DictionaryChanged;
  939. }());
  940. DictionaryChanged._clearAction = 0x1;
  941. DictionaryChanged._newItemAction = 0x2;
  942. DictionaryChanged._removedItemAction = 0x4;
  943. DictionaryChanged._itemValueChangedAction = 0x8;
  944. DictionaryChanged._replacedAction = 0x10;
  945. BABYLON.DictionaryChanged = DictionaryChanged;
  946. var OSDWatchedObjectChangedInfo = (function () {
  947. function OSDWatchedObjectChangedInfo() {
  948. }
  949. return OSDWatchedObjectChangedInfo;
  950. }());
  951. BABYLON.OSDWatchedObjectChangedInfo = OSDWatchedObjectChangedInfo;
  952. var ObservableStringDictionary = (function (_super) {
  953. __extends(ObservableStringDictionary, _super);
  954. function ObservableStringDictionary(watchObjectsPropertyChange) {
  955. var _this = _super.call(this) || this;
  956. _this._propertyChanged = null;
  957. _this._dictionaryChanged = null;
  958. _this.dci = new DictionaryChanged();
  959. _this._callingDicChanged = false;
  960. _this._watchedObjectChanged = null;
  961. _this._callingWatchedObjectChanged = false;
  962. _this._woci = new OSDWatchedObjectChangedInfo();
  963. _this._watchObjectsPropertyChange = watchObjectsPropertyChange;
  964. _this._watchedObjectList = _this._watchObjectsPropertyChange ? new BABYLON.StringDictionary() : null;
  965. return _this;
  966. }
  967. /**
  968. * This will clear this dictionary and copy the content from the 'source' one.
  969. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  970. * @param source the dictionary to take the content from and copy to this dictionary
  971. */
  972. ObservableStringDictionary.prototype.copyFrom = function (source) {
  973. var _this = this;
  974. var oldCount = this.count;
  975. // Don't rely on this class' implementation for clear/add otherwise tons of notification will be thrown
  976. _super.prototype.clear.call(this);
  977. source.forEach(function (t, v) { return _this._add(t, v, false, _this._watchObjectsPropertyChange); });
  978. this.onDictionaryChanged(DictionaryChanged.replacedAction, null, null, null);
  979. this.onPropertyChanged("count", oldCount, this.count);
  980. };
  981. /**
  982. * Get a value from its key or add it if it doesn't exist.
  983. * This method will ensure you that a given key/data will be present in the dictionary.
  984. * @param key the given key to get the matching value from
  985. * @param factory the factory that will create the value if the key is not present in the dictionary.
  986. * The factory will only be invoked if there's no data for the given key.
  987. * @return the value corresponding to the key.
  988. */
  989. ObservableStringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  990. var _this = this;
  991. var val = _super.prototype.getOrAddWithFactory.call(this, key, function (k) {
  992. var v = factory(key);
  993. _this._add(key, v, true, _this._watchObjectsPropertyChange);
  994. return v;
  995. });
  996. return val;
  997. };
  998. /**
  999. * Add a new key and its corresponding value
  1000. * @param key the key to add
  1001. * @param value the value corresponding to the key
  1002. * @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
  1003. */
  1004. ObservableStringDictionary.prototype.add = function (key, value) {
  1005. return this._add(key, value, true, this._watchObjectsPropertyChange);
  1006. };
  1007. ObservableStringDictionary.prototype.getAndRemove = function (key) {
  1008. var val = _super.prototype.get.call(this, key);
  1009. this._remove(key, true, val);
  1010. return val;
  1011. };
  1012. ObservableStringDictionary.prototype._add = function (key, value, fireNotif, registerWatcher) {
  1013. if (_super.prototype.add.call(this, key, value)) {
  1014. if (fireNotif) {
  1015. this.onDictionaryChanged(DictionaryChanged.newItemAction, { key: key, value: value }, null, null);
  1016. this.onPropertyChanged("count", this.count - 1, this.count);
  1017. }
  1018. if (registerWatcher) {
  1019. this._addWatchedElement(key, value);
  1020. }
  1021. return true;
  1022. }
  1023. return false;
  1024. };
  1025. ObservableStringDictionary.prototype._addWatchedElement = function (key, el) {
  1026. var _this = this;
  1027. if (el["propertyChanged"]) {
  1028. this._watchedObjectList.add(key, el.propertyChanged.add(function (e, d) {
  1029. _this.onWatchedObjectChanged(key, el, e);
  1030. }));
  1031. }
  1032. };
  1033. ObservableStringDictionary.prototype._removeWatchedElement = function (key, el) {
  1034. var observer = this._watchedObjectList.getAndRemove(key);
  1035. if (el["propertyChanged"]) {
  1036. el.propertyChanged.remove(observer);
  1037. }
  1038. };
  1039. ObservableStringDictionary.prototype.set = function (key, value) {
  1040. var oldValue = this.get(key);
  1041. if (this._watchObjectsPropertyChange) {
  1042. this._removeWatchedElement(key, oldValue);
  1043. }
  1044. if (_super.prototype.set.call(this, key, value)) {
  1045. this.onDictionaryChanged(DictionaryChanged.itemValueChangedAction, null, null, { key: key, oldValue: oldValue, newValue: value });
  1046. this._addWatchedElement(key, value);
  1047. return true;
  1048. }
  1049. return false;
  1050. };
  1051. /**
  1052. * Remove a key/value from the dictionary.
  1053. * @param key the key to remove
  1054. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  1055. */
  1056. ObservableStringDictionary.prototype.remove = function (key) {
  1057. return this._remove(key, true);
  1058. };
  1059. ObservableStringDictionary.prototype._remove = function (key, fireNotif, element) {
  1060. if (!element) {
  1061. element = this.get(key);
  1062. }
  1063. if (!element) {
  1064. return false;
  1065. }
  1066. if (_super.prototype.remove.call(this, key) === undefined) {
  1067. return false;
  1068. }
  1069. this.onDictionaryChanged(DictionaryChanged.removedItemAction, null, key, null);
  1070. this.onPropertyChanged("count", this.count + 1, this.count);
  1071. if (this._watchObjectsPropertyChange) {
  1072. this._removeWatchedElement(key, element);
  1073. }
  1074. return true;
  1075. };
  1076. /**
  1077. * Clear the whole content of the dictionary
  1078. */
  1079. ObservableStringDictionary.prototype.clear = function () {
  1080. var _this = this;
  1081. this._watchedObjectList.forEach(function (k, v) {
  1082. var el = _this.get(k);
  1083. _this._removeWatchedElement(k, el);
  1084. });
  1085. this._watchedObjectList.clear();
  1086. var oldCount = this.count;
  1087. _super.prototype.clear.call(this);
  1088. this.onDictionaryChanged(DictionaryChanged.clearAction, null, null, null);
  1089. this.onPropertyChanged("count", oldCount, 0);
  1090. };
  1091. Object.defineProperty(ObservableStringDictionary.prototype, "propertyChanged", {
  1092. get: function () {
  1093. if (!this._propertyChanged) {
  1094. this._propertyChanged = new BABYLON.Observable();
  1095. }
  1096. return this._propertyChanged;
  1097. },
  1098. enumerable: true,
  1099. configurable: true
  1100. });
  1101. ObservableStringDictionary.prototype.onPropertyChanged = function (propName, oldValue, newValue, mask) {
  1102. if (this._propertyChanged && this._propertyChanged.hasObservers()) {
  1103. var pci = ObservableStringDictionary.callingPropChanged ? new BABYLON.PropertyChangedInfo() : ObservableStringDictionary.pci;
  1104. pci.oldValue = oldValue;
  1105. pci.newValue = newValue;
  1106. pci.propertyName = propName;
  1107. try {
  1108. ObservableStringDictionary.callingPropChanged = true;
  1109. this.propertyChanged.notifyObservers(pci, mask);
  1110. }
  1111. finally {
  1112. ObservableStringDictionary.callingPropChanged = false;
  1113. }
  1114. }
  1115. };
  1116. Object.defineProperty(ObservableStringDictionary.prototype, "dictionaryChanged", {
  1117. get: function () {
  1118. if (!this._dictionaryChanged) {
  1119. this._dictionaryChanged = new BABYLON.Observable();
  1120. }
  1121. return this._dictionaryChanged;
  1122. },
  1123. enumerable: true,
  1124. configurable: true
  1125. });
  1126. ObservableStringDictionary.prototype.onDictionaryChanged = function (action, newItem, removedKey, changedItem) {
  1127. if (this._dictionaryChanged && this._dictionaryChanged.hasObservers()) {
  1128. var dci = this._callingDicChanged ? new DictionaryChanged() : this.dci;
  1129. dci.action = action;
  1130. dci.newItem = newItem;
  1131. dci.removedKey = removedKey;
  1132. dci.changedItem = changedItem;
  1133. try {
  1134. this._callingDicChanged = true;
  1135. this.dictionaryChanged.notifyObservers(dci, action);
  1136. }
  1137. finally {
  1138. this._callingDicChanged = false;
  1139. }
  1140. }
  1141. };
  1142. Object.defineProperty(ObservableStringDictionary.prototype, "watchedObjectChanged", {
  1143. get: function () {
  1144. if (!this._watchedObjectChanged) {
  1145. this._watchedObjectChanged = new BABYLON.Observable();
  1146. }
  1147. return this._watchedObjectChanged;
  1148. },
  1149. enumerable: true,
  1150. configurable: true
  1151. });
  1152. ObservableStringDictionary.prototype.onWatchedObjectChanged = function (key, object, propChanged) {
  1153. if (this._watchedObjectChanged && this._watchedObjectChanged.hasObservers()) {
  1154. var woci = this._callingWatchedObjectChanged ? new OSDWatchedObjectChangedInfo() : this._woci;
  1155. woci.key = key;
  1156. woci.object = object;
  1157. woci.propertyChanged = propChanged;
  1158. try {
  1159. this._callingWatchedObjectChanged = true;
  1160. this.watchedObjectChanged.notifyObservers(woci);
  1161. }
  1162. finally {
  1163. this._callingWatchedObjectChanged = false;
  1164. }
  1165. }
  1166. };
  1167. return ObservableStringDictionary;
  1168. }(BABYLON.StringDictionary));
  1169. ObservableStringDictionary.pci = new BABYLON.PropertyChangedInfo();
  1170. ObservableStringDictionary.callingPropChanged = false;
  1171. BABYLON.ObservableStringDictionary = ObservableStringDictionary;
  1172. })(BABYLON || (BABYLON = {}));
  1173. //# sourceMappingURL=babylon.observableStringDictionary.js.map
  1174. var __extends = (this && this.__extends) || function (d, b) {
  1175. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1176. function __() { this.constructor = d; }
  1177. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1178. };
  1179. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  1180. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  1181. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  1182. 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;
  1183. return c > 3 && r && Object.defineProperty(target, key, r), r;
  1184. };
  1185. var BABYLON;
  1186. (function (BABYLON) {
  1187. /**
  1188. * This class given information about a given character.
  1189. */
  1190. var CharInfo = (function () {
  1191. function CharInfo() {
  1192. }
  1193. return CharInfo;
  1194. }());
  1195. BABYLON.CharInfo = CharInfo;
  1196. /**
  1197. * This is an abstract base class to hold a Texture that will contain a FontMap
  1198. */
  1199. var BaseFontTexture = (function (_super) {
  1200. __extends(BaseFontTexture, _super);
  1201. function BaseFontTexture(url, scene, noMipmap, invertY, samplingMode) {
  1202. if (noMipmap === void 0) { noMipmap = false; }
  1203. if (invertY === void 0) { invertY = true; }
  1204. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  1205. var _this = _super.call(this, url, scene, noMipmap, invertY, samplingMode) || this;
  1206. _this._cachedFontId = null;
  1207. _this._charInfos = new BABYLON.StringDictionary();
  1208. return _this;
  1209. }
  1210. Object.defineProperty(BaseFontTexture.prototype, "isSuperSampled", {
  1211. /**
  1212. * Is the Font is using Super Sampling (each font texel is doubled).
  1213. */
  1214. get: function () {
  1215. return this._superSample;
  1216. },
  1217. enumerable: true,
  1218. configurable: true
  1219. });
  1220. Object.defineProperty(BaseFontTexture.prototype, "isSignedDistanceField", {
  1221. /**
  1222. * Is the Font was rendered using the Signed Distance Field algorithm
  1223. * @returns {}
  1224. */
  1225. get: function () {
  1226. return this._signedDistanceField;
  1227. },
  1228. enumerable: true,
  1229. configurable: true
  1230. });
  1231. Object.defineProperty(BaseFontTexture.prototype, "spaceWidth", {
  1232. /**
  1233. * Get the Width (in pixel) of the Space character
  1234. */
  1235. get: function () {
  1236. return this._spaceWidth;
  1237. },
  1238. enumerable: true,
  1239. configurable: true
  1240. });
  1241. Object.defineProperty(BaseFontTexture.prototype, "lineHeight", {
  1242. /**
  1243. * Get the Line height (in pixel)
  1244. */
  1245. get: function () {
  1246. return this._lineHeight;
  1247. },
  1248. enumerable: true,
  1249. configurable: true
  1250. });
  1251. /**
  1252. * Measure the width/height that will take a given text
  1253. * @param text the text to measure
  1254. * @param tabulationSize the size (in space character) of the tabulation character, default value must be 4
  1255. */
  1256. BaseFontTexture.prototype.measureText = function (text, tabulationSize) {
  1257. var maxWidth = 0;
  1258. var curWidth = 0;
  1259. var lineCount = 1;
  1260. var charxpos = 0;
  1261. // Parse each char of the string
  1262. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  1263. var char = text_1[_i];
  1264. // Next line feed?
  1265. if (char === "\n") {
  1266. maxWidth = Math.max(maxWidth, curWidth);
  1267. charxpos = 0;
  1268. curWidth = 0;
  1269. ++lineCount;
  1270. continue;
  1271. }
  1272. // Tabulation ?
  1273. if (char === "\t") {
  1274. var nextPos = charxpos + tabulationSize;
  1275. nextPos = nextPos - (nextPos % tabulationSize);
  1276. curWidth += (nextPos - charxpos) * this.spaceWidth;
  1277. charxpos = nextPos;
  1278. continue;
  1279. }
  1280. if (char < " ") {
  1281. continue;
  1282. }
  1283. var ci = this.getChar(char);
  1284. if (!ci) {
  1285. throw new Error("Character " + char + " is not supported by FontTexture " + this.name);
  1286. }
  1287. curWidth += ci.charWidth;
  1288. ++charxpos;
  1289. }
  1290. maxWidth = Math.max(maxWidth, curWidth);
  1291. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  1292. };
  1293. return BaseFontTexture;
  1294. }(BABYLON.Texture));
  1295. BABYLON.BaseFontTexture = BaseFontTexture;
  1296. var BitmapFontInfo = (function () {
  1297. function BitmapFontInfo() {
  1298. this.kerningDic = new BABYLON.StringDictionary();
  1299. this.charDic = new BABYLON.StringDictionary();
  1300. }
  1301. return BitmapFontInfo;
  1302. }());
  1303. BABYLON.BitmapFontInfo = BitmapFontInfo;
  1304. var BitmapFontTexture = (function (_super) {
  1305. __extends(BitmapFontTexture, _super);
  1306. function BitmapFontTexture(scene, bmFontUrl, textureUrl, noMipmap, invertY, samplingMode, onLoad, onError) {
  1307. if (textureUrl === void 0) { textureUrl = null; }
  1308. if (noMipmap === void 0) { noMipmap = false; }
  1309. if (invertY === void 0) { invertY = true; }
  1310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  1311. if (onLoad === void 0) { onLoad = null; }
  1312. if (onError === void 0) { onError = null; }
  1313. var _this = _super.call(this, null, scene, noMipmap, invertY, samplingMode) || this;
  1314. _this._usedCounter = 1;
  1315. var xhr = new XMLHttpRequest();
  1316. xhr.onreadystatechange = function () {
  1317. if (xhr.readyState === XMLHttpRequest.DONE) {
  1318. if (xhr.status === 200) {
  1319. var ext = bmFontUrl.split('.').pop().split(/\#|\?/)[0];
  1320. var plugins = BitmapFontTexture.plugins.get(ext.toLocaleLowerCase());
  1321. if (!plugins) {
  1322. if (onError) {
  1323. onError("couldn't find a plugin for this file extension", -1);
  1324. }
  1325. return;
  1326. }
  1327. var _loop_1 = function (p) {
  1328. var ret = p.loadFont(xhr.response, scene, invertY);
  1329. if (ret) {
  1330. var bfi = ret.bfi;
  1331. if (textureUrl != null) {
  1332. bfi.textureUrl = textureUrl;
  1333. }
  1334. else {
  1335. var baseUrl = bmFontUrl.substr(0, bmFontUrl.lastIndexOf("/") + 1);
  1336. bfi.textureUrl = baseUrl + bfi.textureFile;
  1337. }
  1338. _this._texture = scene.getEngine().createTexture(bfi.textureUrl, noMipmap, invertY, scene, samplingMode, function () {
  1339. if (ret.bfi && onLoad) {
  1340. onLoad();
  1341. }
  1342. });
  1343. _this._lineHeight = bfi.lineHeight;
  1344. _this._charInfos.copyFrom(bfi.charDic);
  1345. var ci = _this.getChar(" ");
  1346. if (ci) {
  1347. _this._spaceWidth = ci.charWidth;
  1348. }
  1349. else {
  1350. _this._charInfos.first(function (k, v) { return _this._spaceWidth = v.charWidth; });
  1351. }
  1352. if (!ret.bfi && onError) {
  1353. onError(ret.errorMsg, ret.errorCode);
  1354. }
  1355. return { value: void 0 };
  1356. }
  1357. };
  1358. for (var _i = 0, plugins_1 = plugins; _i < plugins_1.length; _i++) {
  1359. var p = plugins_1[_i];
  1360. var state_1 = _loop_1(p);
  1361. if (typeof state_1 === "object")
  1362. return state_1.value;
  1363. }
  1364. if (onError) {
  1365. onError("No plugin to load this BMFont file format", -1);
  1366. }
  1367. }
  1368. else {
  1369. if (onError) {
  1370. onError("Couldn't load file through HTTP Request, HTTP Status " + xhr.status, xhr.status);
  1371. }
  1372. }
  1373. }
  1374. };
  1375. xhr.open("GET", bmFontUrl, true);
  1376. xhr.send();
  1377. return _this;
  1378. }
  1379. BitmapFontTexture.GetCachedFontTexture = function (scene, fontTexture) {
  1380. var dic = scene.getOrAddExternalDataWithFactory("BitmapFontTextureCache", function () { return new BABYLON.StringDictionary(); });
  1381. var ft = dic.get(fontTexture.uid);
  1382. if (ft) {
  1383. ++ft._usedCounter;
  1384. return ft;
  1385. }
  1386. dic.add(fontTexture.uid, fontTexture);
  1387. return ft;
  1388. };
  1389. BitmapFontTexture.ReleaseCachedFontTexture = function (scene, fontTexture) {
  1390. var dic = scene.getExternalData("BitmapFontTextureCache");
  1391. if (!dic) {
  1392. return;
  1393. }
  1394. var font = dic.get(fontTexture.uid);
  1395. if (--font._usedCounter === 0) {
  1396. dic.remove(fontTexture.uid);
  1397. font.dispose();
  1398. }
  1399. };
  1400. Object.defineProperty(BitmapFontTexture.prototype, "isDynamicFontTexture", {
  1401. /**
  1402. * 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()
  1403. */
  1404. get: function () {
  1405. return false;
  1406. },
  1407. enumerable: true,
  1408. configurable: true
  1409. });
  1410. /**
  1411. * This method does nothing for a BitmapFontTexture object as it's a static texture
  1412. */
  1413. BitmapFontTexture.prototype.update = function () {
  1414. };
  1415. /**
  1416. * Retrieve the CharInfo object for a given character
  1417. * @param char the character to retrieve the CharInfo object from (e.g.: "A", "a", etc.)
  1418. */
  1419. BitmapFontTexture.prototype.getChar = function (char) {
  1420. return this._charInfos.get(char);
  1421. };
  1422. /**
  1423. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  1424. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  1425. */
  1426. BitmapFontTexture.prototype.incCachedFontTextureCounter = function () {
  1427. ++this._usedCounter;
  1428. };
  1429. /**
  1430. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  1431. */
  1432. BitmapFontTexture.prototype.decCachedFontTextureCounter = function () {
  1433. var dic = this.getScene().getExternalData("BitmapFontTextureCache");
  1434. if (!dic) {
  1435. return;
  1436. }
  1437. if (--this._usedCounter === 0) {
  1438. dic.remove(this._cachedFontId);
  1439. this.dispose();
  1440. }
  1441. };
  1442. BitmapFontTexture.addLoader = function (fileExtension, plugin) {
  1443. var a = BitmapFontTexture.plugins.getOrAddWithFactory(fileExtension.toLocaleLowerCase(), function () { return new Array(); });
  1444. a.push(plugin);
  1445. };
  1446. return BitmapFontTexture;
  1447. }(BaseFontTexture));
  1448. BitmapFontTexture.plugins = new BABYLON.StringDictionary();
  1449. BABYLON.BitmapFontTexture = BitmapFontTexture;
  1450. /**
  1451. * This class is a special kind of texture which generates on the fly characters of a given css style "fontName".
  1452. * The generated texture will be updated when new characters will be retrieved using the getChar() method, but you have
  1453. * to call the update() method for the texture to fetch these changes, you can harmlessly call update any time you want, if no
  1454. * change were made, nothing will happen.
  1455. * The Font Texture can be rendered in three modes: normal size, super sampled size (x2) or using Signed Distance Field rendering.
  1456. * 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).
  1457. * 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.
  1458. */
  1459. var FontTexture = (function (_super) {
  1460. __extends(FontTexture, _super);
  1461. /**
  1462. * Create a new instance of the FontTexture class
  1463. * @param name the name of the texture
  1464. * @param font the font to use, use the W3C CSS notation
  1465. * @param scene the scene that owns the texture
  1466. * @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
  1467. * @param samplingMode the texture sampling mode
  1468. * @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.
  1469. */
  1470. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
  1471. if (maxCharCount === void 0) { maxCharCount = 200; }
  1472. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  1473. if (superSample === void 0) { superSample = false; }
  1474. if (signedDistanceField === void 0) { signedDistanceField = false; }
  1475. var _this = _super.call(this, null, scene, true, false, samplingMode) || this;
  1476. _this._curCharCount = 0;
  1477. _this._lastUpdateCharCount = -1;
  1478. _this._usedCounter = 1;
  1479. _this.name = name;
  1480. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  1481. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  1482. _this._sdfScale = 8;
  1483. _this._signedDistanceField = signedDistanceField;
  1484. _this._superSample = false;
  1485. // SDF will use supersample no matter what, the resolution is otherwise too poor to produce correct result
  1486. if (superSample || signedDistanceField) {
  1487. var sfont = _this.getSuperSampleFont(font);
  1488. if (sfont) {
  1489. _this._superSample = true;
  1490. font = sfont;
  1491. }
  1492. }
  1493. // First canvas creation to determine the size of the texture to create
  1494. _this._canvas = document.createElement("canvas");
  1495. _this._context = _this._canvas.getContext("2d");
  1496. _this._context.font = font;
  1497. _this._context.fillStyle = "white";
  1498. _this._context.textBaseline = "top";
  1499. var res = _this.getFontHeight(font);
  1500. _this._lineHeightSuper = res.height; //+4;
  1501. _this._lineHeight = _this._superSample ? (Math.ceil(_this._lineHeightSuper / 2)) : _this._lineHeightSuper;
  1502. _this._offset = res.offset - 1;
  1503. _this._xMargin = 1 + Math.ceil(_this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  1504. _this._yMargin = _this._xMargin;
  1505. var maxCharWidth = _this._context.measureText("W").width;
  1506. _this._spaceWidthSuper = _this._context.measureText(" ").width;
  1507. _this._spaceWidth = _this._superSample ? (_this._spaceWidthSuper / 2) : _this._spaceWidthSuper;
  1508. // This is an approximate size, but should always be able to fit at least the maxCharCount
  1509. var totalEstSurface = (_this._lineHeightSuper + _this._yMargin) * (maxCharWidth + _this._xMargin) * maxCharCount;
  1510. var edge = Math.sqrt(totalEstSurface);
  1511. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  1512. // Create the texture that will store the font characters
  1513. _this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  1514. var textureSize = _this.getSize();
  1515. _this.hasAlpha = _this._signedDistanceField === false;
  1516. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  1517. _this._canvas = document.createElement("canvas");
  1518. _this._canvas.width = textureSize.width;
  1519. _this._canvas.height = textureSize.height;
  1520. _this._context = _this._canvas.getContext("2d");
  1521. _this._context.textBaseline = "top";
  1522. _this._context.font = font;
  1523. _this._context.fillStyle = "white";
  1524. _this._context.imageSmoothingEnabled = false;
  1525. _this._context.clearRect(0, 0, textureSize.width, textureSize.height);
  1526. // 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
  1527. // 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)
  1528. // So you can see this context as an intermediate one, because it is.
  1529. if (_this._signedDistanceField) {
  1530. var sdfC = document.createElement("canvas");
  1531. var s = _this._sdfScale;
  1532. sdfC.width = maxCharWidth * s;
  1533. sdfC.height = _this._lineHeightSuper * s;
  1534. var sdfCtx = sdfC.getContext("2d");
  1535. sdfCtx.scale(s, s);
  1536. sdfCtx.textBaseline = "top";
  1537. sdfCtx.font = font;
  1538. sdfCtx.fillStyle = "white";
  1539. sdfCtx.imageSmoothingEnabled = false;
  1540. _this._sdfCanvas = sdfC;
  1541. _this._sdfContext = sdfCtx;
  1542. }
  1543. _this._currentFreePosition = BABYLON.Vector2.Zero();
  1544. // Add the basic ASCII based characters
  1545. for (var i = 0x20; i < 0x7F; i++) {
  1546. var c = String.fromCharCode(i);
  1547. _this.getChar(c);
  1548. }
  1549. _this.update();
  1550. return _this;
  1551. }
  1552. Object.defineProperty(FontTexture.prototype, "isDynamicFontTexture", {
  1553. get: function () {
  1554. return true;
  1555. },
  1556. enumerable: true,
  1557. configurable: true
  1558. });
  1559. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  1560. if (supersample === void 0) { supersample = false; }
  1561. if (signedDistanceField === void 0) { signedDistanceField = false; }
  1562. var dic = scene.getOrAddExternalDataWithFactory("FontTextureCache", function () { return new BABYLON.StringDictionary(); });
  1563. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  1564. var ft = dic.get(lfn);
  1565. if (ft) {
  1566. ++ft._usedCounter;
  1567. return ft;
  1568. }
  1569. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample, signedDistanceField);
  1570. ft._cachedFontId = lfn;
  1571. dic.add(lfn, ft);
  1572. return ft;
  1573. };
  1574. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  1575. if (supersample === void 0) { supersample = false; }
  1576. if (signedDistanceField === void 0) { signedDistanceField = false; }
  1577. var dic = scene.getExternalData("FontTextureCache");
  1578. if (!dic) {
  1579. return;
  1580. }
  1581. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  1582. var font = dic.get(lfn);
  1583. if (--font._usedCounter === 0) {
  1584. dic.remove(lfn);
  1585. font.dispose();
  1586. }
  1587. };
  1588. /**
  1589. * Make sure the given char is present in the font map.
  1590. * @param char the character to get or add
  1591. * @return the CharInfo instance corresponding to the given character
  1592. */
  1593. FontTexture.prototype.getChar = function (char) {
  1594. if (char.length !== 1) {
  1595. return null;
  1596. }
  1597. var info = this._charInfos.get(char);
  1598. if (info) {
  1599. return info;
  1600. }
  1601. info = new CharInfo();
  1602. var measure = this._context.measureText(char);
  1603. var textureSize = this.getSize();
  1604. // we reached the end of the current line?
  1605. var width = Math.round(measure.width);
  1606. if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
  1607. this._currentFreePosition.x = 0;
  1608. this._currentFreePosition.y += this._lineHeightSuper + this._yMargin;
  1609. // No more room?
  1610. if (this._currentFreePosition.y > textureSize.height) {
  1611. return this.getChar("!");
  1612. }
  1613. }
  1614. // 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)
  1615. if (this._signedDistanceField) {
  1616. this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
  1617. this._sdfContext.fillText(char, 0, -this._offset);
  1618. var data = this._sdfContext.getImageData(0, 0, width * this._sdfScale, this._sdfCanvas.height);
  1619. var res = this._computeSDFChar(data);
  1620. this._context.putImageData(res, this._currentFreePosition.x, this._currentFreePosition.y);
  1621. }
  1622. else {
  1623. // Draw the character in the HTML canvas
  1624. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  1625. }
  1626. // Fill the CharInfo object
  1627. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  1628. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  1629. if (this._signedDistanceField) {
  1630. var off = 1 / textureSize.width;
  1631. info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
  1632. info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
  1633. }
  1634. info.charWidth = this._superSample ? (width / 2) : width;
  1635. // Add the info structure
  1636. this._charInfos.add(char, info);
  1637. this._curCharCount++;
  1638. // Set the next position
  1639. this._currentFreePosition.x += width + this._xMargin;
  1640. return info;
  1641. };
  1642. FontTexture.prototype._computeSDFChar = function (source) {
  1643. var scl = this._sdfScale;
  1644. var sw = source.width;
  1645. var sh = source.height;
  1646. var dw = sw / scl;
  1647. var dh = sh / scl;
  1648. var roffx = 0;
  1649. var roffy = 0;
  1650. // We shouldn't look beyond half of the biggest between width and height
  1651. var radius = scl;
  1652. var br = radius - 1;
  1653. var lookupSrc = function (dx, dy, offX, offY, lookVis) {
  1654. var sx = dx * scl;
  1655. var sy = dy * scl;
  1656. // Looking out of the area? return true to make the test going on
  1657. if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
  1658. return true;
  1659. }
  1660. // Get the pixel we want
  1661. var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
  1662. var res = (val > 0) === lookVis;
  1663. if (!res) {
  1664. roffx = offX;
  1665. roffy = offY;
  1666. }
  1667. return res;
  1668. };
  1669. var lookupArea = function (dx, dy, lookVis) {
  1670. // 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
  1671. if (lookupSrc(dx, dy, 0, br, lookVis) &&
  1672. lookupSrc(dx, dy, 0, -br, lookVis) &&
  1673. lookupSrc(dx, dy, -br, 0, lookVis) &&
  1674. lookupSrc(dx, dy, br, 0, lookVis)) {
  1675. return 0;
  1676. }
  1677. for (var i = 1; i <= radius; i++) {
  1678. // Quick test N, S, W, E
  1679. 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)) {
  1680. return i * i; // Squared Distance is simple to compute in this case
  1681. }
  1682. // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
  1683. for (var j = 1; j <= i; j++) {
  1684. if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
  1685. !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
  1686. !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
  1687. !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
  1688. // We found the nearest texel having and opposite state, store the squared length
  1689. var res_1 = (i * i) + (j * j);
  1690. var count = 1;
  1691. // 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
  1692. if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
  1693. res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
  1694. ++count;
  1695. }
  1696. if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
  1697. res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
  1698. ++count;
  1699. }
  1700. if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
  1701. res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
  1702. ++count;
  1703. }
  1704. if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
  1705. res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
  1706. ++count;
  1707. }
  1708. if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
  1709. res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
  1710. ++count;
  1711. }
  1712. if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
  1713. res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
  1714. ++count;
  1715. }
  1716. if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
  1717. res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
  1718. ++count;
  1719. }
  1720. if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
  1721. res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
  1722. ++count;
  1723. }
  1724. // Compute the average based on the accumulated distance
  1725. return res_1 / count;
  1726. }
  1727. }
  1728. }
  1729. return 0;
  1730. };
  1731. var tmp = new Array(dw * dh);
  1732. for (var y = 0; y < dh; y++) {
  1733. for (var x = 0; x < dw; x++) {
  1734. var curState = lookupSrc(x, y, 0, 0, true);
  1735. var d = lookupArea(x, y, curState);
  1736. if (d === 0) {
  1737. d = radius * radius * 2;
  1738. }
  1739. tmp[(y * dw) + x] = curState ? d : -d;
  1740. }
  1741. }
  1742. var res = this._context.createImageData(dw, dh);
  1743. var size = dw * dh;
  1744. for (var j = 0; j < size; j++) {
  1745. var d = tmp[j];
  1746. var sign = (d < 0) ? -1 : 1;
  1747. d = Math.sqrt(Math.abs(d)) * sign;
  1748. d *= 127.5 / radius;
  1749. d += 127.5;
  1750. if (d < 0) {
  1751. d = 0;
  1752. }
  1753. else if (d > 255) {
  1754. d = 255;
  1755. }
  1756. d += 0.5;
  1757. res.data[j * 4 + 0] = d;
  1758. res.data[j * 4 + 1] = d;
  1759. res.data[j * 4 + 2] = d;
  1760. res.data[j * 4 + 3] = 255;
  1761. }
  1762. return res;
  1763. };
  1764. FontTexture.prototype.getSuperSampleFont = function (font) {
  1765. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  1766. 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*$/;
  1767. var res = font.toLocaleLowerCase().match(regex);
  1768. if (res == null) {
  1769. return null;
  1770. }
  1771. var size = parseInt(res[4]);
  1772. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  1773. var newFont = "";
  1774. for (var j = 1; j < res.length; j++) {
  1775. if (res[j] != null) {
  1776. newFont += res[j] + " ";
  1777. }
  1778. }
  1779. return newFont;
  1780. };
  1781. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  1782. FontTexture.prototype.getFontHeight = function (font) {
  1783. var fontDraw = document.createElement("canvas");
  1784. var ctx = fontDraw.getContext('2d');
  1785. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  1786. ctx.textBaseline = 'top';
  1787. ctx.fillStyle = 'white';
  1788. ctx.font = font;
  1789. ctx.fillText('jH|', 0, 0);
  1790. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  1791. var start = -1;
  1792. var end = -1;
  1793. for (var row = 0; row < fontDraw.height; row++) {
  1794. for (var column = 0; column < fontDraw.width; column++) {
  1795. var index = (row * fontDraw.width + column) * 4;
  1796. if (pixels[index] === 0) {
  1797. if (column === fontDraw.width - 1 && start !== -1) {
  1798. end = row;
  1799. row = fontDraw.height;
  1800. break;
  1801. }
  1802. continue;
  1803. }
  1804. else {
  1805. if (start === -1) {
  1806. start = row;
  1807. }
  1808. break;
  1809. }
  1810. }
  1811. }
  1812. return { height: (end - start) + 1, offset: start - 1 };
  1813. };
  1814. Object.defineProperty(FontTexture.prototype, "canRescale", {
  1815. get: function () {
  1816. return false;
  1817. },
  1818. enumerable: true,
  1819. configurable: true
  1820. });
  1821. FontTexture.prototype.getContext = function () {
  1822. return this._context;
  1823. };
  1824. /**
  1825. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  1826. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  1827. */
  1828. FontTexture.prototype.update = function () {
  1829. // Update only if there's new char added since the previous update
  1830. if (this._lastUpdateCharCount < this._curCharCount) {
  1831. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  1832. this._lastUpdateCharCount = this._curCharCount;
  1833. }
  1834. };
  1835. // cloning should be prohibited, there's no point to duplicate this texture at all
  1836. FontTexture.prototype.clone = function () {
  1837. return null;
  1838. };
  1839. /**
  1840. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  1841. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  1842. */
  1843. FontTexture.prototype.incCachedFontTextureCounter = function () {
  1844. ++this._usedCounter;
  1845. };
  1846. /**
  1847. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  1848. */
  1849. FontTexture.prototype.decCachedFontTextureCounter = function () {
  1850. var dic = this.getScene().getExternalData("FontTextureCache");
  1851. if (!dic) {
  1852. return;
  1853. }
  1854. if (--this._usedCounter === 0) {
  1855. dic.remove(this._cachedFontId);
  1856. this.dispose();
  1857. }
  1858. };
  1859. return FontTexture;
  1860. }(BaseFontTexture));
  1861. BABYLON.FontTexture = FontTexture;
  1862. /**
  1863. * Orginial code from cocos2d-js, converted to TypeScript by Nockawa
  1864. * Load the Text version of the BMFont format, no XML or binary supported, just plain old text
  1865. */
  1866. var BMFontLoaderTxt = BMFontLoaderTxt_1 = (function () {
  1867. function BMFontLoaderTxt() {
  1868. }
  1869. BMFontLoaderTxt.prototype._parseStrToObj = function (str) {
  1870. var arr = str.match(BMFontLoaderTxt_1.ITEM_EXP);
  1871. if (!arr) {
  1872. return null;
  1873. }
  1874. var obj = {};
  1875. for (var i = 0, li = arr.length; i < li; i++) {
  1876. var tempStr = arr[i];
  1877. var index = tempStr.indexOf("=");
  1878. var key = tempStr.substring(0, index);
  1879. var value = tempStr.substring(index + 1);
  1880. if (value.match(BMFontLoaderTxt_1.INT_EXP))
  1881. value = parseInt(value);
  1882. else if (value[0] === '"')
  1883. value = value.substring(1, value.length - 1);
  1884. obj[key] = value;
  1885. }
  1886. return obj;
  1887. };
  1888. BMFontLoaderTxt.prototype._buildCharInfo = function (initialLine, obj, textureSize, invertY, chars) {
  1889. var char = null;
  1890. var x = null;
  1891. var y = null;
  1892. var xadv = null;
  1893. var width = null;
  1894. var height = null;
  1895. var ci = new CharInfo();
  1896. for (var key in obj) {
  1897. var value = obj[key];
  1898. switch (key) {
  1899. case "id":
  1900. char = String.fromCharCode(value);
  1901. break;
  1902. case "x":
  1903. x = value;
  1904. break;
  1905. case "y":
  1906. y = value;
  1907. break;
  1908. case "width":
  1909. width = value;
  1910. break;
  1911. case "height":
  1912. height = value;
  1913. break;
  1914. case "xadvance":
  1915. xadv = value;
  1916. break;
  1917. }
  1918. }
  1919. if (x != null && y != null && width != null && height != null && char != null) {
  1920. if (xadv) {
  1921. width = xadv;
  1922. }
  1923. if (invertY) {
  1924. ci.topLeftUV = new BABYLON.Vector2(1 - (x / textureSize.width), 1 - (y / textureSize.height));
  1925. ci.bottomRightUV = new BABYLON.Vector2(1 - ((x + width) / textureSize.width), 1 - ((y + height) / textureSize.height));
  1926. }
  1927. else {
  1928. ci.topLeftUV = new BABYLON.Vector2(x / textureSize.width, y / textureSize.height);
  1929. ci.bottomRightUV = new BABYLON.Vector2((x + width) / textureSize.width, (y + height) / textureSize.height);
  1930. }
  1931. ci.charWidth = width;
  1932. chars.add(char, ci);
  1933. }
  1934. else {
  1935. console.log("Error while parsing line " + initialLine);
  1936. }
  1937. };
  1938. BMFontLoaderTxt.prototype.loadFont = function (fontContent, scene, invertY) {
  1939. var fontStr = fontContent;
  1940. var bfi = new BitmapFontInfo();
  1941. var errorCode = 0;
  1942. var errorMsg = "OK";
  1943. //padding
  1944. var info = fontStr.match(BMFontLoaderTxt_1.INFO_EXP);
  1945. var infoObj = this._parseStrToObj(info[0]);
  1946. if (!infoObj) {
  1947. return null;
  1948. }
  1949. var paddingArr = infoObj["padding"].split(",");
  1950. bfi.padding = new BABYLON.Vector4(parseInt(paddingArr[0]), parseInt(paddingArr[1]), parseInt(paddingArr[2]), parseInt(paddingArr[3]));
  1951. //common
  1952. var commonObj = this._parseStrToObj(fontStr.match(BMFontLoaderTxt_1.COMMON_EXP)[0]);
  1953. bfi.lineHeight = commonObj["lineHeight"];
  1954. bfi.textureSize = new BABYLON.Size(commonObj["scaleW"], commonObj["scaleH"]);
  1955. var maxTextureSize = scene.getEngine()._gl.getParameter(0xd33);
  1956. if (commonObj["scaleW"] > maxTextureSize.width || commonObj["scaleH"] > maxTextureSize.height) {
  1957. errorMsg = "FontMap texture's size is bigger than what WebGL supports";
  1958. errorCode = -1;
  1959. }
  1960. else {
  1961. if (commonObj["pages"] !== 1) {
  1962. errorMsg = "FontMap must contain one page only.";
  1963. errorCode = -1;
  1964. }
  1965. else {
  1966. //page
  1967. var pageObj = this._parseStrToObj(fontStr.match(BMFontLoaderTxt_1.PAGE_EXP)[0]);
  1968. if (pageObj["id"] !== 0) {
  1969. errorMsg = "Only one page of ID 0 is supported";
  1970. errorCode = -1;
  1971. }
  1972. else {
  1973. bfi.textureFile = pageObj["file"];
  1974. //char
  1975. var charLines = fontStr.match(BMFontLoaderTxt_1.CHAR_EXP);
  1976. for (var i = 0, li = charLines.length; i < li; i++) {
  1977. var charObj = this._parseStrToObj(charLines[i]);
  1978. this._buildCharInfo(charLines[i], charObj, bfi.textureSize, invertY, bfi.charDic);
  1979. }
  1980. //kerning
  1981. var kerningLines = fontStr.match(BMFontLoaderTxt_1.KERNING_EXP);
  1982. if (kerningLines) {
  1983. for (var i = 0, li = kerningLines.length; i < li; i++) {
  1984. var kerningObj = this._parseStrToObj(kerningLines[i]);
  1985. bfi.kerningDic.add(((kerningObj["first"] << 16) | (kerningObj["second"] & 0xffff)).toString(), kerningObj["amount"]);
  1986. }
  1987. }
  1988. }
  1989. }
  1990. }
  1991. return { bfi: bfi, errorCode: errorCode, errorMsg: errorMsg };
  1992. };
  1993. return BMFontLoaderTxt;
  1994. }());
  1995. BMFontLoaderTxt.INFO_EXP = /info [^\r\n]*(\r\n|$)/gi;
  1996. BMFontLoaderTxt.COMMON_EXP = /common [^\n]*(\n|$)/gi;
  1997. BMFontLoaderTxt.PAGE_EXP = /page [^\n]*(\n|$)/gi;
  1998. BMFontLoaderTxt.CHAR_EXP = /char [^\n]*(\n|$)/gi;
  1999. BMFontLoaderTxt.KERNING_EXP = /kerning [^\n]*(\n|$)/gi;
  2000. BMFontLoaderTxt.ITEM_EXP = /\w+=[^ \r\n]+/gi;
  2001. BMFontLoaderTxt.INT_EXP = /^[\-]?\d+$/;
  2002. BMFontLoaderTxt = BMFontLoaderTxt_1 = __decorate([
  2003. BitmapFontLoaderPlugin("fnt", new BMFontLoaderTxt_1())
  2004. ], BMFontLoaderTxt);
  2005. ;
  2006. function BitmapFontLoaderPlugin(fileExtension, plugin) {
  2007. return function () {
  2008. BitmapFontTexture.addLoader(fileExtension, plugin);
  2009. };
  2010. }
  2011. BABYLON.BitmapFontLoaderPlugin = BitmapFontLoaderPlugin;
  2012. var BMFontLoaderTxt_1;
  2013. })(BABYLON || (BABYLON = {}));
  2014. //# sourceMappingURL=babylon.fontTexture.js.map
  2015. var BABYLON;
  2016. (function (BABYLON) {
  2017. /**
  2018. * Stores 2D Bounding Information.
  2019. * This class handles a circle area and a bounding rectangle one.
  2020. */
  2021. var BoundingInfo2D = (function () {
  2022. function BoundingInfo2D() {
  2023. this.radius = 0;
  2024. this.center = BABYLON.Vector2.Zero();
  2025. this.extent = BABYLON.Vector2.Zero();
  2026. this._worldAABBDirty = false;
  2027. this._worldAABBDirtyObservable = null;
  2028. this._worldAABB = BABYLON.Vector4.Zero();
  2029. }
  2030. /**
  2031. * Create a BoundingInfo2D object from a given size
  2032. * @param size the size that will be used to set the extend, radius will be computed from it.
  2033. */
  2034. BoundingInfo2D.CreateFromSize = function (size) {
  2035. var r = new BoundingInfo2D();
  2036. BoundingInfo2D.CreateFromSizeToRef(size, r);
  2037. return r;
  2038. };
  2039. /**
  2040. * Create a BoundingInfo2D object from a given radius
  2041. * @param radius the radius to use, the extent will be computed from it.
  2042. */
  2043. BoundingInfo2D.CreateFromRadius = function (radius) {
  2044. var r = new BoundingInfo2D();
  2045. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  2046. return r;
  2047. };
  2048. /**
  2049. * Create a BoundingInfo2D object from a list of points.
  2050. * The resulted object will be the smallest bounding area that includes all the given points.
  2051. * @param points an array of points to compute the bounding object from.
  2052. */
  2053. BoundingInfo2D.CreateFromPoints = function (points) {
  2054. var r = new BoundingInfo2D();
  2055. BoundingInfo2D.CreateFromPointsToRef(points, r);
  2056. return r;
  2057. };
  2058. /**
  2059. * Update a BoundingInfo2D object using the given Size as input
  2060. * @param size the bounding data will be computed from this size.
  2061. * @param b must be a valid/allocated object, it will contain the result of the operation
  2062. */
  2063. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  2064. if (!size) {
  2065. size = BABYLON.Size.Zero();
  2066. }
  2067. b.center.x = +size.width / 2;
  2068. b.center.y = +size.height / 2;
  2069. b.extent.x = b.center.x;
  2070. b.extent.y = b.center.y;
  2071. b.radius = b.extent.length();
  2072. b._worldAABBDirty = true;
  2073. };
  2074. /**
  2075. * Update a BoundingInfo2D object using the given radius as input
  2076. * @param radius the bounding data will be computed from this radius
  2077. * @param b must be a valid/allocated object, it will contain the result of the operation
  2078. */
  2079. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  2080. b.center.x = b.center.y = 0;
  2081. var r = +radius;
  2082. b.extent.x = r;
  2083. b.extent.y = r;
  2084. b.radius = r;
  2085. b._worldAABBDirty = true;
  2086. };
  2087. /**
  2088. * Update a BoundingInfo2D object using the given points array as input
  2089. * @param points the point array to use to update the bounding data
  2090. * @param b must be a valid/allocated object, it will contain the result of the operation
  2091. */
  2092. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  2093. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  2094. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  2095. var p = points_1[_i];
  2096. xmin = Math.min(p.x, xmin);
  2097. xmax = Math.max(p.x, xmax);
  2098. ymin = Math.min(p.y, ymin);
  2099. ymax = Math.max(p.y, ymax);
  2100. }
  2101. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  2102. };
  2103. /**
  2104. * Update a BoundingInfo2D object using the given min/max values as input
  2105. * @param xmin the smallest x coordinate
  2106. * @param xmax the biggest x coordinate
  2107. * @param ymin the smallest y coordinate
  2108. * @param ymax the buggest y coordinate
  2109. * @param b must be a valid/allocated object, it will contain the result of the operation
  2110. */
  2111. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  2112. var w = xmax - xmin;
  2113. var h = ymax - ymin;
  2114. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  2115. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  2116. b.radius = b.extent.length();
  2117. b._worldAABBDirty = true;
  2118. };
  2119. /**
  2120. * Duplicate this instance and return a new one
  2121. * @return the duplicated instance
  2122. */
  2123. BoundingInfo2D.prototype.clone = function () {
  2124. var r = new BoundingInfo2D();
  2125. r.center = this.center.clone();
  2126. r.radius = this.radius;
  2127. r.extent = this.extent.clone();
  2128. return r;
  2129. };
  2130. BoundingInfo2D.prototype.clear = function () {
  2131. this.center.copyFromFloats(0, 0);
  2132. this.radius = 0;
  2133. this.extent.copyFromFloats(0, 0);
  2134. this._worldAABBDirty = true;
  2135. };
  2136. BoundingInfo2D.prototype.copyFrom = function (src) {
  2137. this.center.copyFrom(src.center);
  2138. this.radius = src.radius;
  2139. this.extent.copyFrom(src.extent);
  2140. this._worldAABBDirty = true;
  2141. };
  2142. /**
  2143. * return the max extend of the bounding info
  2144. */
  2145. BoundingInfo2D.prototype.max = function () {
  2146. var r = BABYLON.Vector2.Zero();
  2147. this.maxToRef(r);
  2148. return r;
  2149. };
  2150. /**
  2151. * return the min/max extend of the bounding info.
  2152. * x, y, z, w are left, bottom, right and top
  2153. */
  2154. BoundingInfo2D.prototype.minMax = function () {
  2155. var r = BABYLON.Vector4.Zero();
  2156. this.minMaxToRef(r);
  2157. return r;
  2158. };
  2159. /**
  2160. * Update a vector2 with the max extend of the bounding info
  2161. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  2162. */
  2163. BoundingInfo2D.prototype.maxToRef = function (result) {
  2164. result.x = this.center.x + this.extent.x;
  2165. result.y = this.center.y + this.extent.y;
  2166. };
  2167. /**
  2168. * Update a vector4 with the min/max extend of the bounding info
  2169. * x, y, z, w are left, bottom, right and top
  2170. * @param result must be a valid/allocated vector4 that will contain the result of the operation
  2171. */
  2172. BoundingInfo2D.prototype.minMaxToRef = function (result) {
  2173. result.x = this.center.x - this.extent.x;
  2174. result.y = this.center.y - this.extent.y;
  2175. result.z = this.center.x + this.extent.x;
  2176. result.w = this.center.y + this.extent.y;
  2177. };
  2178. /**
  2179. * Return the size of the boundingInfo rect surface
  2180. */
  2181. BoundingInfo2D.prototype.size = function () {
  2182. var r = BABYLON.Size.Zero();
  2183. this.sizeToRef(r);
  2184. return r;
  2185. };
  2186. /**
  2187. * Stores in the result object the size of the boundingInfo rect surface
  2188. * @param result
  2189. */
  2190. BoundingInfo2D.prototype.sizeToRef = function (result) {
  2191. result.width = this.extent.x * 2;
  2192. result.height = this.extent.y * 2;
  2193. };
  2194. /**
  2195. * Inflate the boundingInfo with the given vector
  2196. * @param offset the extent will be incremented with offset and the radius will be computed again
  2197. */
  2198. BoundingInfo2D.prototype.inflate = function (offset) {
  2199. this.extent.addInPlace(offset);
  2200. this.radius = this.extent.length();
  2201. };
  2202. /**
  2203. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  2204. * @param matrix the transformation matrix to apply
  2205. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  2206. */
  2207. BoundingInfo2D.prototype.transform = function (matrix) {
  2208. var r = new BoundingInfo2D();
  2209. this.transformToRef(matrix, r);
  2210. return r;
  2211. };
  2212. /**
  2213. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  2214. * @param other the second BoundingInfo2D to compute the union with this one
  2215. * @return a new instance containing the result of the union
  2216. */
  2217. BoundingInfo2D.prototype.union = function (other) {
  2218. var r = new BoundingInfo2D();
  2219. this.unionToRef(other, r);
  2220. return r;
  2221. };
  2222. BoundingInfo2D.prototype.worldAABBIntersectionTest = function (other) {
  2223. var a = this.worldAABB;
  2224. var b = other.worldAABB;
  2225. return b.z >= a.x && b.x <= a.z && b.w >= a.y && b.y <= a.w;
  2226. };
  2227. /**
  2228. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  2229. * 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.
  2230. * @param matrix The matrix to use to compute the transformation
  2231. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  2232. */
  2233. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  2234. // Construct a bounding box based on the extent values
  2235. var p = BoundingInfo2D._transform;
  2236. p[0].x = this.center.x + this.extent.x;
  2237. p[0].y = this.center.y + this.extent.y;
  2238. p[1].x = this.center.x + this.extent.x;
  2239. p[1].y = this.center.y - this.extent.y;
  2240. p[2].x = this.center.x - this.extent.x;
  2241. p[2].y = this.center.y - this.extent.y;
  2242. p[3].x = this.center.x - this.extent.x;
  2243. p[3].y = this.center.y + this.extent.y;
  2244. // Transform the four points of the bounding box with the matrix
  2245. for (var i = 0; i < 4; i++) {
  2246. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  2247. }
  2248. BoundingInfo2D.CreateFromPointsToRef(p, result);
  2249. };
  2250. BoundingInfo2D.prototype._updateWorldAABB = function (worldMatrix) {
  2251. // Construct a bounding box based on the extent values
  2252. var p = BoundingInfo2D._transform;
  2253. p[0].x = this.center.x + this.extent.x;
  2254. p[0].y = this.center.y + this.extent.y;
  2255. p[1].x = this.center.x + this.extent.x;
  2256. p[1].y = this.center.y - this.extent.y;
  2257. p[2].x = this.center.x - this.extent.x;
  2258. p[2].y = this.center.y - this.extent.y;
  2259. p[3].x = this.center.x - this.extent.x;
  2260. p[3].y = this.center.y + this.extent.y;
  2261. // Transform the four points of the bounding box with the matrix
  2262. for (var i = 0; i < 4; i++) {
  2263. BABYLON.Vector2.TransformToRef(p[i], worldMatrix, p[i]);
  2264. }
  2265. this._worldAABB.x = Math.min(Math.min(p[0].x, p[1].x), Math.min(p[2].x, p[3].x));
  2266. this._worldAABB.y = Math.min(Math.min(p[0].y, p[1].y), Math.min(p[2].y, p[3].y));
  2267. this._worldAABB.z = Math.max(Math.max(p[0].x, p[1].x), Math.max(p[2].x, p[3].x));
  2268. this._worldAABB.w = Math.max(Math.max(p[0].y, p[1].y), Math.max(p[2].y, p[3].y));
  2269. };
  2270. Object.defineProperty(BoundingInfo2D.prototype, "worldAABBDirtyObservable", {
  2271. get: function () {
  2272. if (!this._worldAABBDirtyObservable) {
  2273. this._worldAABBDirtyObservable = new BABYLON.Observable();
  2274. }
  2275. return this._worldAABBDirtyObservable;
  2276. },
  2277. enumerable: true,
  2278. configurable: true
  2279. });
  2280. Object.defineProperty(BoundingInfo2D.prototype, "isWorldAABBDirty", {
  2281. get: function () {
  2282. return this._worldAABBDirty;
  2283. },
  2284. enumerable: true,
  2285. configurable: true
  2286. });
  2287. BoundingInfo2D.prototype.dirtyWorldAABB = function () {
  2288. if (this._worldAABBDirty) {
  2289. return;
  2290. }
  2291. this._worldAABBDirty = true;
  2292. if (this._worldAABBDirtyObservable && this._worldAABBDirtyObservable.hasObservers()) {
  2293. this._worldAABBDirtyObservable.notifyObservers(this);
  2294. }
  2295. };
  2296. Object.defineProperty(BoundingInfo2D.prototype, "worldAABB", {
  2297. /**
  2298. * Retrieve the world AABB, the Vector4's data is x=xmin, y=ymin, z=xmax, w=ymax
  2299. */
  2300. get: function () {
  2301. if (this._worldAABBDirty) {
  2302. if (!this.worldMatrixAccess) {
  2303. throw new Error("you must set the worldMatrixAccess function first");
  2304. }
  2305. this._updateWorldAABB(this.worldMatrixAccess());
  2306. this._worldAABBDirty = false;
  2307. }
  2308. return this._worldAABB;
  2309. },
  2310. enumerable: true,
  2311. configurable: true
  2312. });
  2313. /**
  2314. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  2315. * 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.
  2316. * @param other the second object used to compute the union
  2317. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  2318. */
  2319. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  2320. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  2321. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  2322. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  2323. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  2324. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  2325. };
  2326. /**
  2327. * Check if the given point is inside the BoundingInfo.
  2328. * The test is first made on the radius, then inside the rectangle described by the extent
  2329. * @param pickPosition the position to test
  2330. * @return true if the point is inside, false otherwise
  2331. */
  2332. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  2333. // is it inside the radius?
  2334. var pickLocal = pickPosition.subtract(this.center);
  2335. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  2336. // is it inside the rectangle?
  2337. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  2338. }
  2339. return false;
  2340. };
  2341. return BoundingInfo2D;
  2342. }());
  2343. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  2344. BABYLON.BoundingInfo2D = BoundingInfo2D;
  2345. })(BABYLON || (BABYLON = {}));
  2346. //# sourceMappingURL=babylon.bounding2d.js.map
  2347. var __extends = (this && this.__extends) || function (d, b) {
  2348. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  2349. function __() { this.constructor = d; }
  2350. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2351. };
  2352. var BABYLON;
  2353. (function (BABYLON) {
  2354. var PrimitiveCollisionManagerBase = (function () {
  2355. function PrimitiveCollisionManagerBase(owner) {
  2356. this._owner = owner;
  2357. }
  2358. return PrimitiveCollisionManagerBase;
  2359. }());
  2360. BABYLON.PrimitiveCollisionManagerBase = PrimitiveCollisionManagerBase;
  2361. var ActorInfo = (function () {
  2362. function ActorInfo(owner, actor, deep) {
  2363. var _this = this;
  2364. this.owner = owner;
  2365. this.prim = actor;
  2366. this.flags = 0;
  2367. this.presentInClusters = new BABYLON.StringDictionary();
  2368. this.intersectWith = new BABYLON.ObservableStringDictionary(false);
  2369. this.setFlags((deep ? ActorInfo.flagDeep : 0) | ActorInfo.flagDirty);
  2370. var bi = (deep ? actor.boundingInfo : actor.levelBoundingInfo);
  2371. // Dirty Actor if its WorldAABB changed
  2372. bi.worldAABBDirtyObservable.add(function (e, d) {
  2373. _this.owner.actorDirty(_this);
  2374. });
  2375. // Dirty Actor if it's getting enabled/disabled
  2376. actor.propertyChanged.add(function (e, d) {
  2377. if (d.mask === -1) {
  2378. return;
  2379. }
  2380. _this.setFlagsValue(ActorInfo.flagEnabled, e.newValue === true);
  2381. _this.owner.actorDirty(_this);
  2382. }, BABYLON.Prim2DBase.isVisibleProperty.flagId);
  2383. }
  2384. ActorInfo.prototype.setFlags = function (flags) {
  2385. this.flags |= flags;
  2386. };
  2387. ActorInfo.prototype.clearFlags = function (flags) {
  2388. this.flags &= ~flags;
  2389. };
  2390. ActorInfo.prototype.isAllFlagsSet = function (flags) {
  2391. return (this.flags & flags) === flags;
  2392. };
  2393. ActorInfo.prototype.isSomeFlagsSet = function (flags) {
  2394. return (this.flags & flags) !== 0;
  2395. };
  2396. ActorInfo.prototype.setFlagsValue = function (flags, value) {
  2397. if (value) {
  2398. this.flags |= flags;
  2399. }
  2400. else {
  2401. this.flags &= ~flags;
  2402. }
  2403. };
  2404. Object.defineProperty(ActorInfo.prototype, "worldAABB", {
  2405. get: function () {
  2406. return (this.isSomeFlagsSet(ActorInfo.flagDeep) ? this.prim.boundingInfo : this.prim.levelBoundingInfo).worldAABB;
  2407. },
  2408. enumerable: true,
  2409. configurable: true
  2410. });
  2411. Object.defineProperty(ActorInfo.prototype, "isEnabled", {
  2412. get: function () {
  2413. return this.isSomeFlagsSet(ActorInfo.flagEnabled);
  2414. },
  2415. enumerable: true,
  2416. configurable: true
  2417. });
  2418. Object.defineProperty(ActorInfo.prototype, "isDeep", {
  2419. get: function () {
  2420. return this.isSomeFlagsSet(ActorInfo.flagDeep);
  2421. },
  2422. enumerable: true,
  2423. configurable: true
  2424. });
  2425. Object.defineProperty(ActorInfo.prototype, "isDirty", {
  2426. get: function () {
  2427. return this.isSomeFlagsSet(ActorInfo.flagDirty);
  2428. },
  2429. enumerable: true,
  2430. configurable: true
  2431. });
  2432. Object.defineProperty(ActorInfo.prototype, "isRemoved", {
  2433. get: function () {
  2434. return this.isSomeFlagsSet(ActorInfo.flagRemoved);
  2435. },
  2436. enumerable: true,
  2437. configurable: true
  2438. });
  2439. return ActorInfo;
  2440. }());
  2441. ActorInfo.flagDeep = 0x0001; // set if the actor boundingInfo must be used instead of the levelBoundingInfo
  2442. ActorInfo.flagEnabled = 0x0002; // set if the actor is enabled and should be considered for intersection tests
  2443. ActorInfo.flagDirty = 0x0004; // set if the actor's AABB is dirty
  2444. ActorInfo.flagRemoved = 0x0008; // set if the actor was removed from the PCM
  2445. BABYLON.ActorInfo = ActorInfo;
  2446. var ClusterInfo = (function () {
  2447. function ClusterInfo() {
  2448. this.actors = new BABYLON.StringDictionary();
  2449. }
  2450. ClusterInfo.prototype.clear = function () {
  2451. this.actors.clear();
  2452. };
  2453. return ClusterInfo;
  2454. }());
  2455. BABYLON.ClusterInfo = ClusterInfo;
  2456. var BasicPrimitiviceCollisionManager = (function (_super) {
  2457. __extends(BasicPrimitiviceCollisionManager, _super);
  2458. function BasicPrimitiviceCollisionManager(owner, enableBorders) {
  2459. var _this = _super.call(this, owner) || this;
  2460. _this._actors = new BABYLON.StringDictionary();
  2461. _this._dirtyActors = new BABYLON.StringDictionary();
  2462. _this._clusters = null;
  2463. _this._maxActorByCluster = 0;
  2464. _this._AABBRenderPrim = null;
  2465. _this._canvasSize = BABYLON.Size.Zero();
  2466. _this._ClusterRenderPrim = null;
  2467. _this._debugTextBackground = null;
  2468. _this._clusterDirty = true;
  2469. _this._clusterSize = new BABYLON.Size(2, 2);
  2470. _this._clusterStep = BABYLON.Vector2.Zero();
  2471. _this._lastClusterResizeCounter = 0;
  2472. _this._freeClusters = new Array();
  2473. _this._enableBorder = enableBorders;
  2474. _this._debugUpdateOpCount = new BABYLON.PerfCounter();
  2475. _this._debugUpdateTime = new BABYLON.PerfCounter();
  2476. _this._intersectedActors = new BABYLON.ObservableStringDictionary(false);
  2477. _this._borderIntersecteddActors = new Array(4);
  2478. for (var j = 0; j < 4; j++) {
  2479. _this._borderIntersecteddActors[j] = new BABYLON.ObservableStringDictionary(false);
  2480. }
  2481. var flagId = BABYLON.Canvas2D.actualSizeProperty.flagId;
  2482. if (!BasicPrimitiviceCollisionManager.WAABBCorners) {
  2483. BasicPrimitiviceCollisionManager.WAABBCorners = new Array(4);
  2484. for (var i = 0; i < 4; i++) {
  2485. BasicPrimitiviceCollisionManager.WAABBCorners[i] = BABYLON.Vector2.Zero();
  2486. }
  2487. BasicPrimitiviceCollisionManager.WAABBCornersCluster = new Array(4);
  2488. for (var i = 0; i < 4; i++) {
  2489. BasicPrimitiviceCollisionManager.WAABBCornersCluster[i] = BABYLON.Vector2.Zero();
  2490. }
  2491. }
  2492. owner.propertyChanged.add(function (e, d) {
  2493. if (d.mask === -1) {
  2494. return;
  2495. }
  2496. _this._clusterDirty = true;
  2497. console.log("canvas size changed");
  2498. }, flagId);
  2499. _this.debugRenderAABB = false;
  2500. _this.debugRenderClusters = false;
  2501. _this.debugStats = false;
  2502. return _this;
  2503. }
  2504. BasicPrimitiviceCollisionManager.prototype.addActor = function (actor, deep) {
  2505. var _this = this;
  2506. return this._actors.getOrAddWithFactory(actor.uid, function () {
  2507. var ai = new ActorInfo(_this, actor, deep);
  2508. _this.actorDirty(ai);
  2509. return ai;
  2510. });
  2511. };
  2512. BasicPrimitiviceCollisionManager.prototype.removeActor = function (actor) {
  2513. var ai = this._actors.getAndRemove(actor.uid);
  2514. ai.setFlags(ActorInfo.flagRemoved);
  2515. this.actorDirty(ai);
  2516. };
  2517. BasicPrimitiviceCollisionManager.prototype.actorDirty = function (actor) {
  2518. actor.setFlags(ActorInfo.flagDirty);
  2519. this._dirtyActors.add(actor.prim.uid, actor);
  2520. };
  2521. BasicPrimitiviceCollisionManager.prototype.update = function () {
  2522. this._canvasSize.copyFrom(this._owner.actualSize);
  2523. // Should we update the WireFrame2D Primitive that displays the WorldAABB ?
  2524. if (this.debugRenderAABB) {
  2525. if (this._dirtyActors.count > 0) {
  2526. this._updateAABBDisplay();
  2527. }
  2528. }
  2529. var cw = this._clusterSize.width;
  2530. var ch = this._clusterSize.height;
  2531. // Check for Cluster resize
  2532. if (((this._clusterSize.width < 16 && this._clusterSize.height < 16 && this._maxActorByCluster >= 10) ||
  2533. (this._clusterSize.width > 2 && this._clusterSize.height > 2 && this._maxActorByCluster <= 7)) &&
  2534. this._lastClusterResizeCounter > 100) {
  2535. if (this._maxActorByCluster >= 10) {
  2536. ++cw;
  2537. ++ch;
  2538. }
  2539. else {
  2540. --cw;
  2541. --ch;
  2542. }
  2543. console.log("Change cluster size to " + cw + ":" + ch + ", max actor " + this._maxActorByCluster);
  2544. this._clusterDirty = true;
  2545. }
  2546. // Should we update the WireFrame2D Primitive that displays the clusters
  2547. if (this.debugRenderClusters && this._clusterDirty) {
  2548. this._updateClusterDisplay(cw, ch);
  2549. }
  2550. var updateStats = this.debugStats && (this._dirtyActors.count > 0 || this._clusterDirty);
  2551. this._debugUpdateTime.beginMonitoring();
  2552. // If the Cluster Size changed: rebuild it and add all actors. Otherwise add only new (dirty) actors
  2553. if (this._clusterDirty) {
  2554. this._initializeCluster(cw, ch);
  2555. this._rebuildAllActors();
  2556. }
  2557. else {
  2558. this._rebuildDirtyActors();
  2559. ++this._lastClusterResizeCounter;
  2560. }
  2561. // Proceed to the collision detection between primitives
  2562. this._collisionDetection();
  2563. this._debugUpdateTime.endMonitoring();
  2564. if (updateStats) {
  2565. this._updateDebugStats();
  2566. }
  2567. // Reset the dirty actor list: everything is processed
  2568. this._dirtyActors.clear();
  2569. };
  2570. Object.defineProperty(BasicPrimitiviceCollisionManager.prototype, "intersectedActors", {
  2571. get: function () {
  2572. return this._intersectedActors;
  2573. },
  2574. enumerable: true,
  2575. configurable: true
  2576. });
  2577. Object.defineProperty(BasicPrimitiviceCollisionManager.prototype, "leftBorderIntersectedActors", {
  2578. get: function () {
  2579. return this._borderIntersecteddActors[0];
  2580. },
  2581. enumerable: true,
  2582. configurable: true
  2583. });
  2584. Object.defineProperty(BasicPrimitiviceCollisionManager.prototype, "bottomBorderIntersectedActors", {
  2585. get: function () {
  2586. return this._borderIntersecteddActors[1];
  2587. },
  2588. enumerable: true,
  2589. configurable: true
  2590. });
  2591. Object.defineProperty(BasicPrimitiviceCollisionManager.prototype, "rightBorderIntersectedActors", {
  2592. get: function () {
  2593. return this._borderIntersecteddActors[2];
  2594. },
  2595. enumerable: true,
  2596. configurable: true
  2597. });
  2598. Object.defineProperty(BasicPrimitiviceCollisionManager.prototype, "topBorderIntersectedActors", {
  2599. get: function () {
  2600. return this._borderIntersecteddActors[3];
  2601. },
  2602. enumerable: true,
  2603. configurable: true
  2604. });
  2605. BasicPrimitiviceCollisionManager.prototype._initializeCluster = function (countW, countH) {
  2606. // Check for free
  2607. if (this._clusters) {
  2608. for (var w = 0; w < this._clusterSize.height; w++) {
  2609. for (var h = 0; h < this._clusterSize.width; h++) {
  2610. this._freeClusterInfo(this._clusters[w][h]);
  2611. }
  2612. }
  2613. }
  2614. // Allocate
  2615. this._clusterSize.copyFromFloats(countW, countH);
  2616. this._clusters = [];
  2617. for (var w = 0; w < this._clusterSize.height; w++) {
  2618. this._clusters[w] = [];
  2619. for (var h = 0; h < this._clusterSize.width; h++) {
  2620. var ci = this._allocClusterInfo();
  2621. this._clusters[w][h] = ci;
  2622. }
  2623. }
  2624. this._clusterStep.copyFromFloats(this._owner.actualWidth / countW, this._owner.actualHeight / countH);
  2625. this._maxActorByCluster = 0;
  2626. this._lastClusterResizeCounter = 0;
  2627. this._clusterDirty = false;
  2628. };
  2629. BasicPrimitiviceCollisionManager.prototype._rebuildAllActors = function () {
  2630. var _this = this;
  2631. this._actors.forEach(function (k, ai) {
  2632. _this._processActor(ai);
  2633. });
  2634. };
  2635. BasicPrimitiviceCollisionManager.prototype._rebuildDirtyActors = function () {
  2636. var _this = this;
  2637. this._dirtyActors.forEach(function (k, ai) {
  2638. _this._processActor(ai);
  2639. });
  2640. };
  2641. BasicPrimitiviceCollisionManager.prototype._processActor = function (actor) {
  2642. var _this = this;
  2643. // Check if the actor is being disabled or removed
  2644. if (!actor.isEnabled || actor.isRemoved) {
  2645. actor.presentInClusters.forEach(function (k, ci) {
  2646. ci.actors.remove(actor.prim.uid);
  2647. });
  2648. actor.presentInClusters.clear();
  2649. return;
  2650. }
  2651. var wab = actor.worldAABB;
  2652. // Build the worldAABB corners
  2653. var wac = BasicPrimitiviceCollisionManager.WAABBCorners;
  2654. wac[0].copyFromFloats(wab.x, wab.y); // Bottom/Left
  2655. wac[1].copyFromFloats(wab.z, wab.y); // Bottom/Right
  2656. wac[2].copyFromFloats(wab.z, wab.w); // Top/Right
  2657. wac[3].copyFromFloats(wab.x, wab.w); // Top/Left
  2658. var cs = this._clusterStep;
  2659. var wacc = BasicPrimitiviceCollisionManager.WAABBCornersCluster;
  2660. for (var i = 0; i < 4; i++) {
  2661. var p = wac[i];
  2662. var cx = (p.x - (p.x % cs.x)) / cs.x;
  2663. var cy = (p.y - (p.y % cs.y)) / cs.y;
  2664. wacc[i].copyFromFloats(Math.floor(cx), Math.floor(cy));
  2665. }
  2666. var opCount = 0;
  2667. var totalClusters = 0;
  2668. var newCI = new Array();
  2669. var sx = Math.max(0, wacc[0].x); // Start Cluster X
  2670. var sy = Math.max(0, wacc[0].y); // Start Cluster Y
  2671. var ex = Math.min(this._clusterSize.width - 1, wacc[2].x); // End Cluster X
  2672. var ey = Math.min(this._clusterSize.height - 1, wacc[2].y); // End Cluster Y
  2673. if (this._enableBorder) {
  2674. if (wac[0].x < 0) {
  2675. this._borderIntersecteddActors[0].add(actor.prim.uid, actor.prim);
  2676. }
  2677. else {
  2678. this._borderIntersecteddActors[0].remove(actor.prim.uid);
  2679. }
  2680. if (wac[0].y < 0) {
  2681. this._borderIntersecteddActors[1].add(actor.prim.uid, actor.prim);
  2682. }
  2683. else {
  2684. this._borderIntersecteddActors[1].remove(actor.prim.uid);
  2685. }
  2686. if (wac[2].x >= this._canvasSize.width) {
  2687. this._borderIntersecteddActors[2].add(actor.prim.uid, actor.prim);
  2688. }
  2689. else {
  2690. this._borderIntersecteddActors[2].remove(actor.prim.uid);
  2691. }
  2692. if (wac[2].y >= this._canvasSize.height) {
  2693. this._borderIntersecteddActors[3].add(actor.prim.uid, actor.prim);
  2694. }
  2695. else {
  2696. this._borderIntersecteddActors[3].remove(actor.prim.uid);
  2697. }
  2698. }
  2699. for (var y = sy; y <= ey; y++) {
  2700. var _loop_1 = function (x) {
  2701. var k = x + ":" + y;
  2702. var cx = x, cy = y;
  2703. var ci = actor.presentInClusters.getOrAddWithFactory(k, function (k) {
  2704. var nci = _this._getCluster(cx, cy);
  2705. nci.actors.add(actor.prim.uid, actor);
  2706. _this._maxActorByCluster = Math.max(_this._maxActorByCluster, nci.actors.count);
  2707. ++opCount;
  2708. ++totalClusters;
  2709. return nci;
  2710. });
  2711. newCI.push(ci);
  2712. };
  2713. for (var x = sx; x <= ex; x++) {
  2714. _loop_1(x);
  2715. }
  2716. }
  2717. // Check if there were no change
  2718. if (opCount === 0 && actor.presentInClusters.count === totalClusters) {
  2719. return;
  2720. }
  2721. // Build the array of the cluster where the actor is no longer in
  2722. var clusterToRemove = new Array();
  2723. actor.presentInClusters.forEach(function (k, ci) {
  2724. if (newCI.indexOf(ci) === -1) {
  2725. clusterToRemove.push(k);
  2726. // remove the primitive from the Cluster Info object
  2727. ci.actors.remove(actor.prim.uid);
  2728. }
  2729. });
  2730. // Remove these clusters from the actor's dictionary
  2731. for (var _i = 0, clusterToRemove_1 = clusterToRemove; _i < clusterToRemove_1.length; _i++) {
  2732. var key = clusterToRemove_1[_i];
  2733. actor.presentInClusters.remove(key);
  2734. }
  2735. };
  2736. // 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.
  2737. // Then for a given Actor that is dirty we evaluate the intersection with all the other actors present in the same Cluster(s)
  2738. // So it's basically O(n²), BUT only inside a Cluster and only for dirty Actors.
  2739. BasicPrimitiviceCollisionManager.prototype._collisionDetection = function () {
  2740. var _this = this;
  2741. var hash = BasicPrimitiviceCollisionManager.CandidatesActors;
  2742. var prev = BasicPrimitiviceCollisionManager.PreviousIntersections;
  2743. var opCount = 0;
  2744. this._dirtyActors.forEach(function (k1, ai1) {
  2745. ++opCount;
  2746. // Build the list of candidates
  2747. hash.clear();
  2748. ai1.presentInClusters.forEach(function (k, ci) {
  2749. ++opCount;
  2750. ci.actors.forEach(function (k, v) { return hash.add(k, v); });
  2751. });
  2752. var wab1 = ai1.worldAABB;
  2753. // Save the previous intersections
  2754. prev.clear();
  2755. prev.copyFrom(ai1.intersectWith);
  2756. ai1.intersectWith.clear();
  2757. // For each candidate
  2758. hash.forEach(function (k2, ai2) {
  2759. ++opCount;
  2760. // Check if we're testing against itself
  2761. if (k1 === k2) {
  2762. return;
  2763. }
  2764. var wab2 = ai2.worldAABB;
  2765. if (wab2.z >= wab1.x && wab2.x <= wab1.z && wab2.w >= wab1.y && wab2.y <= wab1.w) {
  2766. if (ai1.prim.intersectOtherPrim(ai2.prim)) {
  2767. ++opCount;
  2768. ai1.intersectWith.add(k2, ai2);
  2769. if (k1 < k2) {
  2770. _this._intersectedActors.add(k1 + ";" + k2, { a: ai1.prim, b: ai2.prim });
  2771. }
  2772. else {
  2773. _this._intersectedActors.add(k2 + ";" + k1, { a: ai2.prim, b: ai1.prim });
  2774. }
  2775. }
  2776. }
  2777. });
  2778. // Check and remove the associations that no longer exist in the main intersection list
  2779. prev.forEach(function (k, ai) {
  2780. if (!ai1.intersectWith.contains(k)) {
  2781. ++opCount;
  2782. _this._intersectedActors.remove((k < k1 ? k : k1) + ";" + (k < k1 ? k1 : k));
  2783. }
  2784. });
  2785. });
  2786. this._debugUpdateOpCount.fetchNewFrame();
  2787. this._debugUpdateOpCount.addCount(opCount, true);
  2788. };
  2789. BasicPrimitiviceCollisionManager.prototype._getCluster = function (x, y) {
  2790. return this._clusters[x][y];
  2791. };
  2792. BasicPrimitiviceCollisionManager.prototype._updateDebugStats = function () {
  2793. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  2794. var txt = "Primitive Collision Stats\n" +
  2795. (" - PCM Execution Time: " + format(this._debugUpdateTime.lastSecAverage) + "ms\n") +
  2796. (" - Operation Count: " + format(this._debugUpdateOpCount.current) + ", (avg:" + format(this._debugUpdateOpCount.lastSecAverage) + ", t:" + format(this._debugUpdateOpCount.total) + ")\n") +
  2797. (" - Max Actor per Cluster: " + this._maxActorByCluster + "\n") +
  2798. (" - Intersections count: " + this.intersectedActors.count);
  2799. if (!this._debugTextBackground) {
  2800. this._debugTextBackground = new BABYLON.Rectangle2D({
  2801. id: "###DEBUG PMC STATS###", parent: this._owner, marginAlignment: "h: left, v: top", fill: "#C0404080", padding: "top: 10, left: 10, right: 10, bottom: 10", roundRadius: 10, children: [
  2802. new BABYLON.Text2D(txt, { id: "###DEBUG PMC TEXT###", fontName: "12pt Lucida Console" })
  2803. ]
  2804. });
  2805. }
  2806. else {
  2807. var text2d = this._debugTextBackground.children[0];
  2808. text2d.text = txt;
  2809. }
  2810. };
  2811. BasicPrimitiviceCollisionManager.prototype._updateAABBDisplay = function () {
  2812. var g = new BABYLON.WireFrameGroup2D("main", new BABYLON.Color4(0.5, 0.8, 1.0, 1.0));
  2813. var v = BABYLON.Vector2.Zero();
  2814. this._actors.forEach(function (k, ai) {
  2815. if (ai.isEnabled) {
  2816. var ab = ai.worldAABB;
  2817. v.x = ab.x;
  2818. v.y = ab.y;
  2819. g.startLineStrip(v);
  2820. v.x = ab.z;
  2821. g.pushVertex(v);
  2822. v.y = ab.w;
  2823. g.pushVertex(v);
  2824. v.x = ab.x;
  2825. g.pushVertex(v);
  2826. v.y = ab.y;
  2827. g.endLineStrip(v);
  2828. }
  2829. });
  2830. if (!this._AABBRenderPrim) {
  2831. this._AABBRenderPrim = new BABYLON.WireFrame2D([g], { parent: this._owner, alignToPixel: true, id: "###DEBUG PCM AABB###" });
  2832. }
  2833. else {
  2834. this._AABBRenderPrim.wireFrameGroups.set("main", g);
  2835. this._AABBRenderPrim.wireFrameGroupsDirty();
  2836. }
  2837. };
  2838. BasicPrimitiviceCollisionManager.prototype._updateClusterDisplay = function (cw, ch) {
  2839. var g = new BABYLON.WireFrameGroup2D("main", new BABYLON.Color4(0.8, 0.1, 0.5, 1.0));
  2840. var v1 = BABYLON.Vector2.Zero();
  2841. var v2 = BABYLON.Vector2.Zero();
  2842. // Vertical lines
  2843. var step = (this._owner.actualWidth - 1) / cw;
  2844. v1.y = 0;
  2845. v2.y = this._owner.actualHeight;
  2846. for (var x = 0; x <= cw; x++) {
  2847. g.pushVertex(v1);
  2848. g.pushVertex(v2);
  2849. v1.x += step;
  2850. v2.x += step;
  2851. }
  2852. // Horizontal lines
  2853. step = (this._owner.actualHeight - 1) / ch;
  2854. v1.x = v1.y = v2.y = 0;
  2855. v2.x = this._owner.actualWidth;
  2856. for (var y = 0; y <= ch; y++) {
  2857. g.pushVertex(v1);
  2858. g.pushVertex(v2);
  2859. v1.y += step;
  2860. v2.y += step;
  2861. }
  2862. if (!this._ClusterRenderPrim) {
  2863. this._ClusterRenderPrim = new BABYLON.WireFrame2D([g], { parent: this._owner, alignToPixel: true, id: "###DEBUG PCM Clusters###" });
  2864. }
  2865. else {
  2866. this._ClusterRenderPrim.wireFrameGroups.set("main", g);
  2867. this._ClusterRenderPrim.wireFrameGroupsDirty();
  2868. }
  2869. };
  2870. // 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
  2871. // ClusterInfo object and we have two method to allocate/free them. This way we always deal with the same objects.
  2872. // The free array never shrink, always grows...For the better...and the worst!
  2873. BasicPrimitiviceCollisionManager.prototype._allocClusterInfo = function () {
  2874. if (this._freeClusters.length === 0) {
  2875. for (var i = 0; i < 8; i++) {
  2876. this._freeClusters.push(new ClusterInfo());
  2877. }
  2878. }
  2879. return this._freeClusters.pop();
  2880. };
  2881. BasicPrimitiviceCollisionManager.prototype._freeClusterInfo = function (ci) {
  2882. ci.clear();
  2883. this._freeClusters.push(ci);
  2884. };
  2885. return BasicPrimitiviceCollisionManager;
  2886. }(PrimitiveCollisionManagerBase));
  2887. BasicPrimitiviceCollisionManager.WAABBCorners = null;
  2888. BasicPrimitiviceCollisionManager.WAABBCornersCluster = null;
  2889. BasicPrimitiviceCollisionManager.CandidatesActors = new BABYLON.StringDictionary();
  2890. BasicPrimitiviceCollisionManager.PreviousIntersections = new BABYLON.StringDictionary();
  2891. BABYLON.BasicPrimitiviceCollisionManager = BasicPrimitiviceCollisionManager;
  2892. })(BABYLON || (BABYLON = {}));
  2893. //# sourceMappingURL=babylon.primitiveCollisionManager.js.map
  2894. var __extends = (this && this.__extends) || function (d, b) {
  2895. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  2896. function __() { this.constructor = d; }
  2897. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2898. };
  2899. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2900. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  2901. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  2902. 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;
  2903. return c > 3 && r && Object.defineProperty(target, key, r), r;
  2904. };
  2905. var BABYLON;
  2906. (function (BABYLON) {
  2907. var LayoutEngineBase = (function () {
  2908. function LayoutEngineBase() {
  2909. this.layoutDirtyOnPropertyChangedMask = 0;
  2910. }
  2911. LayoutEngineBase.prototype.newChild = function (child, data) {
  2912. };
  2913. LayoutEngineBase.prototype.updateLayout = function (prim) {
  2914. };
  2915. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  2916. get: function () {
  2917. return false;
  2918. },
  2919. enumerable: true,
  2920. configurable: true
  2921. });
  2922. LayoutEngineBase.prototype.isLocked = function () {
  2923. return this._isLocked;
  2924. };
  2925. LayoutEngineBase.prototype.lock = function () {
  2926. if (this._isLocked) {
  2927. return false;
  2928. }
  2929. this._isLocked = true;
  2930. return true;
  2931. };
  2932. return LayoutEngineBase;
  2933. }());
  2934. LayoutEngineBase = __decorate([
  2935. BABYLON.className("LayoutEngineBase", "BABYLON")
  2936. ], LayoutEngineBase);
  2937. BABYLON.LayoutEngineBase = LayoutEngineBase;
  2938. var CanvasLayoutEngine = CanvasLayoutEngine_1 = (function (_super) {
  2939. __extends(CanvasLayoutEngine, _super);
  2940. /**
  2941. * The default Layout Engine, primitive are positioning into a Canvas, using their x/y coordinates.
  2942. * This layout must be used as a Singleton through the CanvasLayoutEngine.Singleton property.
  2943. */
  2944. function CanvasLayoutEngine() {
  2945. return _super.apply(this, arguments) || this;
  2946. }
  2947. // A very simple (no) layout computing...
  2948. // The Canvas and its direct children gets the Canvas' size as Layout Area
  2949. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  2950. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  2951. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  2952. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  2953. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  2954. var child = _a[_i];
  2955. this._doUpdate(child);
  2956. }
  2957. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  2958. }
  2959. };
  2960. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  2961. // Canvas ?
  2962. if (prim instanceof BABYLON.Canvas2D) {
  2963. prim.layoutArea = prim.actualSize; //.multiplyByFloats(prim.scaleX, prim.scaleY);
  2964. }
  2965. else if (prim.parent instanceof BABYLON.Canvas2D) {
  2966. prim.layoutArea = prim.owner.actualSize; //.multiplyByFloats(prim.owner.scaleX, prim.owner.scaleY);
  2967. }
  2968. else {
  2969. prim.layoutArea = prim.parent.contentArea;
  2970. }
  2971. };
  2972. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  2973. get: function () {
  2974. return true;
  2975. },
  2976. enumerable: true,
  2977. configurable: true
  2978. });
  2979. return CanvasLayoutEngine;
  2980. }(LayoutEngineBase));
  2981. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine_1();
  2982. CanvasLayoutEngine = CanvasLayoutEngine_1 = __decorate([
  2983. BABYLON.className("CanvasLayoutEngine", "BABYLON")
  2984. ], CanvasLayoutEngine);
  2985. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  2986. var StackPanelLayoutEngine = StackPanelLayoutEngine_1 = (function (_super) {
  2987. __extends(StackPanelLayoutEngine, _super);
  2988. function StackPanelLayoutEngine() {
  2989. var _this = _super.call(this) || this;
  2990. _this._isHorizontal = true;
  2991. _this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  2992. return _this;
  2993. }
  2994. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  2995. get: function () {
  2996. if (!StackPanelLayoutEngine_1._horizontal) {
  2997. StackPanelLayoutEngine_1._horizontal = new StackPanelLayoutEngine_1();
  2998. StackPanelLayoutEngine_1._horizontal.isHorizontal = true;
  2999. StackPanelLayoutEngine_1._horizontal.lock();
  3000. }
  3001. return StackPanelLayoutEngine_1._horizontal;
  3002. },
  3003. enumerable: true,
  3004. configurable: true
  3005. });
  3006. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  3007. get: function () {
  3008. if (!StackPanelLayoutEngine_1._vertical) {
  3009. StackPanelLayoutEngine_1._vertical = new StackPanelLayoutEngine_1();
  3010. StackPanelLayoutEngine_1._vertical.isHorizontal = false;
  3011. StackPanelLayoutEngine_1._vertical.lock();
  3012. }
  3013. return StackPanelLayoutEngine_1._vertical;
  3014. },
  3015. enumerable: true,
  3016. configurable: true
  3017. });
  3018. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  3019. get: function () {
  3020. return this._isHorizontal;
  3021. },
  3022. set: function (val) {
  3023. if (this.isLocked()) {
  3024. return;
  3025. }
  3026. this._isHorizontal = val;
  3027. },
  3028. enumerable: true,
  3029. configurable: true
  3030. });
  3031. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  3032. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  3033. var x = 0;
  3034. var y = 0;
  3035. var h = this.isHorizontal;
  3036. var max = 0;
  3037. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  3038. var child = _a[_i];
  3039. if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  3040. continue;
  3041. }
  3042. var layoutArea = void 0;
  3043. if (child._hasMargin) {
  3044. child.margin.computeWithAlignment(prim.layoutArea, child.actualSize, child.marginAlignment, StackPanelLayoutEngine_1.dstOffset, StackPanelLayoutEngine_1.dstArea, true);
  3045. layoutArea = StackPanelLayoutEngine_1.dstArea.clone();
  3046. child.layoutArea = layoutArea;
  3047. }
  3048. else {
  3049. layoutArea = child.layoutArea;
  3050. child.margin.computeArea(child.actualSize, layoutArea);
  3051. }
  3052. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  3053. }
  3054. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  3055. var child = _c[_b];
  3056. if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  3057. continue;
  3058. }
  3059. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  3060. var layoutArea = child.layoutArea;
  3061. if (h) {
  3062. x += layoutArea.width;
  3063. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  3064. }
  3065. else {
  3066. y += layoutArea.height;
  3067. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  3068. }
  3069. }
  3070. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  3071. }
  3072. };
  3073. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  3074. get: function () {
  3075. return false;
  3076. },
  3077. enumerable: true,
  3078. configurable: true
  3079. });
  3080. return StackPanelLayoutEngine;
  3081. }(LayoutEngineBase));
  3082. StackPanelLayoutEngine._horizontal = null;
  3083. StackPanelLayoutEngine._vertical = null;
  3084. StackPanelLayoutEngine.dstOffset = BABYLON.Vector4.Zero();
  3085. StackPanelLayoutEngine.dstArea = BABYLON.Size.Zero();
  3086. StackPanelLayoutEngine = StackPanelLayoutEngine_1 = __decorate([
  3087. BABYLON.className("StackPanelLayoutEngine", "BABYLON")
  3088. ], StackPanelLayoutEngine);
  3089. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  3090. var CanvasLayoutEngine_1, StackPanelLayoutEngine_1;
  3091. })(BABYLON || (BABYLON = {}));
  3092. //# sourceMappingURL=babylon.canvas2dLayoutEngine.js.map
  3093. var __extends = (this && this.__extends) || function (d, b) {
  3094. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3095. function __() { this.constructor = d; }
  3096. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3097. };
  3098. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  3099. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3100. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  3101. 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;
  3102. return c > 3 && r && Object.defineProperty(target, key, r), r;
  3103. };
  3104. var BABYLON;
  3105. (function (BABYLON) {
  3106. /**
  3107. * Base class implementing the ILocable interface.
  3108. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  3109. */
  3110. var LockableBase = (function () {
  3111. function LockableBase() {
  3112. }
  3113. LockableBase.prototype.isLocked = function () {
  3114. return this._isLocked;
  3115. };
  3116. LockableBase.prototype.lock = function () {
  3117. if (this._isLocked) {
  3118. return true;
  3119. }
  3120. this.onLock();
  3121. this._isLocked = true;
  3122. return false;
  3123. };
  3124. /**
  3125. * Protected handler that will be called when the instance is about to be locked.
  3126. */
  3127. LockableBase.prototype.onLock = function () {
  3128. };
  3129. return LockableBase;
  3130. }());
  3131. BABYLON.LockableBase = LockableBase;
  3132. var SolidColorBrush2D = (function (_super) {
  3133. __extends(SolidColorBrush2D, _super);
  3134. function SolidColorBrush2D(color, lock) {
  3135. if (lock === void 0) { lock = false; }
  3136. var _this = _super.call(this) || this;
  3137. _this._color = color;
  3138. if (lock) {
  3139. {
  3140. _this.lock();
  3141. }
  3142. }
  3143. return _this;
  3144. }
  3145. /**
  3146. * Return true if the brush is transparent, false if it's totally opaque
  3147. */
  3148. SolidColorBrush2D.prototype.isTransparent = function () {
  3149. return this._color && this._color.a < 1.0;
  3150. };
  3151. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  3152. /**
  3153. * The color used by this instance to render
  3154. * @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.
  3155. */
  3156. get: function () {
  3157. return this._color;
  3158. },
  3159. set: function (value) {
  3160. if (this.isLocked()) {
  3161. return;
  3162. }
  3163. this._color = value;
  3164. },
  3165. enumerable: true,
  3166. configurable: true
  3167. });
  3168. /**
  3169. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  3170. */
  3171. SolidColorBrush2D.prototype.toString = function () {
  3172. return this._color.toHexString();
  3173. };
  3174. return SolidColorBrush2D;
  3175. }(LockableBase));
  3176. SolidColorBrush2D = __decorate([
  3177. BABYLON.className("SolidColorBrush2D", "BABYLON")
  3178. ], SolidColorBrush2D);
  3179. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  3180. var GradientColorBrush2D = (function (_super) {
  3181. __extends(GradientColorBrush2D, _super);
  3182. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  3183. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  3184. if (rotation === void 0) { rotation = 0; }
  3185. if (scale === void 0) { scale = 1; }
  3186. if (lock === void 0) { lock = false; }
  3187. var _this = _super.call(this) || this;
  3188. _this._color1 = color1;
  3189. _this._color2 = color2;
  3190. _this._translation = translation;
  3191. _this._rotation = rotation;
  3192. _this._scale = scale;
  3193. if (lock) {
  3194. _this.lock();
  3195. }
  3196. return _this;
  3197. }
  3198. /**
  3199. * Return true if the brush is transparent, false if it's totally opaque
  3200. */
  3201. GradientColorBrush2D.prototype.isTransparent = function () {
  3202. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  3203. };
  3204. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  3205. /**
  3206. * First color, the blend will start from this color
  3207. */
  3208. get: function () {
  3209. return this._color1;
  3210. },
  3211. set: function (value) {
  3212. if (this.isLocked()) {
  3213. return;
  3214. }
  3215. this._color1 = value;
  3216. },
  3217. enumerable: true,
  3218. configurable: true
  3219. });
  3220. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  3221. /**
  3222. * Second color, the blend will end to this color
  3223. */
  3224. get: function () {
  3225. return this._color2;
  3226. },
  3227. set: function (value) {
  3228. if (this.isLocked()) {
  3229. return;
  3230. }
  3231. this._color2 = value;
  3232. },
  3233. enumerable: true,
  3234. configurable: true
  3235. });
  3236. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  3237. /**
  3238. * Translation vector to apply on the blend
  3239. * Default is [0;0]
  3240. */
  3241. get: function () {
  3242. return this._translation;
  3243. },
  3244. set: function (value) {
  3245. if (this.isLocked()) {
  3246. return;
  3247. }
  3248. this._translation = value;
  3249. },
  3250. enumerable: true,
  3251. configurable: true
  3252. });
  3253. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  3254. /**
  3255. * Rotation in radian to apply to the brush
  3256. * Default direction of the brush is vertical, you can change this using this property.
  3257. * Default is 0.
  3258. */
  3259. get: function () {
  3260. return this._rotation;
  3261. },
  3262. set: function (value) {
  3263. if (this.isLocked()) {
  3264. return;
  3265. }
  3266. this._rotation = value;
  3267. },
  3268. enumerable: true,
  3269. configurable: true
  3270. });
  3271. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  3272. /**
  3273. * Scale factor to apply to the gradient.
  3274. * Default is 1: no scale.
  3275. */
  3276. get: function () {
  3277. return this._scale;
  3278. },
  3279. set: function (value) {
  3280. if (this.isLocked()) {
  3281. return;
  3282. }
  3283. this._scale = value;
  3284. },
  3285. enumerable: true,
  3286. configurable: true
  3287. });
  3288. /**
  3289. * Return a string describing the brush
  3290. */
  3291. GradientColorBrush2D.prototype.toString = function () {
  3292. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  3293. };
  3294. /**
  3295. * Build a unique key string for the given parameters
  3296. */
  3297. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  3298. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  3299. };
  3300. return GradientColorBrush2D;
  3301. }(LockableBase));
  3302. GradientColorBrush2D = __decorate([
  3303. BABYLON.className("GradientColorBrush2D", "BABYLON")
  3304. ], GradientColorBrush2D);
  3305. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  3306. })(BABYLON || (BABYLON = {}));
  3307. //# sourceMappingURL=babylon.brushes2d.js.map
  3308. var __extends = (this && this.__extends) || function (d, b) {
  3309. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3310. function __() { this.constructor = d; }
  3311. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3312. };
  3313. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  3314. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3315. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  3316. 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;
  3317. return c > 3 && r && Object.defineProperty(target, key, r), r;
  3318. };
  3319. var BABYLON;
  3320. (function (BABYLON) {
  3321. var Prim2DClassInfo = (function () {
  3322. function Prim2DClassInfo() {
  3323. }
  3324. return Prim2DClassInfo;
  3325. }());
  3326. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  3327. var Prim2DPropInfo = (function () {
  3328. function Prim2DPropInfo() {
  3329. }
  3330. return Prim2DPropInfo;
  3331. }());
  3332. Prim2DPropInfo.PROPKIND_MODEL = 1;
  3333. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  3334. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  3335. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  3336. var ClassTreeInfo = (function () {
  3337. function ClassTreeInfo(baseClass, type, classContentFactory) {
  3338. this._baseClass = baseClass;
  3339. this._type = type;
  3340. this._subClasses = new Array();
  3341. this._levelContent = new BABYLON.StringDictionary();
  3342. this._classContentFactory = classContentFactory;
  3343. }
  3344. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  3345. get: function () {
  3346. if (!this._classContent) {
  3347. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  3348. }
  3349. return this._classContent;
  3350. },
  3351. enumerable: true,
  3352. configurable: true
  3353. });
  3354. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  3355. get: function () {
  3356. return this._type;
  3357. },
  3358. enumerable: true,
  3359. configurable: true
  3360. });
  3361. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  3362. get: function () {
  3363. return this._levelContent;
  3364. },
  3365. enumerable: true,
  3366. configurable: true
  3367. });
  3368. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  3369. get: function () {
  3370. if (!this._fullContent) {
  3371. var dic_1 = new BABYLON.StringDictionary();
  3372. var curLevel = this;
  3373. while (curLevel) {
  3374. curLevel.levelContent.forEach(function (k, v) { return dic_1.add(k, v); });
  3375. curLevel = curLevel._baseClass;
  3376. }
  3377. this._fullContent = dic_1;
  3378. }
  3379. return this._fullContent;
  3380. },
  3381. enumerable: true,
  3382. configurable: true
  3383. });
  3384. ClassTreeInfo.prototype.getLevelOf = function (type) {
  3385. // Are we already there?
  3386. if (type === this._type) {
  3387. return this;
  3388. }
  3389. var baseProto = Object.getPrototypeOf(type);
  3390. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  3391. if (!curProtoContent) {
  3392. this.getLevelOf(baseProto);
  3393. }
  3394. return this.getOrAddType(baseProto, type);
  3395. };
  3396. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  3397. // Are we at the level corresponding to the baseType?
  3398. // If so, get or add the level we're looking for
  3399. if (baseType === this._type) {
  3400. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  3401. var subType = _a[_i];
  3402. if (subType.type === type) {
  3403. return subType.node;
  3404. }
  3405. }
  3406. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  3407. var info = { type: type, node: node };
  3408. this._subClasses.push(info);
  3409. return info.node;
  3410. }
  3411. // Recurse down to keep looking for the node corresponding to the baseTypeName
  3412. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  3413. var subType = _c[_b];
  3414. var info = subType.node.getOrAddType(baseType, type);
  3415. if (info) {
  3416. return info;
  3417. }
  3418. }
  3419. return null;
  3420. };
  3421. ClassTreeInfo.get = function (type) {
  3422. var dic = type["__classTreeInfo"];
  3423. if (!dic) {
  3424. return null;
  3425. }
  3426. return dic.getLevelOf(type);
  3427. };
  3428. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  3429. var dic = type["__classTreeInfo"];
  3430. if (!dic) {
  3431. dic = new ClassTreeInfo(null, type, classContentFactory);
  3432. type["__classTreeInfo"] = dic;
  3433. }
  3434. return dic;
  3435. };
  3436. return ClassTreeInfo;
  3437. }());
  3438. BABYLON.ClassTreeInfo = ClassTreeInfo;
  3439. var DataBinding = DataBinding_1 = (function () {
  3440. function DataBinding() {
  3441. this._converter = null;
  3442. this._mode = DataBinding_1.MODE_DEFAULT;
  3443. this._uiElementId = null;
  3444. this._dataSource = null;
  3445. this._currentDataSource = null;
  3446. this._propertyPathName = null;
  3447. this._stringFormat = null;
  3448. this._updateSourceTrigger = DataBinding_1.UPDATESOURCETRIGGER_PROPERTYCHANGED;
  3449. this._boundTo = null;
  3450. this._owner = null;
  3451. this._updateCounter = 0;
  3452. }
  3453. Object.defineProperty(DataBinding.prototype, "converter", {
  3454. /**
  3455. * Provide a callback that will convert the value obtained by the Data Binding to the type of the SmartProperty it's bound to.
  3456. * If no value are set, then it's assumed that the sourceValue is of the same type as the SmartProperty's one.
  3457. * 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.
  3458. * @param sourceValue the source object retrieve by the Data Binding mechanism
  3459. * @returns the object of a compatible type with the SmartProperty it's bound to
  3460. */
  3461. get: function () {
  3462. return this._converter;
  3463. },
  3464. set: function (value) {
  3465. if (this._converter === value) {
  3466. return;
  3467. }
  3468. this._converter = value;
  3469. },
  3470. enumerable: true,
  3471. configurable: true
  3472. });
  3473. Object.defineProperty(DataBinding.prototype, "mode", {
  3474. /**
  3475. * 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
  3476. */
  3477. get: function () {
  3478. if (this._mode === DataBinding_1.MODE_DEFAULT) {
  3479. return this._boundTo.bindingMode;
  3480. }
  3481. return this._mode;
  3482. },
  3483. set: function (value) {
  3484. if (this._mode === value) {
  3485. return;
  3486. }
  3487. this._mode = value;
  3488. },
  3489. enumerable: true,
  3490. configurable: true
  3491. });
  3492. Object.defineProperty(DataBinding.prototype, "uiElementId", {
  3493. /**
  3494. * You can override the Data Source object with this member which is the Id of a uiElement existing in the UI Logical tree.
  3495. * If not set and source no set too, then the dataSource property will be used.
  3496. */
  3497. get: function () {
  3498. return this._uiElementId;
  3499. },
  3500. set: function (value) {
  3501. if (this._uiElementId === value) {
  3502. return;
  3503. }
  3504. this._uiElementId = value;
  3505. },
  3506. enumerable: true,
  3507. configurable: true
  3508. });
  3509. Object.defineProperty(DataBinding.prototype, "dataSource", {
  3510. /**
  3511. * You can override the Data Source object with this member which is the source object to use directly.
  3512. * If not set and uiElement no set too, then the dataSource property of the SmartPropertyBase object will be used.
  3513. */
  3514. get: function () {
  3515. return this._dataSource;
  3516. },
  3517. set: function (value) {
  3518. if (this._dataSource === value) {
  3519. return;
  3520. }
  3521. this._dataSource = value;
  3522. },
  3523. enumerable: true,
  3524. configurable: true
  3525. });
  3526. Object.defineProperty(DataBinding.prototype, "propertyPathName", {
  3527. /**
  3528. * The path & name of the property to get from the source object.
  3529. * 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.
  3530. * If nothing is set then the source object will be used.
  3531. * 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.
  3532. * 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.
  3533. */
  3534. get: function () {
  3535. return this._propertyPathName;
  3536. },
  3537. set: function (value) {
  3538. if (this._propertyPathName === value) {
  3539. return;
  3540. }
  3541. if (this._owner) {
  3542. }
  3543. this._propertyPathName = value;
  3544. if (this._owner) {
  3545. }
  3546. },
  3547. enumerable: true,
  3548. configurable: true
  3549. });
  3550. Object.defineProperty(DataBinding.prototype, "stringFormat", {
  3551. /**
  3552. * 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}`
  3553. */
  3554. get: function () {
  3555. return this._stringFormat;
  3556. },
  3557. set: function (value) {
  3558. if (this._stringFormat === value) {
  3559. return;
  3560. }
  3561. this._stringFormat = value;
  3562. },
  3563. enumerable: true,
  3564. configurable: true
  3565. });
  3566. Object.defineProperty(DataBinding.prototype, "updateSourceTrigger", {
  3567. /**
  3568. * 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.
  3569. */
  3570. get: function () {
  3571. return this._updateSourceTrigger;
  3572. },
  3573. set: function (value) {
  3574. if (this._updateSourceTrigger === value) {
  3575. return;
  3576. }
  3577. this._updateSourceTrigger = value;
  3578. },
  3579. enumerable: true,
  3580. configurable: true
  3581. });
  3582. DataBinding.prototype.canUpdateTarget = function (resetUpdateCounter) {
  3583. if (resetUpdateCounter) {
  3584. this._updateCounter = 0;
  3585. }
  3586. var mode = this.mode;
  3587. if (mode === DataBinding_1.MODE_ONETIME) {
  3588. return this._updateCounter === 0;
  3589. }
  3590. if (mode === DataBinding_1.MODE_ONEWAYTOSOURCE) {
  3591. return false;
  3592. }
  3593. return true;
  3594. };
  3595. DataBinding.prototype.updateTarget = function () {
  3596. var value = this._getActualDataSource();
  3597. var properties = this.propertyPathName.split(".");
  3598. for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) {
  3599. var propertyName = properties_1[_i];
  3600. value = value[propertyName];
  3601. }
  3602. this._storeBoundValue(this._owner, value);
  3603. };
  3604. DataBinding.prototype._storeBoundValue = function (watcher, value) {
  3605. if ((++this._updateCounter > 1) && (this.mode === DataBinding_1.MODE_ONETIME)) {
  3606. return;
  3607. }
  3608. var newValue = value;
  3609. if (this._converter) {
  3610. newValue = this._converter(value);
  3611. }
  3612. if (this._stringFormat) {
  3613. newValue = this._stringFormat(newValue);
  3614. }
  3615. watcher[this._boundTo.name] = newValue;
  3616. };
  3617. DataBinding.prototype._getActualDataSource = function () {
  3618. if (this.dataSource) {
  3619. return this.dataSource;
  3620. }
  3621. if (this.uiElementId) {
  3622. // TODO Find UIElement
  3623. return null;
  3624. }
  3625. return this._owner.dataSource;
  3626. };
  3627. DataBinding.prototype._registerDataSource = function (updateTarget) {
  3628. var ds = this._getActualDataSource();
  3629. if (ds === this._currentDataSource) {
  3630. return;
  3631. }
  3632. if (this._currentDataSource) {
  3633. BindingHelper.unregisterDataSource(this._currentDataSource, this, 0);
  3634. }
  3635. if (ds) {
  3636. BindingHelper.registerDataSource(ds, this);
  3637. if (updateTarget && this.canUpdateTarget(true)) {
  3638. this.updateTarget();
  3639. }
  3640. }
  3641. this._currentDataSource = ds;
  3642. };
  3643. DataBinding.prototype._unregisterDataSource = function () {
  3644. var ds = this._getActualDataSource();
  3645. if (ds) {
  3646. BindingHelper.unregisterDataSource(ds, this, 0);
  3647. }
  3648. };
  3649. return DataBinding;
  3650. }());
  3651. /**
  3652. * Use the mode specified in the SmartProperty declaration
  3653. */
  3654. DataBinding.MODE_DEFAULT = 1;
  3655. /**
  3656. * Update the binding target only once when the Smart Property's value is first accessed
  3657. */
  3658. DataBinding.MODE_ONETIME = 2;
  3659. /**
  3660. * Update the smart property when the source changes.
  3661. * The source won't be updated if the smart property value is set.
  3662. */
  3663. DataBinding.MODE_ONEWAY = 3;
  3664. /**
  3665. * Only update the source when the target's data is changing.
  3666. */
  3667. DataBinding.MODE_ONEWAYTOSOURCE = 4;
  3668. /**
  3669. * Update the bind target when the source changes and update the source when the Smart Property value is set.
  3670. */
  3671. DataBinding.MODE_TWOWAY = 5;
  3672. /**
  3673. * Use the Update Source Trigger defined in the SmartProperty declaration
  3674. */
  3675. DataBinding.UPDATESOURCETRIGGER_DEFAULT = 1;
  3676. /**
  3677. * Update the source as soon as the Smart Property has a value change
  3678. */
  3679. DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED = 2;
  3680. /**
  3681. * Update the source when the binding target loses focus
  3682. */
  3683. DataBinding.UPDATESOURCETRIGGER_LOSTFOCUS = 3;
  3684. /**
  3685. * Update the source will be made by explicitly calling the UpdateFromDataSource method
  3686. */
  3687. DataBinding.UPDATESOURCETRIGGER_EXPLICIT = 4;
  3688. DataBinding = DataBinding_1 = __decorate([
  3689. BABYLON.className("DataBinding", "BABYLON")
  3690. ], DataBinding);
  3691. BABYLON.DataBinding = DataBinding;
  3692. var SmartPropertyBase = SmartPropertyBase_1 = (function (_super) {
  3693. __extends(SmartPropertyBase, _super);
  3694. function SmartPropertyBase() {
  3695. var _this = _super.call(this) || this;
  3696. _this._dataSource = null;
  3697. _this._dataSourceObserver = null;
  3698. _this._instanceDirtyFlags = 0;
  3699. _this._isDisposed = false;
  3700. _this._bindings = null;
  3701. _this._hasBinding = 0;
  3702. _this._bindingSourceChanged = 0;
  3703. _this._disposeObservable = null;
  3704. return _this;
  3705. }
  3706. Object.defineProperty(SmartPropertyBase.prototype, "disposeObservable", {
  3707. get: function () {
  3708. if (!this._disposeObservable) {
  3709. this._disposeObservable = new BABYLON.Observable();
  3710. }
  3711. return this._disposeObservable;
  3712. },
  3713. enumerable: true,
  3714. configurable: true
  3715. });
  3716. Object.defineProperty(SmartPropertyBase.prototype, "isDisposed", {
  3717. /**
  3718. * Check if the object is disposed or not.
  3719. * @returns true if the object is dispose, false otherwise.
  3720. */
  3721. get: function () {
  3722. return this._isDisposed;
  3723. },
  3724. enumerable: true,
  3725. configurable: true
  3726. });
  3727. /**
  3728. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  3729. * @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.
  3730. */
  3731. SmartPropertyBase.prototype.dispose = function () {
  3732. if (this.isDisposed) {
  3733. return false;
  3734. }
  3735. if (this._disposeObservable && this._disposeObservable.hasObservers()) {
  3736. this._disposeObservable.notifyObservers(this);
  3737. }
  3738. this._isDisposed = true;
  3739. return true;
  3740. };
  3741. /**
  3742. * Check if a given set of properties are dirty or not.
  3743. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  3744. * @return true if at least one property is dirty, false if none of them are.
  3745. */
  3746. SmartPropertyBase.prototype.checkPropertiesDirty = function (flags) {
  3747. return (this._instanceDirtyFlags & flags) !== 0;
  3748. };
  3749. /**
  3750. * Clear a given set of properties.
  3751. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  3752. * @return the new set of property still marked as dirty
  3753. */
  3754. SmartPropertyBase.prototype.clearPropertiesDirty = function (flags) {
  3755. this._instanceDirtyFlags &= ~flags;
  3756. return this._instanceDirtyFlags;
  3757. };
  3758. SmartPropertyBase.prototype._resetPropertiesDirty = function () {
  3759. this._instanceDirtyFlags = 0;
  3760. };
  3761. /**
  3762. * Add an externally attached data from its key.
  3763. * This method call will fail and return false, if such key already exists.
  3764. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  3765. * @param key the unique key that identifies the data
  3766. * @param data the data object to associate to the key for this Engine instance
  3767. * @return true if no such key were already present and the data was added successfully, false otherwise
  3768. */
  3769. SmartPropertyBase.prototype.addExternalData = function (key, data) {
  3770. if (!this._externalData) {
  3771. this._externalData = new BABYLON.StringDictionary();
  3772. }
  3773. return this._externalData.add(key, data);
  3774. };
  3775. /**
  3776. * Get an externally attached data from its key
  3777. * @param key the unique key that identifies the data
  3778. * @return the associated data, if present (can be null), or undefined if not present
  3779. */
  3780. SmartPropertyBase.prototype.getExternalData = function (key) {
  3781. if (!this._externalData) {
  3782. return null;
  3783. }
  3784. return this._externalData.get(key);
  3785. };
  3786. /**
  3787. * Get an externally attached data from its key, create it using a factory if it's not already present
  3788. * @param key the unique key that identifies the data
  3789. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  3790. * @return the associated data, can be null if the factory returned null.
  3791. */
  3792. SmartPropertyBase.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  3793. if (!this._externalData) {
  3794. this._externalData = new BABYLON.StringDictionary();
  3795. }
  3796. return this._externalData.getOrAddWithFactory(key, factory);
  3797. };
  3798. /**
  3799. * Remove an externally attached data from the Engine instance
  3800. * @param key the unique key that identifies the data
  3801. * @return true if the data was successfully removed, false if it doesn't exist
  3802. */
  3803. SmartPropertyBase.prototype.removeExternalData = function (key) {
  3804. if (!this._externalData) {
  3805. return false;
  3806. }
  3807. return this._externalData.remove(key);
  3808. };
  3809. SmartPropertyBase._hookProperty = function (propId, piStore, kind, settings) {
  3810. return function (target, propName, descriptor) {
  3811. if (!settings) {
  3812. settings = {};
  3813. }
  3814. var propInfo = SmartPropertyBase_1._createPropInfo(target, propName, propId, kind, settings);
  3815. if (piStore) {
  3816. piStore(propInfo);
  3817. }
  3818. var getter = descriptor.get, setter = descriptor.set;
  3819. var typeLevelCompare = (settings.typeLevelCompare !== undefined) ? settings.typeLevelCompare : false;
  3820. // Overload the property setter implementation to add our own logic
  3821. descriptor.set = function (val) {
  3822. if (!setter) {
  3823. throw Error("Property '" + propInfo.name + "' of type '" + BABYLON.Tools.getFullClassName(this) + "' has no setter defined but was invoked as if it had one.");
  3824. }
  3825. // check for disposed first, do nothing
  3826. if (this.isDisposed) {
  3827. return;
  3828. }
  3829. var curVal = getter.call(this);
  3830. if (SmartPropertyBase_1._checkUnchanged(curVal, val)) {
  3831. return;
  3832. }
  3833. // Cast the object we're working one
  3834. var prim = this;
  3835. // Change the value
  3836. setter.call(this, val);
  3837. // Notify change, dirty flags update
  3838. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  3839. };
  3840. };
  3841. };
  3842. SmartPropertyBase._createPropInfo = function (target, propName, propId, kind, settings) {
  3843. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  3844. var node = dic.getLevelOf(target);
  3845. var propInfo = node.levelContent.get(propId.toString());
  3846. if (propInfo) {
  3847. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  3848. }
  3849. // Create, setup and add the PropInfo object to our prop dictionary
  3850. propInfo = new Prim2DPropInfo();
  3851. propInfo.id = propId;
  3852. propInfo.flagId = Math.pow(2, propId);
  3853. propInfo.kind = kind;
  3854. propInfo.name = propName;
  3855. propInfo.bindingMode = (settings.bindingMode !== undefined) ? settings.bindingMode : DataBinding.MODE_TWOWAY;
  3856. propInfo.bindingUpdateSourceTrigger = (settings.bindingUpdateSourceTrigger !== undefined) ? settings.bindingUpdateSourceTrigger : DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED;
  3857. propInfo.dirtyBoundingInfo = (settings.dirtyBoundingInfo !== undefined) ? settings.dirtyBoundingInfo : false;
  3858. propInfo.dirtyParentBoundingInfo = (settings.dirtyParentBoundingBox !== undefined) ? settings.dirtyParentBoundingBox : false;
  3859. propInfo.typeLevelCompare = (settings.typeLevelCompare !== undefined) ? settings.typeLevelCompare : false;
  3860. node.levelContent.add(propName, propInfo);
  3861. return propInfo;
  3862. };
  3863. Object.defineProperty(SmartPropertyBase.prototype, "propDic", {
  3864. /**
  3865. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  3866. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  3867. */
  3868. get: function () {
  3869. if (!this._propInfo) {
  3870. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  3871. if (!cti) {
  3872. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  3873. }
  3874. this._propInfo = cti.fullContent;
  3875. }
  3876. return this._propInfo;
  3877. },
  3878. enumerable: true,
  3879. configurable: true
  3880. });
  3881. SmartPropertyBase._checkUnchanged = function (curValue, newValue) {
  3882. // Nothing to nothing: nothing to do!
  3883. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  3884. return true;
  3885. }
  3886. // Check value unchanged
  3887. if ((curValue != null) && (newValue != null)) {
  3888. if (typeof (curValue.equals) == "function") {
  3889. if (curValue.equals(newValue)) {
  3890. return true;
  3891. }
  3892. }
  3893. else {
  3894. if (curValue === newValue) {
  3895. return true;
  3896. }
  3897. }
  3898. }
  3899. return false;
  3900. };
  3901. SmartPropertyBase.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  3902. // Trigger property changed
  3903. var info = SmartPropertyBase_1.propChangeGuarding ? new BABYLON.PropertyChangedInfo() : SmartPropertyPrim.propChangedInfo;
  3904. info.oldValue = curValue;
  3905. info.newValue = newValue;
  3906. info.propertyName = propName;
  3907. var propMask = propInfo ? propInfo.flagId : -1;
  3908. try {
  3909. SmartPropertyBase_1.propChangeGuarding = true;
  3910. this.propertyChanged.notifyObservers(info, propMask);
  3911. }
  3912. finally {
  3913. SmartPropertyBase_1.propChangeGuarding = false;
  3914. }
  3915. };
  3916. SmartPropertyBase.prototype._triggerPropertyChanged = function (propInfo, newValue) {
  3917. if (this.isDisposed) {
  3918. return;
  3919. }
  3920. if (!propInfo) {
  3921. return;
  3922. }
  3923. this._handlePropChanged(undefined, newValue, propInfo.name, propInfo, propInfo.typeLevelCompare);
  3924. };
  3925. Object.defineProperty(SmartPropertyBase.prototype, "dataSource", {
  3926. /**
  3927. * Set the object from which Smart Properties using Binding will take/update their data from/to.
  3928. * 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.
  3929. */
  3930. get: function () {
  3931. // Don't access to _dataSource directly but via a call to the _getDataSource method which can be overloaded in inherited classes
  3932. return this._getDataSource();
  3933. },
  3934. set: function (value) {
  3935. if (this._dataSource === value) {
  3936. return;
  3937. }
  3938. var oldValue = this._dataSource;
  3939. this._dataSource = value;
  3940. if (this._bindings && value != null) {
  3941. // Register the bindings
  3942. for (var _i = 0, _a = this._bindings; _i < _a.length; _i++) {
  3943. var binding = _a[_i];
  3944. if (binding != null) {
  3945. binding._registerDataSource(true);
  3946. }
  3947. }
  3948. }
  3949. this.onPropertyChanged("dataSource", oldValue, value);
  3950. },
  3951. enumerable: true,
  3952. configurable: true
  3953. });
  3954. // Inheriting classes can overload this method to provides additional logic for dataSource access
  3955. SmartPropertyBase.prototype._getDataSource = function () {
  3956. return this._dataSource;
  3957. };
  3958. SmartPropertyBase.prototype.createSimpleDataBinding = function (propInfo, propertyPathName, mode) {
  3959. if (mode === void 0) { mode = DataBinding.MODE_DEFAULT; }
  3960. var binding = new DataBinding();
  3961. binding.propertyPathName = propertyPathName;
  3962. binding.mode = mode;
  3963. return this.createDataBinding(propInfo, binding);
  3964. };
  3965. SmartPropertyBase.prototype.createDataBinding = function (propInfo, binding) {
  3966. if (!this._bindings) {
  3967. this._bindings = new Array();
  3968. }
  3969. if (!binding || binding._owner != null) {
  3970. throw Error("A valid/unused Binding must be passed.");
  3971. }
  3972. // Unregister a potentially existing binding for this property
  3973. this.removeDataBinding(propInfo);
  3974. // register the binding
  3975. binding._owner = this;
  3976. binding._boundTo = propInfo;
  3977. this._bindings[propInfo.id] = binding;
  3978. this._hasBinding |= propInfo.flagId;
  3979. binding._registerDataSource(true);
  3980. return binding;
  3981. };
  3982. SmartPropertyBase.prototype.removeDataBinding = function (propInfo) {
  3983. if ((this._hasBinding & propInfo.flagId) === 0) {
  3984. return false;
  3985. }
  3986. var curBinding = this._bindings[propInfo.id];
  3987. curBinding._unregisterDataSource();
  3988. this._bindings[propInfo.id] = null;
  3989. this._hasBinding &= ~propInfo.flagId;
  3990. return true;
  3991. };
  3992. SmartPropertyBase.prototype.updateFromDataSource = function () {
  3993. for (var _i = 0, _a = this._bindings; _i < _a.length; _i++) {
  3994. var binding = _a[_i];
  3995. if (binding) {
  3996. }
  3997. }
  3998. };
  3999. return SmartPropertyBase;
  4000. }(BABYLON.PropertyChangedBase));
  4001. SmartPropertyBase.propChangedInfo = new BABYLON.PropertyChangedInfo();
  4002. SmartPropertyBase.propChangeGuarding = false;
  4003. SmartPropertyBase = SmartPropertyBase_1 = __decorate([
  4004. BABYLON.className("SmartPropertyBase", "BABYLON")
  4005. ], SmartPropertyBase);
  4006. BABYLON.SmartPropertyBase = SmartPropertyBase;
  4007. var BindingInfo = (function () {
  4008. function BindingInfo(binding, level, isLast) {
  4009. this.binding = binding;
  4010. this.level = level;
  4011. this.isLast = isLast;
  4012. }
  4013. return BindingInfo;
  4014. }());
  4015. var MonitoredObjectData = (function () {
  4016. function MonitoredObjectData(monitoredObject) {
  4017. var _this = this;
  4018. this.monitoredObject = monitoredObject;
  4019. this.monitoredIntermediateProperties = new BABYLON.StringDictionary();
  4020. this.observer = this.monitoredObject.propertyChanged.add(function (e, s) { _this.propertyChangedHandler(e.propertyName, e.oldValue, e.newValue); });
  4021. this.boundProperties = new BABYLON.StringDictionary();
  4022. this.monitoredIntermediateMask = 0;
  4023. this.boundPropertiesMask = 0;
  4024. }
  4025. MonitoredObjectData.prototype.propertyChangedHandler = function (propName, oldValue, newValue) {
  4026. var propId = BindingHelper._getPropertyID(this.monitoredObject, propName);
  4027. var propIdStr = propId.toString();
  4028. // Loop through all the registered bindings for this property that had a value change
  4029. if ((this.boundPropertiesMask & propId) !== 0) {
  4030. var bindingInfos = this.boundProperties.get(propIdStr);
  4031. for (var _i = 0, bindingInfos_1 = bindingInfos; _i < bindingInfos_1.length; _i++) {
  4032. var bi = bindingInfos_1[_i];
  4033. if (!bi.isLast) {
  4034. BindingHelper.unregisterDataSource(this.monitoredObject, bi.binding, bi.level);
  4035. BindingHelper.registerDataSource(bi.binding._currentDataSource, bi.binding);
  4036. }
  4037. if (bi.binding.canUpdateTarget(false)) {
  4038. bi.binding.updateTarget();
  4039. }
  4040. }
  4041. }
  4042. };
  4043. return MonitoredObjectData;
  4044. }());
  4045. var BindingHelper = (function () {
  4046. function BindingHelper() {
  4047. }
  4048. BindingHelper.registerDataSource = function (dataSource, binding) {
  4049. var properties = binding.propertyPathName.split(".");
  4050. var ownerMod = null;
  4051. var ownerInterPropId = 0;
  4052. var propertyOwner = dataSource;
  4053. var _loop_1 = function (i) {
  4054. var propName = properties[i];
  4055. var propId = BindingHelper._getPropertyID(propertyOwner, propName);
  4056. var propIdStr = propId.toString();
  4057. var mod = void 0;
  4058. if (ownerMod) {
  4059. var o_1 = ownerMod;
  4060. var po_1 = propertyOwner;
  4061. var oii_1 = ownerInterPropId;
  4062. mod = ownerMod.monitoredIntermediateProperties.getOrAddWithFactory(oii_1.toString(), function (k) {
  4063. o_1.monitoredIntermediateMask |= oii_1;
  4064. return BindingHelper._getMonitoredObjectData(po_1);
  4065. });
  4066. }
  4067. else {
  4068. mod = BindingHelper._getMonitoredObjectData(propertyOwner);
  4069. }
  4070. var m = mod;
  4071. var bindingInfos = mod.boundProperties.getOrAddWithFactory(propIdStr, function (k) {
  4072. m.boundPropertiesMask |= propId;
  4073. return new Array();
  4074. });
  4075. var bi = BABYLON.Tools.first(bindingInfos, function (cbi) { return cbi.binding === binding; });
  4076. if (!bi) {
  4077. bindingInfos.push(new BindingInfo(binding, i, (i + 1) === properties.length));
  4078. }
  4079. ownerMod = mod;
  4080. ownerInterPropId = propId;
  4081. propertyOwner = propertyOwner[propName];
  4082. };
  4083. for (var i = 0; i < properties.length; i++) {
  4084. _loop_1(i);
  4085. }
  4086. };
  4087. BindingHelper.unregisterDataSource = function (dataSource, binding, level) {
  4088. var properties = binding.propertyPathName.split(".");
  4089. var propertyOwner = dataSource;
  4090. var mod = BindingHelper._getMonitoredObjectData(propertyOwner);
  4091. for (var i = 0; i < properties.length; i++) {
  4092. var propName = properties[i];
  4093. var propId = BindingHelper._getPropertyID(propertyOwner, propName);
  4094. var propIdStr = propId.toString();
  4095. if (i >= level) {
  4096. mod = BindingHelper._unregisterBinding(mod, propId, binding);
  4097. }
  4098. else {
  4099. mod = mod.monitoredIntermediateProperties.get(propIdStr);
  4100. }
  4101. propertyOwner = propertyOwner[propName];
  4102. }
  4103. };
  4104. BindingHelper._unregisterBinding = function (mod, propertyID, binding) {
  4105. var propertyIDStr = propertyID.toString();
  4106. var res = null;
  4107. // Check if the property is registered as an intermediate and remove it
  4108. if ((mod.monitoredIntermediateMask & propertyID) !== 0) {
  4109. res = mod.monitoredIntermediateProperties.get(propertyIDStr);
  4110. mod.monitoredIntermediateProperties.remove(propertyIDStr);
  4111. // Update the mask
  4112. mod.monitoredIntermediateMask &= ~propertyID;
  4113. }
  4114. // Check if the property is registered as a final property and remove it
  4115. if ((mod.boundPropertiesMask & propertyID) !== 0) {
  4116. var bindingInfos = mod.boundProperties.get(propertyIDStr);
  4117. // Find the binding and remove it
  4118. var bi = BABYLON.Tools.first(bindingInfos, function (cbi) { return cbi.binding === binding; });
  4119. if (bi) {
  4120. var bii = bindingInfos.indexOf(bi);
  4121. bindingInfos.splice(bii, 1);
  4122. }
  4123. // If the array is empty, update the mask
  4124. if (bindingInfos.length === 0) {
  4125. mod.boundPropertiesMask &= ~propertyID;
  4126. }
  4127. }
  4128. // Check if the MOD is empty and unregister the observer and remove it from the list of MODs
  4129. if (mod.boundPropertiesMask === 0 && mod.monitoredIntermediateMask === 0) {
  4130. // Unregister the observer on Property Change
  4131. mod.monitoredObject.propertyChanged.remove(mod.observer);
  4132. // Remove the MOD from the dic
  4133. var objectId = BindingHelper._getObjectId(mod.monitoredObject);
  4134. BindingHelper._monitoredObjects.remove(objectId);
  4135. }
  4136. return res;
  4137. };
  4138. BindingHelper._getMonitoredObjectData = function (object) {
  4139. var objectId = BindingHelper._getObjectId(object);
  4140. var mod = BindingHelper._monitoredObjects.getOrAddWithFactory(objectId, function (k) { return new MonitoredObjectData(object); });
  4141. return mod;
  4142. };
  4143. BindingHelper._getObjectId = function (obj) {
  4144. var id = obj["__bindingHelperObjectId__"];
  4145. if (id == null) {
  4146. id = BABYLON.Tools.RandomId();
  4147. obj["__bindingHelperObjectId__"] = id;
  4148. return id;
  4149. }
  4150. return id;
  4151. };
  4152. BindingHelper._getObjectTypePropertyIDs = function (obj) {
  4153. var fullName = BABYLON.Tools.getFullClassName(obj);
  4154. if (!fullName) {
  4155. throw Error("Types involved in Data Binding must be decorated with the @className decorator");
  4156. }
  4157. var d = BindingHelper._propertiesID.getOrAddWithFactory(fullName, function () { return new BABYLON.StringDictionary(); });
  4158. return d;
  4159. };
  4160. BindingHelper._getPropertyID = function (object, propName) {
  4161. var otd = BindingHelper._getObjectTypePropertyIDs(object);
  4162. // Make sure we have a WatchedPropertyData for this property of this object type. This will contains the flagIg of the watched property.
  4163. // We use this flagId to flag for each watched instance which properties are watched, as final or intermediate and which directions are used
  4164. var propData = otd.getOrAddWithFactory(propName, function (k) { return 1 << otd.count; });
  4165. return propData;
  4166. };
  4167. return BindingHelper;
  4168. }());
  4169. BindingHelper._propertiesID = new BABYLON.StringDictionary();
  4170. BindingHelper._monitoredObjects = new BABYLON.StringDictionary();
  4171. var SmartPropertyPrim = SmartPropertyPrim_1 = (function (_super) {
  4172. __extends(SmartPropertyPrim, _super);
  4173. function SmartPropertyPrim() {
  4174. var _this = _super.call(this) || this;
  4175. _this._flags = 0;
  4176. _this._uid = null;
  4177. _this._modelKey = null;
  4178. _this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  4179. _this._boundingInfo = new BABYLON.BoundingInfo2D();
  4180. _this.animations = new Array();
  4181. return _this;
  4182. }
  4183. /**
  4184. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  4185. * @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.
  4186. */
  4187. SmartPropertyPrim.prototype.dispose = function () {
  4188. if (this.isDisposed) {
  4189. return false;
  4190. }
  4191. _super.prototype.dispose.call(this);
  4192. // Don't set to null, it may upset somebody...
  4193. this.animations.splice(0);
  4194. return true;
  4195. };
  4196. Object.defineProperty(SmartPropertyPrim.prototype, "uid", {
  4197. /**
  4198. * return a unique identifier for the Canvas2D
  4199. */
  4200. get: function () {
  4201. if (!this._uid) {
  4202. this._uid = BABYLON.Tools.RandomId();
  4203. }
  4204. return this._uid;
  4205. },
  4206. enumerable: true,
  4207. configurable: true
  4208. });
  4209. /**
  4210. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  4211. * Look at Sprite2D for more information
  4212. */
  4213. SmartPropertyPrim.prototype.getAnimatables = function () {
  4214. return new Array();
  4215. };
  4216. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  4217. /**
  4218. * Property giving the Model Key associated to the property.
  4219. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  4220. * @returns the model key string.
  4221. */
  4222. get: function () {
  4223. var _this = this;
  4224. // No need to compute it?
  4225. if (!this._isFlagSet(SmartPropertyPrim_1.flagModelDirty) && this._modelKey) {
  4226. return this._modelKey;
  4227. }
  4228. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  4229. var propDic = this.propDic;
  4230. propDic.forEach(function (k, v) {
  4231. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  4232. var propVal = _this[v.name];
  4233. // 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
  4234. if (propVal && propVal.constructor === Array) {
  4235. var firstVal = propVal[0];
  4236. if (!firstVal) {
  4237. propVal = 0;
  4238. }
  4239. else {
  4240. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  4241. }
  4242. }
  4243. var value = "[null]";
  4244. if (propVal != null) {
  4245. if (v.typeLevelCompare) {
  4246. value = BABYLON.Tools.getClassName(propVal);
  4247. }
  4248. else {
  4249. // String Dictionaries' content are too complex, with use a Random GUID to make the model unique
  4250. if (propVal instanceof BABYLON.StringDictionary) {
  4251. value = BABYLON.Tools.RandomId();
  4252. }
  4253. else if (propVal instanceof BABYLON.BaseTexture) {
  4254. value = propVal.uid;
  4255. }
  4256. else {
  4257. value = propVal.toString();
  4258. }
  4259. }
  4260. }
  4261. modelKey += v.name + ":" + value + ";";
  4262. }
  4263. });
  4264. this._clearFlags(SmartPropertyPrim_1.flagModelDirty);
  4265. this._modelKey = modelKey;
  4266. return modelKey;
  4267. },
  4268. enumerable: true,
  4269. configurable: true
  4270. });
  4271. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  4272. /**
  4273. * States if the Primitive is dirty and should be rendered again next time.
  4274. * @returns true is dirty, false otherwise
  4275. */
  4276. get: function () {
  4277. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim_1.flagModelDirty | SmartPropertyPrim_1.flagModelUpdate | SmartPropertyPrim_1.flagPositioningDirty | SmartPropertyPrim_1.flagLayoutDirty);
  4278. },
  4279. enumerable: true,
  4280. configurable: true
  4281. });
  4282. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  4283. this._setFlags(SmartPropertyPrim_1.flagLevelBoundingInfoDirty);
  4284. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  4285. if (this instanceof BABYLON.Prim2DBase) {
  4286. var curprim = this;
  4287. while (curprim) {
  4288. curprim._setFlags(SmartPropertyPrim_1.flagBoundingInfoDirty);
  4289. if (curprim.isSizeAuto) {
  4290. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  4291. curprim._setFlags(SmartPropertyPrim_1.flagPositioningDirty);
  4292. }
  4293. if (curprim instanceof BABYLON.Group2D) {
  4294. if (curprim.isRenderableGroup) {
  4295. break;
  4296. }
  4297. }
  4298. curprim = curprim.parent;
  4299. }
  4300. }
  4301. };
  4302. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  4303. _super.prototype._handlePropChanged.call(this, curValue, newValue, propName, propInfo, typeLevelCompare);
  4304. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  4305. if (propInfo.dirtyBoundingInfo) {
  4306. this._boundingBoxDirty();
  4307. }
  4308. else if (propInfo.dirtyParentBoundingInfo) {
  4309. var p = this._parent;
  4310. if (p != null) {
  4311. p._boundingBoxDirty();
  4312. }
  4313. }
  4314. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  4315. if (this instanceof BABYLON.Group2D && this._renderableData) {
  4316. this.handleGroupChanged(propInfo);
  4317. }
  4318. // Check for parent layout dirty
  4319. if (this instanceof BABYLON.Prim2DBase) {
  4320. var p = this._parent;
  4321. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  4322. p._setLayoutDirty();
  4323. }
  4324. }
  4325. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  4326. var instanceDirty = false;
  4327. if (typeLevelCompare && curValue != null && newValue != null) {
  4328. var cvProto = curValue.__proto__;
  4329. var nvProto = newValue.__proto__;
  4330. instanceDirty = (cvProto === nvProto);
  4331. }
  4332. // Set the dirty flags
  4333. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  4334. if (!this.isDirty) {
  4335. this._setFlags(SmartPropertyPrim_1.flagModelDirty);
  4336. }
  4337. }
  4338. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  4339. var propMask = propInfo.flagId;
  4340. this.onPrimitivePropertyDirty(propMask);
  4341. }
  4342. };
  4343. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  4344. this.onPrimBecomesDirty();
  4345. this._instanceDirtyFlags |= propFlagId;
  4346. };
  4347. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  4348. };
  4349. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  4350. _super.prototype._resetPropertiesDirty.call(this);
  4351. this._clearFlags(SmartPropertyPrim_1.flagPrimInDirtyList | SmartPropertyPrim_1.flagNeedRefresh);
  4352. };
  4353. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  4354. /**
  4355. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  4356. */
  4357. get: function () {
  4358. if (this._isFlagSet(SmartPropertyPrim_1.flagLevelBoundingInfoDirty)) {
  4359. if (this.updateLevelBoundingInfo()) {
  4360. this._boundingInfo.dirtyWorldAABB();
  4361. this._clearFlags(SmartPropertyPrim_1.flagLevelBoundingInfoDirty);
  4362. }
  4363. else {
  4364. this._levelBoundingInfo.clear();
  4365. }
  4366. }
  4367. return this._levelBoundingInfo;
  4368. },
  4369. enumerable: true,
  4370. configurable: true
  4371. });
  4372. /**
  4373. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  4374. */
  4375. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  4376. return false;
  4377. };
  4378. /**
  4379. * Property method called when the Primitive becomes dirty
  4380. */
  4381. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  4382. };
  4383. /**
  4384. * Check if a given flag is set
  4385. * @param flag the flag value
  4386. * @return true if set, false otherwise
  4387. */
  4388. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  4389. return (this._flags & flag) !== 0;
  4390. };
  4391. /**
  4392. * Check if all given flags are set
  4393. * @param flags the flags ORed
  4394. * @return true if all the flags are set, false otherwise
  4395. */
  4396. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  4397. return (this._flags & flags) === flags;
  4398. };
  4399. /**
  4400. * Check if at least one flag of the given flags is set
  4401. * @param flags the flags ORed
  4402. * @return true if at least one flag is set, false otherwise
  4403. */
  4404. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  4405. return (this._flags & flags) !== 0;
  4406. };
  4407. /**
  4408. * Clear the given flags
  4409. * @param flags the flags to clear
  4410. */
  4411. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  4412. this._flags &= ~flags;
  4413. };
  4414. /**
  4415. * Set the given flags to true state
  4416. * @param flags the flags ORed to set
  4417. * @return the flags state before this call
  4418. */
  4419. SmartPropertyPrim.prototype._setFlags = function (flags) {
  4420. var cur = this._flags;
  4421. this._flags |= flags;
  4422. return cur;
  4423. };
  4424. /**
  4425. * Change the state of the given flags
  4426. * @param flags the flags ORed to change
  4427. * @param state true to set them, false to clear them
  4428. */
  4429. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  4430. if (state) {
  4431. this._flags |= flags;
  4432. }
  4433. else {
  4434. this._flags &= ~flags;
  4435. }
  4436. };
  4437. return SmartPropertyPrim;
  4438. }(SmartPropertyBase));
  4439. SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT = 0;
  4440. SmartPropertyPrim.flagNoPartOfLayout = 0x0000001; // set if the primitive's position/size must not be computed by Layout Engine
  4441. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  4442. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  4443. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  4444. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  4445. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  4446. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  4447. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  4448. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  4449. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  4450. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  4451. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  4452. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  4453. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  4454. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  4455. SmartPropertyPrim.flagPrimInDirtyList = 0x0008000; // set if the primitive is in the primDirtyList
  4456. SmartPropertyPrim.flagIsContainer = 0x0010000; // set if the primitive is a container
  4457. SmartPropertyPrim.flagNeedRefresh = 0x0020000; // set if the primitive wasn't successful at refresh
  4458. SmartPropertyPrim.flagActualScaleDirty = 0x0040000; // set if the actualScale property needs to be recomputed
  4459. SmartPropertyPrim.flagDontInheritParentScale = 0x0080000; // set if the actualScale must not use its parent's scale to be computed
  4460. SmartPropertyPrim.flagGlobalTransformDirty = 0x0100000; // set if the global transform must be recomputed due to a local transform change
  4461. SmartPropertyPrim.flagLayoutBoundingInfoDirty = 0x0200000; // set if the layout bounding info is dirty
  4462. SmartPropertyPrim.flagCollisionActor = 0x0400000; // set if the primitive is part of the collision engine
  4463. SmartPropertyPrim.flagModelUpdate = 0x0800000; // set if the primitive's model data is to update
  4464. SmartPropertyPrim = SmartPropertyPrim_1 = __decorate([
  4465. BABYLON.className("SmartPropertyPrim", "BABYLON")
  4466. ], SmartPropertyPrim);
  4467. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  4468. function dependencyProperty(propId, piStore, mode, updateSourceTrigger) {
  4469. if (mode === void 0) { mode = DataBinding.MODE_TWOWAY; }
  4470. if (updateSourceTrigger === void 0) { updateSourceTrigger = DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED; }
  4471. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_DYNAMIC, { bindingMode: mode, bindingUpdateSourceTrigger: updateSourceTrigger });
  4472. }
  4473. BABYLON.dependencyProperty = dependencyProperty;
  4474. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  4475. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  4476. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  4477. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  4478. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_MODEL, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  4479. }
  4480. BABYLON.modelLevelProperty = modelLevelProperty;
  4481. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  4482. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  4483. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  4484. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  4485. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_INSTANCE, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  4486. }
  4487. BABYLON.instanceLevelProperty = instanceLevelProperty;
  4488. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  4489. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  4490. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  4491. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  4492. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_DYNAMIC, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  4493. }
  4494. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  4495. var DataBinding_1, SmartPropertyBase_1, SmartPropertyPrim_1;
  4496. })(BABYLON || (BABYLON = {}));
  4497. //# sourceMappingURL=babylon.smartPropertyPrim.js.map
  4498. var __extends = (this && this.__extends) || function (d, b) {
  4499. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4500. function __() { this.constructor = d; }
  4501. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4502. };
  4503. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  4504. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  4505. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4506. 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;
  4507. return c > 3 && r && Object.defineProperty(target, key, r), r;
  4508. };
  4509. var BABYLON;
  4510. (function (BABYLON) {
  4511. var PrepareRender2DContext = (function () {
  4512. function PrepareRender2DContext() {
  4513. this.forceRefreshPrimitive = false;
  4514. }
  4515. return PrepareRender2DContext;
  4516. }());
  4517. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  4518. var Render2DContext = (function () {
  4519. function Render2DContext(renderMode) {
  4520. this._renderMode = renderMode;
  4521. this.useInstancing = false;
  4522. this.groupInfoPartData = null;
  4523. this.partDataStartIndex = this.partDataEndIndex = null;
  4524. this.instancedBuffers = null;
  4525. }
  4526. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  4527. /**
  4528. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  4529. */
  4530. get: function () {
  4531. return this._renderMode;
  4532. },
  4533. enumerable: true,
  4534. configurable: true
  4535. });
  4536. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  4537. /**
  4538. * The set of primitives to render is opaque.
  4539. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  4540. */
  4541. get: function () {
  4542. return Render2DContext._renderModeOpaque;
  4543. },
  4544. enumerable: true,
  4545. configurable: true
  4546. });
  4547. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  4548. /**
  4549. * The set of primitives to render is using Alpha Test (aka masking).
  4550. * 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.
  4551. */
  4552. get: function () {
  4553. return Render2DContext._renderModeAlphaTest;
  4554. },
  4555. enumerable: true,
  4556. configurable: true
  4557. });
  4558. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  4559. /**
  4560. * The set of primitives to render is transparent.
  4561. * 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.
  4562. */
  4563. get: function () {
  4564. return Render2DContext._renderModeTransparent;
  4565. },
  4566. enumerable: true,
  4567. configurable: true
  4568. });
  4569. return Render2DContext;
  4570. }());
  4571. Render2DContext._renderModeOpaque = 1;
  4572. Render2DContext._renderModeAlphaTest = 2;
  4573. Render2DContext._renderModeTransparent = 3;
  4574. BABYLON.Render2DContext = Render2DContext;
  4575. /**
  4576. * This class store information for the pointerEventObservable Observable.
  4577. * 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.
  4578. */
  4579. var PrimitivePointerInfo = (function () {
  4580. function PrimitivePointerInfo() {
  4581. this.primitivePointerPos = BABYLON.Vector2.Zero();
  4582. this.tilt = BABYLON.Vector2.Zero();
  4583. this.cancelBubble = false;
  4584. }
  4585. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  4586. // 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.
  4587. /**
  4588. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  4589. * Bubbles: yes
  4590. */
  4591. get: function () {
  4592. return PrimitivePointerInfo._pointerOver;
  4593. },
  4594. enumerable: true,
  4595. configurable: true
  4596. });
  4597. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  4598. /**
  4599. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  4600. * Bubbles: no
  4601. */
  4602. get: function () {
  4603. return PrimitivePointerInfo._pointerEnter;
  4604. },
  4605. enumerable: true,
  4606. configurable: true
  4607. });
  4608. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  4609. /**
  4610. * 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.
  4611. * Bubbles: yes
  4612. */
  4613. get: function () {
  4614. return PrimitivePointerInfo._pointerDown;
  4615. },
  4616. enumerable: true,
  4617. configurable: true
  4618. });
  4619. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  4620. /**
  4621. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  4622. * Bubbles: yes
  4623. */
  4624. get: function () {
  4625. return PrimitivePointerInfo._pointerMouseWheel;
  4626. },
  4627. enumerable: true,
  4628. configurable: true
  4629. });
  4630. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  4631. /**
  4632. * 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.
  4633. * Bubbles: yes
  4634. */
  4635. get: function () {
  4636. return PrimitivePointerInfo._pointerMove;
  4637. },
  4638. enumerable: true,
  4639. configurable: true
  4640. });
  4641. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  4642. /**
  4643. * 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.
  4644. * Bubbles: yes
  4645. */
  4646. get: function () {
  4647. return PrimitivePointerInfo._pointerUp;
  4648. },
  4649. enumerable: true,
  4650. configurable: true
  4651. });
  4652. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  4653. /**
  4654. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  4655. * Bubbles: yes
  4656. */
  4657. get: function () {
  4658. return PrimitivePointerInfo._pointerOut;
  4659. },
  4660. enumerable: true,
  4661. configurable: true
  4662. });
  4663. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  4664. /**
  4665. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  4666. * Bubbles: no
  4667. */
  4668. get: function () {
  4669. return PrimitivePointerInfo._pointerLeave;
  4670. },
  4671. enumerable: true,
  4672. configurable: true
  4673. });
  4674. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  4675. /**
  4676. * 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.
  4677. * Bubbles: yes
  4678. */
  4679. get: function () {
  4680. return PrimitivePointerInfo._pointerGotCapture;
  4681. },
  4682. enumerable: true,
  4683. configurable: true
  4684. });
  4685. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  4686. /**
  4687. * This event type is raised after pointer capture is released for a pointer.
  4688. * Bubbles: yes
  4689. */
  4690. get: function () {
  4691. return PrimitivePointerInfo._pointerLostCapture;
  4692. },
  4693. enumerable: true,
  4694. configurable: true
  4695. });
  4696. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  4697. get: function () {
  4698. return PrimitivePointerInfo._mouseWheelPrecision;
  4699. },
  4700. enumerable: true,
  4701. configurable: true
  4702. });
  4703. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  4704. this.relatedTarget = prim;
  4705. this.relatedTargetPointerPos = primPointerPos;
  4706. };
  4707. PrimitivePointerInfo.getEventTypeName = function (mask) {
  4708. switch (mask) {
  4709. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  4710. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  4711. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  4712. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  4713. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  4714. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  4715. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  4716. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  4717. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  4718. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  4719. }
  4720. };
  4721. return PrimitivePointerInfo;
  4722. }());
  4723. PrimitivePointerInfo._pointerOver = 0x0001;
  4724. PrimitivePointerInfo._pointerEnter = 0x0002;
  4725. PrimitivePointerInfo._pointerDown = 0x0004;
  4726. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  4727. PrimitivePointerInfo._pointerMove = 0x0010;
  4728. PrimitivePointerInfo._pointerUp = 0x0020;
  4729. PrimitivePointerInfo._pointerOut = 0x0040;
  4730. PrimitivePointerInfo._pointerLeave = 0x0080;
  4731. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  4732. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  4733. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  4734. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  4735. /**
  4736. * Defines the horizontal and vertical alignment information for a Primitive.
  4737. */
  4738. var PrimitiveAlignment = PrimitiveAlignment_1 = (function () {
  4739. function PrimitiveAlignment(changeCallback) {
  4740. this._changedCallback = changeCallback;
  4741. this._horizontal = PrimitiveAlignment_1.AlignLeft;
  4742. this._vertical = PrimitiveAlignment_1.AlignBottom;
  4743. }
  4744. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  4745. /**
  4746. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  4747. */
  4748. get: function () { return PrimitiveAlignment_1._AlignLeft; },
  4749. enumerable: true,
  4750. configurable: true
  4751. });
  4752. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  4753. /**
  4754. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  4755. */
  4756. get: function () { return PrimitiveAlignment_1._AlignTop; },
  4757. enumerable: true,
  4758. configurable: true
  4759. });
  4760. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  4761. /**
  4762. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  4763. */
  4764. get: function () { return PrimitiveAlignment_1._AlignRight; },
  4765. enumerable: true,
  4766. configurable: true
  4767. });
  4768. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  4769. /**
  4770. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  4771. */
  4772. get: function () { return PrimitiveAlignment_1._AlignBottom; },
  4773. enumerable: true,
  4774. configurable: true
  4775. });
  4776. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  4777. /**
  4778. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  4779. */
  4780. get: function () { return PrimitiveAlignment_1._AlignCenter; },
  4781. enumerable: true,
  4782. configurable: true
  4783. });
  4784. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  4785. /**
  4786. * The content is stretched toward the opposite edges of the Primitive
  4787. */
  4788. get: function () { return PrimitiveAlignment_1._AlignStretch; },
  4789. enumerable: true,
  4790. configurable: true
  4791. });
  4792. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  4793. /**
  4794. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  4795. */
  4796. get: function () {
  4797. return this._horizontal;
  4798. },
  4799. set: function (value) {
  4800. if (this._horizontal === value) {
  4801. return;
  4802. }
  4803. this._horizontal = value;
  4804. this.onChangeCallback();
  4805. },
  4806. enumerable: true,
  4807. configurable: true
  4808. });
  4809. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  4810. /**
  4811. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  4812. */
  4813. get: function () {
  4814. return this._vertical;
  4815. },
  4816. set: function (value) {
  4817. if (this._vertical === value) {
  4818. return;
  4819. }
  4820. this._vertical = value;
  4821. this.onChangeCallback();
  4822. },
  4823. enumerable: true,
  4824. configurable: true
  4825. });
  4826. PrimitiveAlignment.prototype.onChangeCallback = function () {
  4827. if (this._changedCallback) {
  4828. this._changedCallback();
  4829. }
  4830. };
  4831. /**
  4832. * Set the horizontal alignment from a string value.
  4833. * @param text can be either: 'left','right','center','stretch'
  4834. */
  4835. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  4836. var v = text.trim().toLocaleLowerCase();
  4837. switch (v) {
  4838. case "left":
  4839. this.horizontal = PrimitiveAlignment_1.AlignLeft;
  4840. return;
  4841. case "right":
  4842. this.horizontal = PrimitiveAlignment_1.AlignRight;
  4843. return;
  4844. case "center":
  4845. this.horizontal = PrimitiveAlignment_1.AlignCenter;
  4846. return;
  4847. case "stretch":
  4848. this.horizontal = PrimitiveAlignment_1.AlignStretch;
  4849. return;
  4850. }
  4851. };
  4852. /**
  4853. * Set the vertical alignment from a string value.
  4854. * @param text can be either: 'top','bottom','center','stretch'
  4855. */
  4856. PrimitiveAlignment.prototype.setVertical = function (text) {
  4857. var v = text.trim().toLocaleLowerCase();
  4858. switch (v) {
  4859. case "top":
  4860. this.vertical = PrimitiveAlignment_1.AlignTop;
  4861. return;
  4862. case "bottom":
  4863. this.vertical = PrimitiveAlignment_1.AlignBottom;
  4864. return;
  4865. case "center":
  4866. this.vertical = PrimitiveAlignment_1.AlignCenter;
  4867. return;
  4868. case "stretch":
  4869. this.vertical = PrimitiveAlignment_1.AlignStretch;
  4870. return;
  4871. }
  4872. };
  4873. /**
  4874. * Set the horizontal and or vertical alignments from a string value.
  4875. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  4876. */
  4877. PrimitiveAlignment.prototype.fromString = function (value) {
  4878. var m = value.trim().split(",");
  4879. if (m.length === 1) {
  4880. this.setHorizontal(m[0]);
  4881. this.setVertical(m[0]);
  4882. }
  4883. else {
  4884. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  4885. var v = m_1[_i];
  4886. v = v.toLocaleLowerCase().trim();
  4887. // Horizontal
  4888. var i = v.indexOf("h:");
  4889. if (i === -1) {
  4890. i = v.indexOf("horizontal:");
  4891. }
  4892. if (i !== -1) {
  4893. v = v.substr(v.indexOf(":") + 1);
  4894. this.setHorizontal(v);
  4895. continue;
  4896. }
  4897. // Vertical
  4898. i = v.indexOf("v:");
  4899. if (i === -1) {
  4900. i = v.indexOf("vertical:");
  4901. }
  4902. if (i !== -1) {
  4903. v = v.substr(v.indexOf(":") + 1);
  4904. this.setVertical(v);
  4905. continue;
  4906. }
  4907. }
  4908. }
  4909. };
  4910. PrimitiveAlignment.prototype.copyFrom = function (pa) {
  4911. this._horizontal = pa._horizontal;
  4912. this._vertical = pa._vertical;
  4913. this.onChangeCallback();
  4914. };
  4915. Object.defineProperty(PrimitiveAlignment.prototype, "isDefault", {
  4916. get: function () {
  4917. return this.horizontal === PrimitiveAlignment_1.AlignLeft && this.vertical === PrimitiveAlignment_1.AlignBottom;
  4918. },
  4919. enumerable: true,
  4920. configurable: true
  4921. });
  4922. return PrimitiveAlignment;
  4923. }());
  4924. PrimitiveAlignment._AlignLeft = 1;
  4925. PrimitiveAlignment._AlignTop = 1; // Same as left
  4926. PrimitiveAlignment._AlignRight = 2;
  4927. PrimitiveAlignment._AlignBottom = 2; // Same as right
  4928. PrimitiveAlignment._AlignCenter = 3;
  4929. PrimitiveAlignment._AlignStretch = 4;
  4930. PrimitiveAlignment = PrimitiveAlignment_1 = __decorate([
  4931. BABYLON.className("PrimitiveAlignment", "BABYLON")
  4932. ], PrimitiveAlignment);
  4933. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  4934. /**
  4935. * Stores information about a Primitive that was intersected
  4936. */
  4937. var PrimitiveIntersectedInfo = (function () {
  4938. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  4939. this.prim = prim;
  4940. this.intersectionLocation = intersectionLocation;
  4941. }
  4942. return PrimitiveIntersectedInfo;
  4943. }());
  4944. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  4945. /**
  4946. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  4947. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  4948. */
  4949. var PrimitiveThickness = PrimitiveThickness_1 = (function () {
  4950. function PrimitiveThickness(parentAccess, changedCallback) {
  4951. this._parentAccess = parentAccess;
  4952. this._changedCallback = changedCallback;
  4953. this._pixels = new Array(4);
  4954. this._percentages = new Array(4);
  4955. this._setType(0, PrimitiveThickness_1.Auto);
  4956. this._setType(1, PrimitiveThickness_1.Auto);
  4957. this._setType(2, PrimitiveThickness_1.Auto);
  4958. this._setType(3, PrimitiveThickness_1.Auto);
  4959. this._pixels[0] = 0;
  4960. this._pixels[1] = 0;
  4961. this._pixels[2] = 0;
  4962. this._pixels[3] = 0;
  4963. }
  4964. /**
  4965. * Set the thickness from a string value
  4966. * @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.
  4967. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  4968. */
  4969. PrimitiveThickness.prototype.fromString = function (thickness) {
  4970. this._clear();
  4971. var m = thickness.trim().split(",");
  4972. // Special case, one value to apply to all edges
  4973. if (m.length === 1 && thickness.indexOf(":") === -1) {
  4974. this._setStringValue(m[0], 0, false);
  4975. this._setStringValue(m[0], 1, false);
  4976. this._setStringValue(m[0], 2, false);
  4977. this._setStringValue(m[0], 3, false);
  4978. this.onChangeCallback();
  4979. return;
  4980. }
  4981. var res = false;
  4982. for (var _i = 0, m_2 = m; _i < m_2.length; _i++) {
  4983. var cm = m_2[_i];
  4984. res = this._extractString(cm, false) || res;
  4985. }
  4986. if (!res) {
  4987. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  4988. }
  4989. // Check the margin that weren't set and set them in auto
  4990. if ((this._flags & 0x000F) === 0)
  4991. this._flags |= PrimitiveThickness_1.Pixel << 0;
  4992. if ((this._flags & 0x00F0) === 0)
  4993. this._flags |= PrimitiveThickness_1.Pixel << 4;
  4994. if ((this._flags & 0x0F00) === 0)
  4995. this._flags |= PrimitiveThickness_1.Pixel << 8;
  4996. if ((this._flags & 0xF000) === 0)
  4997. this._flags |= PrimitiveThickness_1.Pixel << 12;
  4998. this.onChangeCallback();
  4999. };
  5000. /**
  5001. * Set the thickness from multiple string
  5002. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  5003. * @param top the top thickness to set
  5004. * @param left the left thickness to set
  5005. * @param right the right thickness to set
  5006. * @param bottom the bottom thickness to set
  5007. */
  5008. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  5009. this._clear();
  5010. this._setStringValue(top, 0, false);
  5011. this._setStringValue(left, 1, false);
  5012. this._setStringValue(right, 2, false);
  5013. this._setStringValue(bottom, 3, false);
  5014. this.onChangeCallback();
  5015. return this;
  5016. };
  5017. /**
  5018. * Set the thickness from pixel values
  5019. * @param top the top thickness in pixels to set
  5020. * @param left the left thickness in pixels to set
  5021. * @param right the right thickness in pixels to set
  5022. * @param bottom the bottom thickness in pixels to set
  5023. */
  5024. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  5025. this._clear();
  5026. this._pixels[0] = top;
  5027. this._pixels[1] = left;
  5028. this._pixels[2] = right;
  5029. this._pixels[3] = bottom;
  5030. this.onChangeCallback();
  5031. return this;
  5032. };
  5033. /**
  5034. * Apply the same pixel value to all edges
  5035. * @param margin the value to set, in pixels.
  5036. */
  5037. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  5038. this._clear();
  5039. this._pixels[0] = margin;
  5040. this._pixels[1] = margin;
  5041. this._pixels[2] = margin;
  5042. this._pixels[3] = margin;
  5043. this.onChangeCallback();
  5044. return this;
  5045. };
  5046. PrimitiveThickness.prototype.copyFrom = function (pt) {
  5047. this._clear();
  5048. for (var i = 0; i < 4; i++) {
  5049. this._pixels[i] = pt._pixels[i];
  5050. this._percentages[i] = pt._percentages[i];
  5051. }
  5052. this._flags = pt._flags;
  5053. this.onChangeCallback();
  5054. };
  5055. /**
  5056. * Set all edges in auto
  5057. */
  5058. PrimitiveThickness.prototype.auto = function () {
  5059. this._clear();
  5060. this._flags = (PrimitiveThickness_1.Auto << 0) | (PrimitiveThickness_1.Auto << 4) | (PrimitiveThickness_1.Auto << 8) | (PrimitiveThickness_1.Auto << 12);
  5061. this._pixels[0] = 0;
  5062. this._pixels[1] = 0;
  5063. this._pixels[2] = 0;
  5064. this._pixels[3] = 0;
  5065. this.onChangeCallback();
  5066. return this;
  5067. };
  5068. PrimitiveThickness.prototype._clear = function () {
  5069. this._flags = 0;
  5070. this._pixels[0] = 0;
  5071. this._pixels[1] = 0;
  5072. this._pixels[2] = 0;
  5073. this._pixels[3] = 0;
  5074. this._percentages[0] = null;
  5075. this._percentages[1] = null;
  5076. this._percentages[2] = null;
  5077. this._percentages[3] = null;
  5078. };
  5079. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  5080. var v = value.trim().toLocaleLowerCase();
  5081. if (v.indexOf("top:") === 0) {
  5082. v = v.substr(4).trim();
  5083. return this._setStringValue(v, 0, emitChanged);
  5084. }
  5085. if (v.indexOf("left:") === 0) {
  5086. v = v.substr(5).trim();
  5087. return this._setStringValue(v, 1, emitChanged);
  5088. }
  5089. if (v.indexOf("right:") === 0) {
  5090. v = v.substr(6).trim();
  5091. return this._setStringValue(v, 2, emitChanged);
  5092. }
  5093. if (v.indexOf("bottom:") === 0) {
  5094. v = v.substr(7).trim();
  5095. return this._setStringValue(v, 3, emitChanged);
  5096. }
  5097. return false;
  5098. };
  5099. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  5100. // Check for auto
  5101. var v = value.trim().toLocaleLowerCase();
  5102. if (v === "auto") {
  5103. if (this._isType(index, PrimitiveThickness_1.Auto)) {
  5104. return true;
  5105. }
  5106. this._setType(index, PrimitiveThickness_1.Auto);
  5107. this._pixels[index] = 0;
  5108. if (emitChanged) {
  5109. this.onChangeCallback();
  5110. }
  5111. }
  5112. else if (v === "inherit") {
  5113. if (this._isType(index, PrimitiveThickness_1.Inherit)) {
  5114. return true;
  5115. }
  5116. this._setType(index, PrimitiveThickness_1.Inherit);
  5117. this._pixels[index] = null;
  5118. if (emitChanged) {
  5119. this.onChangeCallback();
  5120. }
  5121. }
  5122. else {
  5123. var pI = v.indexOf("%");
  5124. // Check for percentage
  5125. if (pI !== -1) {
  5126. var n_1 = v.substr(0, pI);
  5127. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  5128. if (this._isType(index, PrimitiveThickness_1.Percentage) && (this._percentages[index] === number_1)) {
  5129. return true;
  5130. }
  5131. this._setType(index, PrimitiveThickness_1.Percentage);
  5132. if (isNaN(number_1)) {
  5133. return false;
  5134. }
  5135. this._percentages[index] = number_1;
  5136. if (emitChanged) {
  5137. this.onChangeCallback();
  5138. }
  5139. return true;
  5140. }
  5141. // Check for pixel
  5142. var n = void 0;
  5143. pI = v.indexOf("px");
  5144. if (pI !== -1) {
  5145. n = v.substr(0, pI).trim();
  5146. }
  5147. else {
  5148. n = v;
  5149. }
  5150. var number = Number(n);
  5151. if (this._isType(index, PrimitiveThickness_1.Pixel) && (this._pixels[index] === number)) {
  5152. return true;
  5153. }
  5154. if (isNaN(number)) {
  5155. return false;
  5156. }
  5157. this._pixels[index] = number;
  5158. this._setType(index, PrimitiveThickness_1.Pixel);
  5159. if (emitChanged) {
  5160. this.onChangeCallback();
  5161. }
  5162. return true;
  5163. }
  5164. };
  5165. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  5166. // 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
  5167. value = Math.round(value);
  5168. if (this._isType(index, PrimitiveThickness_1.Pixel) && this._pixels[index] === value) {
  5169. return;
  5170. }
  5171. this._setType(index, PrimitiveThickness_1.Pixel);
  5172. this._pixels[index] = value;
  5173. if (emitChanged) {
  5174. this.onChangeCallback();
  5175. }
  5176. };
  5177. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  5178. // Clip Value to bounds
  5179. value = Math.min(1, value);
  5180. value = Math.max(0, value);
  5181. value = Math.round(value * 100) / 100; // 0.01 precision
  5182. if (this._isType(index, PrimitiveThickness_1.Percentage) && this._percentages[index] === value) {
  5183. return;
  5184. }
  5185. this._setType(index, PrimitiveThickness_1.Percentage);
  5186. this._percentages[index] = value;
  5187. if (emitChanged) {
  5188. this.onChangeCallback();
  5189. }
  5190. };
  5191. PrimitiveThickness.prototype._getStringValue = function (index) {
  5192. var f = (this._flags >> (index * 4)) & 0xF;
  5193. switch (f) {
  5194. case PrimitiveThickness_1.Auto:
  5195. return "auto";
  5196. case PrimitiveThickness_1.Pixel:
  5197. return this._pixels[index] + "px";
  5198. case PrimitiveThickness_1.Percentage:
  5199. return this._percentages[index] * 100 + "%";
  5200. case PrimitiveThickness_1.Inherit:
  5201. return "inherit";
  5202. }
  5203. return "";
  5204. };
  5205. PrimitiveThickness.prototype._isType = function (index, type) {
  5206. var f = (this._flags >> (index * 4)) & 0xF;
  5207. return f === type;
  5208. };
  5209. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  5210. var t = (this._flags >> (index * 4)) & 0xF;
  5211. if (processInherit && (t === PrimitiveThickness_1.Inherit)) {
  5212. var p = this._parentAccess();
  5213. if (p) {
  5214. return p._getType(index, true);
  5215. }
  5216. return PrimitiveThickness_1.Auto;
  5217. }
  5218. return t;
  5219. };
  5220. PrimitiveThickness.prototype._setType = function (index, type) {
  5221. this._flags &= ~(0xF << (index * 4));
  5222. this._flags |= type << (index * 4);
  5223. };
  5224. PrimitiveThickness.prototype.setTop = function (value) {
  5225. if (typeof value === "string") {
  5226. this._setStringValue(value, 0, true);
  5227. }
  5228. else {
  5229. this.topPixels = value;
  5230. }
  5231. };
  5232. PrimitiveThickness.prototype.setLeft = function (value) {
  5233. if (typeof value === "string") {
  5234. this._setStringValue(value, 1, true);
  5235. }
  5236. else {
  5237. this.leftPixels = value;
  5238. }
  5239. };
  5240. PrimitiveThickness.prototype.setRight = function (value) {
  5241. if (typeof value === "string") {
  5242. this._setStringValue(value, 2, true);
  5243. }
  5244. else {
  5245. this.rightPixels = value;
  5246. }
  5247. };
  5248. PrimitiveThickness.prototype.setBottom = function (value) {
  5249. if (typeof value === "string") {
  5250. this._setStringValue(value, 3, true);
  5251. }
  5252. else {
  5253. this.bottomPixels = value;
  5254. }
  5255. };
  5256. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  5257. /**
  5258. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  5259. */
  5260. get: function () {
  5261. return this._getStringValue(0);
  5262. },
  5263. set: function (value) {
  5264. this._setStringValue(value, 0, true);
  5265. },
  5266. enumerable: true,
  5267. configurable: true
  5268. });
  5269. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  5270. /**
  5271. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  5272. */
  5273. get: function () {
  5274. return this._getStringValue(1);
  5275. },
  5276. set: function (value) {
  5277. this._setStringValue(value, 1, true);
  5278. },
  5279. enumerable: true,
  5280. configurable: true
  5281. });
  5282. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  5283. /**
  5284. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  5285. */
  5286. get: function () {
  5287. return this._getStringValue(2);
  5288. },
  5289. set: function (value) {
  5290. this._setStringValue(value, 2, true);
  5291. },
  5292. enumerable: true,
  5293. configurable: true
  5294. });
  5295. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  5296. /**
  5297. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  5298. */
  5299. get: function () {
  5300. return this._getStringValue(3);
  5301. },
  5302. set: function (value) {
  5303. this._setStringValue(value, 3, true);
  5304. },
  5305. enumerable: true,
  5306. configurable: true
  5307. });
  5308. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  5309. /**
  5310. * Get/set the top thickness in pixel.
  5311. */
  5312. get: function () {
  5313. return this._pixels[0];
  5314. },
  5315. set: function (value) {
  5316. this._setPixels(value, 0, true);
  5317. },
  5318. enumerable: true,
  5319. configurable: true
  5320. });
  5321. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  5322. /**
  5323. * Get/set the left thickness in pixel.
  5324. */
  5325. get: function () {
  5326. return this._pixels[1];
  5327. },
  5328. set: function (value) {
  5329. this._setPixels(value, 1, true);
  5330. },
  5331. enumerable: true,
  5332. configurable: true
  5333. });
  5334. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  5335. /**
  5336. * Get/set the right thickness in pixel.
  5337. */
  5338. get: function () {
  5339. return this._pixels[2];
  5340. },
  5341. set: function (value) {
  5342. this._setPixels(value, 2, true);
  5343. },
  5344. enumerable: true,
  5345. configurable: true
  5346. });
  5347. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  5348. /**
  5349. * Get/set the bottom thickness in pixel.
  5350. */
  5351. get: function () {
  5352. return this._pixels[3];
  5353. },
  5354. set: function (value) {
  5355. this._setPixels(value, 3, true);
  5356. },
  5357. enumerable: true,
  5358. configurable: true
  5359. });
  5360. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  5361. /**
  5362. * Get/set the top thickness in percentage.
  5363. * The get will return a valid value only if the edge type is percentage.
  5364. * The Set will change the edge mode if needed
  5365. */
  5366. get: function () {
  5367. return this._percentages[0];
  5368. },
  5369. set: function (value) {
  5370. this._setPercentage(value, 0, true);
  5371. },
  5372. enumerable: true,
  5373. configurable: true
  5374. });
  5375. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  5376. /**
  5377. * Get/set the left thickness in percentage.
  5378. * The get will return a valid value only if the edge mode is percentage.
  5379. * The Set will change the edge mode if needed
  5380. */
  5381. get: function () {
  5382. return this._percentages[1];
  5383. },
  5384. set: function (value) {
  5385. this._setPercentage(value, 1, true);
  5386. },
  5387. enumerable: true,
  5388. configurable: true
  5389. });
  5390. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  5391. /**
  5392. * Get/set the right thickness in percentage.
  5393. * The get will return a valid value only if the edge mode is percentage.
  5394. * The Set will change the edge mode if needed
  5395. */
  5396. get: function () {
  5397. return this._percentages[2];
  5398. },
  5399. set: function (value) {
  5400. this._setPercentage(value, 2, true);
  5401. },
  5402. enumerable: true,
  5403. configurable: true
  5404. });
  5405. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  5406. /**
  5407. * Get/set the bottom thickness in percentage.
  5408. * The get will return a valid value only if the edge mode is percentage.
  5409. * The Set will change the edge mode if needed
  5410. */
  5411. get: function () {
  5412. return this._percentages[3];
  5413. },
  5414. set: function (value) {
  5415. this._setPercentage(value, 3, true);
  5416. },
  5417. enumerable: true,
  5418. configurable: true
  5419. });
  5420. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  5421. /**
  5422. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  5423. */
  5424. get: function () {
  5425. return this._getType(0, false);
  5426. },
  5427. set: function (mode) {
  5428. this._setType(0, mode);
  5429. },
  5430. enumerable: true,
  5431. configurable: true
  5432. });
  5433. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  5434. /**
  5435. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  5436. */
  5437. get: function () {
  5438. return this._getType(1, false);
  5439. },
  5440. set: function (mode) {
  5441. this._setType(1, mode);
  5442. },
  5443. enumerable: true,
  5444. configurable: true
  5445. });
  5446. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  5447. /**
  5448. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  5449. */
  5450. get: function () {
  5451. return this._getType(2, false);
  5452. },
  5453. set: function (mode) {
  5454. this._setType(2, mode);
  5455. },
  5456. enumerable: true,
  5457. configurable: true
  5458. });
  5459. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  5460. /**
  5461. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  5462. */
  5463. get: function () {
  5464. return this._getType(3, false);
  5465. },
  5466. set: function (mode) {
  5467. this._setType(3, mode);
  5468. },
  5469. enumerable: true,
  5470. configurable: true
  5471. });
  5472. Object.defineProperty(PrimitiveThickness.prototype, "isDefault", {
  5473. get: function () {
  5474. return this._flags === 0x1111;
  5475. },
  5476. enumerable: true,
  5477. configurable: true
  5478. });
  5479. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  5480. var type = this._getType(index, false);
  5481. if (type === PrimitiveThickness_1.Inherit) {
  5482. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  5483. return;
  5484. }
  5485. if (type !== PrimitiveThickness_1.Percentage) {
  5486. return;
  5487. }
  5488. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  5489. this._pixels[index] = pixels;
  5490. if (emitChanged) {
  5491. this.onChangeCallback();
  5492. }
  5493. };
  5494. PrimitiveThickness.prototype.onChangeCallback = function () {
  5495. if (this._changedCallback) {
  5496. this._changedCallback();
  5497. }
  5498. };
  5499. /**
  5500. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  5501. * @param sourceArea the source area where the content must be sized/positioned
  5502. * @param contentSize the content size to position/resize
  5503. * @param alignment the alignment setting
  5504. * @param dstOffset the position of the content, x, y, z, w are left, bottom, right, top
  5505. * @param dstArea the new size of the content
  5506. */
  5507. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea, computeLayoutArea) {
  5508. if (computeLayoutArea === void 0) { computeLayoutArea = false; }
  5509. // Fetch some data
  5510. var topType = this._getType(0, true);
  5511. var leftType = this._getType(1, true);
  5512. var rightType = this._getType(2, true);
  5513. var bottomType = this._getType(3, true);
  5514. var hasWidth = contentSize && (contentSize.width != null);
  5515. var hasHeight = contentSize && (contentSize.height != null);
  5516. var width = hasWidth ? contentSize.width : 0;
  5517. var height = hasHeight ? contentSize.height : 0;
  5518. var isTopAuto = topType === PrimitiveThickness_1.Auto;
  5519. var isLeftAuto = leftType === PrimitiveThickness_1.Auto;
  5520. var isRightAuto = rightType === PrimitiveThickness_1.Auto;
  5521. var isBottomAuto = bottomType === PrimitiveThickness_1.Auto;
  5522. switch (alignment.horizontal) {
  5523. case PrimitiveAlignment.AlignLeft:
  5524. {
  5525. if (isLeftAuto) {
  5526. dstOffset.x = 0;
  5527. }
  5528. else {
  5529. this._computePixels(1, sourceArea, true);
  5530. dstOffset.x = this.leftPixels;
  5531. }
  5532. dstArea.width = width;
  5533. if (computeLayoutArea) {
  5534. dstArea.width += this.leftPixels;
  5535. }
  5536. dstOffset.z = sourceArea.width - (dstOffset.x + width);
  5537. break;
  5538. }
  5539. case PrimitiveAlignment.AlignRight:
  5540. {
  5541. if (isRightAuto) {
  5542. dstOffset.x = Math.round(sourceArea.width - width);
  5543. }
  5544. else {
  5545. this._computePixels(2, sourceArea, true);
  5546. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  5547. }
  5548. dstArea.width = width;
  5549. if (computeLayoutArea) {
  5550. dstArea.width += this.rightPixels;
  5551. }
  5552. dstOffset.z = this.rightPixels;
  5553. break;
  5554. }
  5555. case PrimitiveAlignment.AlignStretch:
  5556. {
  5557. if (isLeftAuto) {
  5558. dstOffset.x = 0;
  5559. }
  5560. else {
  5561. this._computePixels(1, sourceArea, true);
  5562. dstOffset.x = this.leftPixels;
  5563. }
  5564. var right = 0;
  5565. if (!isRightAuto) {
  5566. this._computePixels(2, sourceArea, true);
  5567. right = this.rightPixels;
  5568. }
  5569. dstArea.width = sourceArea.width - (dstOffset.x + right);
  5570. dstOffset.z = this.rightPixels;
  5571. break;
  5572. }
  5573. case PrimitiveAlignment.AlignCenter:
  5574. {
  5575. if (!isLeftAuto) {
  5576. this._computePixels(1, sourceArea, true);
  5577. }
  5578. if (!isRightAuto) {
  5579. this._computePixels(2, sourceArea, true);
  5580. }
  5581. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  5582. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  5583. dstArea.width = width;
  5584. dstOffset.z = sourceArea.width - (dstOffset.x + width);
  5585. break;
  5586. }
  5587. }
  5588. switch (alignment.vertical) {
  5589. case PrimitiveAlignment.AlignTop:
  5590. {
  5591. if (isTopAuto) {
  5592. dstOffset.y = sourceArea.height - height;
  5593. }
  5594. else {
  5595. this._computePixels(0, sourceArea, true);
  5596. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  5597. }
  5598. dstArea.height = height;
  5599. if (computeLayoutArea) {
  5600. dstArea.height += this.topPixels;
  5601. }
  5602. dstOffset.w = this.topPixels;
  5603. break;
  5604. }
  5605. case PrimitiveAlignment.AlignBottom:
  5606. {
  5607. if (isBottomAuto) {
  5608. dstOffset.y = 0;
  5609. }
  5610. else {
  5611. this._computePixels(3, sourceArea, true);
  5612. dstOffset.y = this.bottomPixels;
  5613. }
  5614. dstArea.height = height;
  5615. if (computeLayoutArea) {
  5616. dstArea.height += this.bottomPixels;
  5617. }
  5618. dstOffset.w = sourceArea.height - (dstOffset.y + height);
  5619. break;
  5620. }
  5621. case PrimitiveAlignment.AlignStretch:
  5622. {
  5623. if (isBottomAuto) {
  5624. dstOffset.y = 0;
  5625. }
  5626. else {
  5627. this._computePixels(3, sourceArea, true);
  5628. dstOffset.y = this.bottomPixels;
  5629. }
  5630. var top_1 = 0;
  5631. if (!isTopAuto) {
  5632. this._computePixels(0, sourceArea, true);
  5633. top_1 = this.topPixels;
  5634. }
  5635. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  5636. dstOffset.w = this.topPixels;
  5637. break;
  5638. }
  5639. case PrimitiveAlignment.AlignCenter:
  5640. {
  5641. if (!isTopAuto) {
  5642. this._computePixels(0, sourceArea, true);
  5643. }
  5644. if (!isBottomAuto) {
  5645. this._computePixels(3, sourceArea, true);
  5646. }
  5647. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  5648. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  5649. dstArea.height = height;
  5650. dstOffset.w = sourceArea.height - (dstOffset.y + height);
  5651. break;
  5652. }
  5653. }
  5654. };
  5655. /**
  5656. * Compute an area and its position considering this thickness properties based on a given source area
  5657. * @param sourceArea the source area
  5658. * @param dstOffset the position of the resulting area
  5659. * @param dstArea the size of the resulting area
  5660. */
  5661. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  5662. this._computePixels(0, sourceArea, true);
  5663. this._computePixels(1, sourceArea, true);
  5664. this._computePixels(2, sourceArea, true);
  5665. this._computePixels(3, sourceArea, true);
  5666. dstOffset.x = this.leftPixels;
  5667. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  5668. dstOffset.y = this.bottomPixels;
  5669. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  5670. dstOffset.z = this.rightPixels;
  5671. dstOffset.w = this.topPixels;
  5672. };
  5673. /**
  5674. * Compute an area considering this thickness properties based on a given source area
  5675. * @param sourceArea the source area
  5676. * @param result the resulting area
  5677. */
  5678. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  5679. this._computePixels(0, sourceArea, true);
  5680. this._computePixels(1, sourceArea, true);
  5681. this._computePixels(2, sourceArea, true);
  5682. this._computePixels(3, sourceArea, true);
  5683. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  5684. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  5685. };
  5686. PrimitiveThickness.prototype.enlarge = function (sourceArea, dstOffset, enlargedArea) {
  5687. this._computePixels(0, sourceArea, true);
  5688. this._computePixels(1, sourceArea, true);
  5689. this._computePixels(2, sourceArea, true);
  5690. this._computePixels(3, sourceArea, true);
  5691. dstOffset.x = this.leftPixels;
  5692. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  5693. dstOffset.y = this.bottomPixels;
  5694. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  5695. dstOffset.z = this.rightPixels;
  5696. dstOffset.w = this.topPixels;
  5697. };
  5698. return PrimitiveThickness;
  5699. }());
  5700. PrimitiveThickness.Auto = 0x1;
  5701. PrimitiveThickness.Inherit = 0x2;
  5702. PrimitiveThickness.Percentage = 0x4;
  5703. PrimitiveThickness.Pixel = 0x8;
  5704. PrimitiveThickness = PrimitiveThickness_1 = __decorate([
  5705. BABYLON.className("PrimitiveThickness", "BABYLON")
  5706. ], PrimitiveThickness);
  5707. BABYLON.PrimitiveThickness = PrimitiveThickness;
  5708. /**
  5709. * Main class used for the Primitive Intersection API
  5710. */
  5711. var IntersectInfo2D = (function () {
  5712. function IntersectInfo2D() {
  5713. this.findFirstOnly = false;
  5714. this.intersectHidden = false;
  5715. this.pickPosition = BABYLON.Vector2.Zero();
  5716. }
  5717. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  5718. /**
  5719. * true if at least one primitive intersected during the test
  5720. */
  5721. get: function () {
  5722. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  5723. },
  5724. enumerable: true,
  5725. configurable: true
  5726. });
  5727. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  5728. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  5729. var cur = _a[_i];
  5730. if (cur.prim === prim) {
  5731. return cur.intersectionLocation;
  5732. }
  5733. }
  5734. return null;
  5735. };
  5736. // Internals, don't use
  5737. IntersectInfo2D.prototype._exit = function (firstLevel) {
  5738. if (firstLevel) {
  5739. this._globalPickPosition = null;
  5740. }
  5741. };
  5742. return IntersectInfo2D;
  5743. }());
  5744. BABYLON.IntersectInfo2D = IntersectInfo2D;
  5745. var Prim2DBase = Prim2DBase_1 = (function (_super) {
  5746. __extends(Prim2DBase, _super);
  5747. function Prim2DBase(settings) {
  5748. var _this;
  5749. // Avoid checking every time if the object exists
  5750. if (settings == null) {
  5751. settings = {};
  5752. }
  5753. // BASE CLASS CALL
  5754. _this = _super.call(this) || this;
  5755. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  5756. var owner;
  5757. var parent;
  5758. if (Prim2DBase_1._isCanvasInit) {
  5759. owner = _this;
  5760. parent = null;
  5761. _this._canvasPreInit(settings);
  5762. }
  5763. else {
  5764. if (settings.parent != null) {
  5765. parent = settings.parent;
  5766. owner = settings.parent.owner;
  5767. if (!owner) {
  5768. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  5769. }
  5770. 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)) {
  5771. 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");
  5772. }
  5773. }
  5774. }
  5775. // Fields initialization
  5776. _this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  5777. _this._size = null; //Size.Zero();
  5778. _this._scale = new BABYLON.Vector2(1, 1);
  5779. _this._actualSize = null;
  5780. _this._boundingSize = BABYLON.Size.Zero();
  5781. _this._layoutArea = BABYLON.Size.Zero();
  5782. _this._layoutAreaPos = null;
  5783. _this._layoutBoundingInfo = null;
  5784. _this._marginOffset = BABYLON.Vector4.Zero();
  5785. _this._paddingOffset = BABYLON.Vector4.Zero();
  5786. _this._parentPaddingOffset = BABYLON.Vector2.Zero();
  5787. _this._parentContentArea = BABYLON.Size.Zero();
  5788. _this._lastAutoSizeArea = BABYLON.Size.Zero();
  5789. _this._contentArea = new BABYLON.Size(null, null);
  5790. _this._pointerEventObservable = new BABYLON.Observable();
  5791. _this._owner = owner;
  5792. _this._parent = null;
  5793. _this._margin = null;
  5794. _this._padding = null;
  5795. _this._marginAlignment = null;
  5796. _this._id = settings.id;
  5797. _this._children = new Array();
  5798. _this._localTransform = new BABYLON.Matrix();
  5799. _this._globalTransform = null;
  5800. _this._invGlobalTransform = null;
  5801. _this._globalTransformProcessStep = 0;
  5802. _this._globalTransformStep = 0;
  5803. _this._renderGroup = null;
  5804. _this._primLinearPosition = 0;
  5805. _this._manualZOrder = null;
  5806. _this._zOrder = 0;
  5807. _this._zMax = 0;
  5808. _this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  5809. _this._actualOpacity = 0;
  5810. _this._actualScale = BABYLON.Vector2.Zero();
  5811. _this._displayDebugAreas = false;
  5812. _this._debugAreaGroup = null;
  5813. _this._primTriArray = null;
  5814. _this._primTriArrayDirty = true;
  5815. _this._levelBoundingInfo.worldMatrixAccess = function () { return _this.globalTransform; };
  5816. _this._boundingInfo.worldMatrixAccess = function () { return _this.globalTransform; };
  5817. var isPickable = true;
  5818. var isContainer = true;
  5819. if (settings.isPickable !== undefined) {
  5820. isPickable = settings.isPickable;
  5821. }
  5822. if (settings.isContainer !== undefined) {
  5823. isContainer = settings.isContainer;
  5824. }
  5825. if (settings.dontInheritParentScale) {
  5826. _this._setFlags(BABYLON.SmartPropertyPrim.flagDontInheritParentScale);
  5827. }
  5828. _this._setFlags((isPickable ? BABYLON.SmartPropertyPrim.flagIsPickable : 0) | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty | (isContainer ? BABYLON.SmartPropertyPrim.flagIsContainer : 0) | BABYLON.SmartPropertyPrim.flagActualScaleDirty | BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  5829. if (settings.opacity != null) {
  5830. _this._opacity = settings.opacity;
  5831. }
  5832. else {
  5833. _this._opacity = 1;
  5834. }
  5835. _this._updateRenderMode();
  5836. if (settings.childrenFlatZOrder) {
  5837. _this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  5838. }
  5839. // If the parent is given, initialize the hierarchy/owner related data
  5840. if (parent != null) {
  5841. parent.addChild(_this);
  5842. _this._hierarchyDepth = parent._hierarchyDepth + 1;
  5843. _this._patchHierarchy(parent.owner);
  5844. }
  5845. // If it's a group, detect its own states
  5846. if (_this.owner && _this instanceof BABYLON.Group2D) {
  5847. var group = _this;
  5848. group.detectGroupStates();
  5849. }
  5850. // Time to insert children if some are specified
  5851. if (settings.children != null) {
  5852. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  5853. var child = _a[_i];
  5854. _this.addChild(child);
  5855. // Good time to patch the hierarchy, it won't go very far if there's no need to
  5856. if (_this.owner != null && _this._hierarchyDepth != null) {
  5857. child._patchHierarchy(_this.owner);
  5858. }
  5859. }
  5860. }
  5861. if (settings.zOrder != null) {
  5862. _this.zOrder = settings.zOrder;
  5863. }
  5864. // Set the model related properties
  5865. if (settings.position != null) {
  5866. _this.position = settings.position;
  5867. }
  5868. else if (settings.x != null || settings.y != null) {
  5869. _this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  5870. }
  5871. else {
  5872. _this._position = null;
  5873. }
  5874. _this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  5875. if (settings.scale != null) {
  5876. _this.scale = settings.scale;
  5877. }
  5878. else {
  5879. if (settings.scaleX != null) {
  5880. _this.scaleX = settings.scaleX;
  5881. }
  5882. if (settings.scaleY != null) {
  5883. _this.scaleY = settings.scaleY;
  5884. }
  5885. }
  5886. _this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  5887. _this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  5888. // Layout Engine
  5889. if (settings.layoutEngine != null) {
  5890. if (typeof settings.layoutEngine === "string") {
  5891. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  5892. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  5893. _this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  5894. }
  5895. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  5896. _this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  5897. }
  5898. else if (name_1.indexOf("verticalstackpanel") === 0) {
  5899. _this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  5900. }
  5901. }
  5902. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  5903. _this.layoutEngine = settings.layoutEngine;
  5904. }
  5905. }
  5906. // Set the layout/margin stuffs
  5907. if (settings.marginTop) {
  5908. _this.margin.setTop(settings.marginTop);
  5909. }
  5910. if (settings.marginLeft) {
  5911. _this.margin.setLeft(settings.marginLeft);
  5912. }
  5913. if (settings.marginRight) {
  5914. _this.margin.setRight(settings.marginRight);
  5915. }
  5916. if (settings.marginBottom) {
  5917. _this.margin.setBottom(settings.marginBottom);
  5918. }
  5919. if (settings.margin) {
  5920. if (typeof settings.margin === "string") {
  5921. _this.margin.fromString(settings.margin);
  5922. }
  5923. else {
  5924. _this.margin.fromUniformPixels(settings.margin);
  5925. }
  5926. }
  5927. if (settings.marginHAlignment) {
  5928. _this.marginAlignment.horizontal = settings.marginHAlignment;
  5929. }
  5930. if (settings.marginVAlignment) {
  5931. _this.marginAlignment.vertical = settings.marginVAlignment;
  5932. }
  5933. if (settings.marginAlignment) {
  5934. _this.marginAlignment.fromString(settings.marginAlignment);
  5935. }
  5936. if (settings.paddingTop) {
  5937. _this.padding.setTop(settings.paddingTop);
  5938. }
  5939. if (settings.paddingLeft) {
  5940. _this.padding.setLeft(settings.paddingLeft);
  5941. }
  5942. if (settings.paddingRight) {
  5943. _this.padding.setRight(settings.paddingRight);
  5944. }
  5945. if (settings.paddingBottom) {
  5946. _this.padding.setBottom(settings.paddingBottom);
  5947. }
  5948. if (settings.padding) {
  5949. _this.padding.fromString(settings.padding);
  5950. }
  5951. if (settings.layoutData) {
  5952. var p = _this.parent;
  5953. if (p && p.layoutEngine) {
  5954. p.layoutEngine.newChild(_this, settings.layoutData);
  5955. }
  5956. }
  5957. // Dirty layout and positioning
  5958. _this._parentLayoutDirty();
  5959. _this._positioningDirty();
  5960. // Add in the PCM
  5961. if (settings.levelCollision || settings.deepCollision) {
  5962. _this._actorInfo = _this.owner._primitiveCollisionManager.addActor(_this, settings.deepCollision === true);
  5963. _this._setFlags(BABYLON.SmartPropertyPrim.flagCollisionActor);
  5964. }
  5965. else {
  5966. _this._actorInfo = null;
  5967. }
  5968. return _this;
  5969. }
  5970. Object.defineProperty(Prim2DBase.prototype, "intersectWithObservable", {
  5971. get: function () {
  5972. if (!this._actorInfo) {
  5973. return null;
  5974. }
  5975. return this._actorInfo.intersectWith.dictionaryChanged;
  5976. },
  5977. enumerable: true,
  5978. configurable: true
  5979. });
  5980. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  5981. get: function () {
  5982. if (!this._actionManager) {
  5983. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  5984. }
  5985. return this._actionManager;
  5986. },
  5987. enumerable: true,
  5988. configurable: true
  5989. });
  5990. /**
  5991. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  5992. * @param predicate the predicate to test on each parent
  5993. * @return the first primitive where the predicate was successful
  5994. */
  5995. Prim2DBase.prototype.traverseUp = function (predicate) {
  5996. var p = this;
  5997. while (p != null) {
  5998. if (predicate(p)) {
  5999. return p;
  6000. }
  6001. p = p._parent;
  6002. }
  6003. return null;
  6004. };
  6005. Object.defineProperty(Prim2DBase.prototype, "owner", {
  6006. /**
  6007. * Retrieve the owner Canvas2D
  6008. */
  6009. get: function () {
  6010. return this._owner;
  6011. },
  6012. enumerable: true,
  6013. configurable: true
  6014. });
  6015. Object.defineProperty(Prim2DBase.prototype, "parent", {
  6016. /**
  6017. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  6018. */
  6019. get: function () {
  6020. return this._parent;
  6021. },
  6022. enumerable: true,
  6023. configurable: true
  6024. });
  6025. Object.defineProperty(Prim2DBase.prototype, "children", {
  6026. /**
  6027. * The array of direct children primitives
  6028. */
  6029. get: function () {
  6030. return this._children;
  6031. },
  6032. enumerable: true,
  6033. configurable: true
  6034. });
  6035. Object.defineProperty(Prim2DBase.prototype, "id", {
  6036. /**
  6037. * The identifier of this primitive, may not be unique, it's for information purpose only
  6038. */
  6039. get: function () {
  6040. return this._id;
  6041. },
  6042. set: function (value) {
  6043. if (this._id === value) {
  6044. return;
  6045. }
  6046. var oldValue = this._id;
  6047. this.onPropertyChanged("id", oldValue, this._id);
  6048. },
  6049. enumerable: true,
  6050. configurable: true
  6051. });
  6052. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  6053. get: function () {
  6054. if (this._actualPosition != null) {
  6055. return this._actualPosition;
  6056. }
  6057. if (this._position != null) {
  6058. return this._position;
  6059. }
  6060. // At least return 0,0, we can't return null on actualPosition
  6061. return Prim2DBase_1._nullPosition;
  6062. },
  6063. /**
  6064. * DO NOT INVOKE for internal purpose only
  6065. */
  6066. set: function (val) {
  6067. this._actualPosition = val;
  6068. },
  6069. enumerable: true,
  6070. configurable: true
  6071. });
  6072. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  6073. /**
  6074. * Shortcut to actualPosition.x
  6075. */
  6076. get: function () {
  6077. return this.actualPosition.x;
  6078. },
  6079. set: function (val) {
  6080. this._actualPosition.x = val;
  6081. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualPosition);
  6082. },
  6083. enumerable: true,
  6084. configurable: true
  6085. });
  6086. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  6087. /**
  6088. * Shortcut to actualPosition.y
  6089. */
  6090. get: function () {
  6091. return this.actualPosition.y;
  6092. },
  6093. set: function (val) {
  6094. this._actualPosition.y = val;
  6095. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualPosition);
  6096. },
  6097. enumerable: true,
  6098. configurable: true
  6099. });
  6100. Object.defineProperty(Prim2DBase.prototype, "position", {
  6101. /**
  6102. * Position of the primitive, relative to its parent.
  6103. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  6104. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  6105. * Setting this property may have no effect is specific alignment are in effect.
  6106. */
  6107. get: function () {
  6108. if (!this._position) {
  6109. this._position = BABYLON.Vector2.Zero();
  6110. }
  6111. return this._position;
  6112. },
  6113. set: function (value) {
  6114. if (!this._checkPositionChange()) {
  6115. return;
  6116. }
  6117. this._position = value;
  6118. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
  6119. },
  6120. enumerable: true,
  6121. configurable: true
  6122. });
  6123. Object.defineProperty(Prim2DBase.prototype, "x", {
  6124. /**
  6125. * Direct access to the position.x value of the primitive
  6126. * Use this property when you only want to change one component of the position property
  6127. */
  6128. get: function () {
  6129. if (!this._position) {
  6130. return null;
  6131. }
  6132. return this._position.x;
  6133. },
  6134. set: function (value) {
  6135. if (!this._checkPositionChange()) {
  6136. return;
  6137. }
  6138. if (!this._position) {
  6139. this._position = BABYLON.Vector2.Zero();
  6140. }
  6141. if (this._position.x === value) {
  6142. return;
  6143. }
  6144. this._position.x = value;
  6145. this._triggerPropertyChanged(Prim2DBase_1.positionProperty, value);
  6146. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
  6147. },
  6148. enumerable: true,
  6149. configurable: true
  6150. });
  6151. Object.defineProperty(Prim2DBase.prototype, "y", {
  6152. /**
  6153. * Direct access to the position.y value of the primitive
  6154. * Use this property when you only want to change one component of the position property
  6155. */
  6156. get: function () {
  6157. if (!this._position) {
  6158. return null;
  6159. }
  6160. return this._position.y;
  6161. },
  6162. set: function (value) {
  6163. if (!this._checkPositionChange()) {
  6164. return;
  6165. }
  6166. if (!this._position) {
  6167. this._position = BABYLON.Vector2.Zero();
  6168. }
  6169. if (this._position.y === value) {
  6170. return;
  6171. }
  6172. this._position.y = value;
  6173. this._triggerPropertyChanged(Prim2DBase_1.positionProperty, value);
  6174. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
  6175. },
  6176. enumerable: true,
  6177. configurable: true
  6178. });
  6179. Object.defineProperty(Prim2DBase.prototype, "size", {
  6180. /**
  6181. * Size of the primitive or its bounding area
  6182. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  6183. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  6184. */
  6185. get: function () {
  6186. return this.internalGetSize();
  6187. },
  6188. set: function (value) {
  6189. this.internalSetSize(value);
  6190. },
  6191. enumerable: true,
  6192. configurable: true
  6193. });
  6194. Prim2DBase.prototype.internalGetSize = function () {
  6195. if (!this._size || this._size.width == null || this._size.height == null) {
  6196. if (Prim2DBase_1.boundinbBoxReentrency) {
  6197. return Prim2DBase_1.nullSize;
  6198. }
  6199. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  6200. return this._boundingSize;
  6201. }
  6202. Prim2DBase_1.boundinbBoxReentrency = true;
  6203. var b = this.boundingInfo;
  6204. Prim2DBase_1.boundinbBoxReentrency = false;
  6205. return this._boundingSize;
  6206. }
  6207. return this._size;
  6208. };
  6209. Prim2DBase.prototype.internalSetSize = function (value) {
  6210. this._size = value;
  6211. };
  6212. Object.defineProperty(Prim2DBase.prototype, "width", {
  6213. /**
  6214. * Direct access to the size.width value of the primitive
  6215. * Use this property when you only want to change one component of the size property
  6216. */
  6217. get: function () {
  6218. if (!this.size) {
  6219. return null;
  6220. }
  6221. return this.size.width;
  6222. },
  6223. set: function (value) {
  6224. if (this.size && this.size.width === value) {
  6225. return;
  6226. }
  6227. if (!this.size) {
  6228. this.size = new BABYLON.Size(value, 0);
  6229. }
  6230. else {
  6231. this.size.width = value;
  6232. }
  6233. this._triggerPropertyChanged(Prim2DBase_1.sizeProperty, value);
  6234. this._positioningDirty();
  6235. },
  6236. enumerable: true,
  6237. configurable: true
  6238. });
  6239. Object.defineProperty(Prim2DBase.prototype, "height", {
  6240. /**
  6241. * Direct access to the size.height value of the primitive
  6242. * Use this property when you only want to change one component of the size property
  6243. */
  6244. get: function () {
  6245. if (!this.size) {
  6246. return null;
  6247. }
  6248. return this.size.height;
  6249. },
  6250. set: function (value) {
  6251. if (this.size && this.size.height === value) {
  6252. return;
  6253. }
  6254. if (!this.size) {
  6255. this.size = new BABYLON.Size(0, value);
  6256. }
  6257. else {
  6258. this.size.height = value;
  6259. }
  6260. this._triggerPropertyChanged(Prim2DBase_1.sizeProperty, value);
  6261. this._positioningDirty();
  6262. },
  6263. enumerable: true,
  6264. configurable: true
  6265. });
  6266. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  6267. get: function () {
  6268. return this._rotation;
  6269. },
  6270. set: function (value) {
  6271. this._rotation = value;
  6272. },
  6273. enumerable: true,
  6274. configurable: true
  6275. });
  6276. Object.defineProperty(Prim2DBase.prototype, "scale", {
  6277. get: function () {
  6278. return this._scale.x;
  6279. },
  6280. set: function (value) {
  6281. this._scale.x = this._scale.y = value;
  6282. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  6283. this._spreadActualScaleDirty();
  6284. },
  6285. enumerable: true,
  6286. configurable: true
  6287. });
  6288. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  6289. /**
  6290. * Return the size of the primitive as it's being rendered into the target.
  6291. * This value may be different of the size property when layout/alignment is used or specific primitive types can implement a custom logic through this property.
  6292. * BEWARE: don't use the setter, it's for internal purpose only
  6293. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  6294. */
  6295. get: function () {
  6296. if (this._actualSize) {
  6297. return this._actualSize;
  6298. }
  6299. return this._size;
  6300. },
  6301. set: function (value) {
  6302. if (this._actualSize.equals(value)) {
  6303. return;
  6304. }
  6305. this._actualSize = value;
  6306. },
  6307. enumerable: true,
  6308. configurable: true
  6309. });
  6310. Object.defineProperty(Prim2DBase.prototype, "actualWidth", {
  6311. /**
  6312. * Shortcut to actualSize.width
  6313. */
  6314. get: function () {
  6315. return this.actualSize.width;
  6316. },
  6317. set: function (val) {
  6318. this._actualSize.width = val;
  6319. this._triggerPropertyChanged(Prim2DBase_1.actualSizeProperty, this._actualSize);
  6320. },
  6321. enumerable: true,
  6322. configurable: true
  6323. });
  6324. Object.defineProperty(Prim2DBase.prototype, "actualHeight", {
  6325. /**
  6326. * Shortcut to actualPosition.height
  6327. */
  6328. get: function () {
  6329. return this.actualSize.height;
  6330. },
  6331. set: function (val) {
  6332. this._actualSize.height = val;
  6333. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualSize);
  6334. },
  6335. enumerable: true,
  6336. configurable: true
  6337. });
  6338. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  6339. get: function () {
  6340. if (this._manualZOrder != null) {
  6341. return this._manualZOrder;
  6342. }
  6343. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  6344. this._updateZOrder();
  6345. }
  6346. return (1 - this._zOrder);
  6347. },
  6348. enumerable: true,
  6349. configurable: true
  6350. });
  6351. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  6352. /**
  6353. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  6354. * The Primitive's size won't be less than specified.
  6355. * The default value depends of the Primitive type
  6356. */
  6357. get: function () {
  6358. return this._minSize;
  6359. },
  6360. set: function (value) {
  6361. if (this._minSize && value && this._minSize.equals(value)) {
  6362. return;
  6363. }
  6364. this._minSize = value;
  6365. this._parentLayoutDirty();
  6366. },
  6367. enumerable: true,
  6368. configurable: true
  6369. });
  6370. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  6371. /**
  6372. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  6373. * The Primitive's size won't be more than specified.
  6374. * The default value depends of the Primitive type
  6375. */
  6376. get: function () {
  6377. return this._maxSize;
  6378. },
  6379. set: function (value) {
  6380. if (this._maxSize && value && this._maxSize.equals(value)) {
  6381. return;
  6382. }
  6383. this._maxSize = value;
  6384. this._parentLayoutDirty();
  6385. },
  6386. enumerable: true,
  6387. configurable: true
  6388. });
  6389. Object.defineProperty(Prim2DBase.prototype, "origin", {
  6390. /**
  6391. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  6392. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  6393. * For instance:
  6394. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  6395. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  6396. * 0,1 means the center is top/left
  6397. * @returns The normalized center.
  6398. */
  6399. get: function () {
  6400. return this._origin;
  6401. },
  6402. set: function (value) {
  6403. this._origin = value;
  6404. },
  6405. enumerable: true,
  6406. configurable: true
  6407. });
  6408. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  6409. get: function () {
  6410. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  6411. },
  6412. set: function (value) {
  6413. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  6414. },
  6415. enumerable: true,
  6416. configurable: true
  6417. });
  6418. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  6419. get: function () {
  6420. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  6421. },
  6422. set: function (value) {
  6423. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  6424. },
  6425. enumerable: true,
  6426. configurable: true
  6427. });
  6428. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  6429. get: function () {
  6430. return this._manualZOrder;
  6431. },
  6432. set: function (value) {
  6433. if (this._manualZOrder === value) {
  6434. return;
  6435. }
  6436. this._manualZOrder = value;
  6437. this.onZOrderChanged();
  6438. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  6439. this._actualZOrderChangedObservable.notifyObservers(value);
  6440. }
  6441. },
  6442. enumerable: true,
  6443. configurable: true
  6444. });
  6445. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  6446. get: function () {
  6447. return this._manualZOrder != null;
  6448. },
  6449. enumerable: true,
  6450. configurable: true
  6451. });
  6452. Object.defineProperty(Prim2DBase.prototype, "margin", {
  6453. get: function () {
  6454. var _this = this;
  6455. if (!this._margin) {
  6456. this._margin = new PrimitiveThickness(function () {
  6457. if (!_this.parent) {
  6458. return null;
  6459. }
  6460. return _this.parent.margin;
  6461. }, function () { return _this._positioningDirty(); });
  6462. }
  6463. return this._margin;
  6464. },
  6465. set: function (value) {
  6466. this.margin.copyFrom(value);
  6467. },
  6468. enumerable: true,
  6469. configurable: true
  6470. });
  6471. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  6472. /**
  6473. * Check for both margin and marginAlignment, return true if at least one of them is specified with a non default value
  6474. */
  6475. get: function () {
  6476. return (this._margin !== null && !this._margin.isDefault) || (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  6477. },
  6478. enumerable: true,
  6479. configurable: true
  6480. });
  6481. Object.defineProperty(Prim2DBase.prototype, "padding", {
  6482. get: function () {
  6483. var _this = this;
  6484. if (!this._padding) {
  6485. this._padding = new PrimitiveThickness(function () {
  6486. if (!_this.parent) {
  6487. return null;
  6488. }
  6489. return _this.parent.padding;
  6490. }, function () { return _this._positioningDirty(); });
  6491. }
  6492. return this._padding;
  6493. },
  6494. set: function (value) {
  6495. this.padding.copyFrom(value);
  6496. },
  6497. enumerable: true,
  6498. configurable: true
  6499. });
  6500. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  6501. get: function () {
  6502. return this._padding !== null && !this._padding.isDefault;
  6503. },
  6504. enumerable: true,
  6505. configurable: true
  6506. });
  6507. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  6508. get: function () {
  6509. var _this = this;
  6510. if (!this._marginAlignment) {
  6511. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  6512. }
  6513. return this._marginAlignment;
  6514. },
  6515. set: function (value) {
  6516. this.marginAlignment.copyFrom(value);
  6517. },
  6518. enumerable: true,
  6519. configurable: true
  6520. });
  6521. Object.defineProperty(Prim2DBase.prototype, "_hasMarginAlignment", {
  6522. /**
  6523. * Check if there a marginAlignment specified (non null and not default)
  6524. */
  6525. get: function () {
  6526. return (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  6527. },
  6528. enumerable: true,
  6529. configurable: true
  6530. });
  6531. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  6532. get: function () {
  6533. return this._opacity;
  6534. },
  6535. set: function (value) {
  6536. if (value < 0) {
  6537. value = 0;
  6538. }
  6539. else if (value > 1) {
  6540. value = 1;
  6541. }
  6542. if (this._opacity === value) {
  6543. return;
  6544. }
  6545. this._opacity = value;
  6546. this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  6547. this._spreadActualOpacityChanged();
  6548. this._updateRenderMode();
  6549. },
  6550. enumerable: true,
  6551. configurable: true
  6552. });
  6553. Object.defineProperty(Prim2DBase.prototype, "scaleX", {
  6554. get: function () {
  6555. return this._scale.x;
  6556. },
  6557. set: function (value) {
  6558. this._scale.x = value;
  6559. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  6560. this._spreadActualScaleDirty();
  6561. },
  6562. enumerable: true,
  6563. configurable: true
  6564. });
  6565. Object.defineProperty(Prim2DBase.prototype, "scaleY", {
  6566. get: function () {
  6567. return this._scale.y;
  6568. },
  6569. set: function (value) {
  6570. this._scale.y = value;
  6571. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  6572. this._spreadActualScaleDirty();
  6573. },
  6574. enumerable: true,
  6575. configurable: true
  6576. });
  6577. Prim2DBase.prototype._spreadActualScaleDirty = function () {
  6578. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  6579. var child = _a[_i];
  6580. child._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  6581. child._spreadActualScaleDirty();
  6582. }
  6583. };
  6584. Object.defineProperty(Prim2DBase.prototype, "actualScale", {
  6585. /**
  6586. * 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
  6587. */
  6588. get: function () {
  6589. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualScaleDirty)) {
  6590. var cur = this._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : this.parent;
  6591. var sx = this.scaleX;
  6592. var sy = this.scaleY;
  6593. while (cur) {
  6594. sx *= cur.scaleX;
  6595. sy *= cur.scaleY;
  6596. cur = cur._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : cur.parent;
  6597. }
  6598. this._actualScale.copyFromFloats(sx, sy);
  6599. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  6600. }
  6601. return this._actualScale;
  6602. },
  6603. enumerable: true,
  6604. configurable: true
  6605. });
  6606. Object.defineProperty(Prim2DBase.prototype, "actualScaleX", {
  6607. /**
  6608. * Get the actual Scale of the X axis, shortcut for this.actualScale.x
  6609. */
  6610. get: function () {
  6611. return this.actualScale.x;
  6612. },
  6613. enumerable: true,
  6614. configurable: true
  6615. });
  6616. Object.defineProperty(Prim2DBase.prototype, "actualScaleY", {
  6617. /**
  6618. * Get the actual Scale of the Y axis, shortcut for this.actualScale.y
  6619. */
  6620. get: function () {
  6621. return this.actualScale.y;
  6622. },
  6623. enumerable: true,
  6624. configurable: true
  6625. });
  6626. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  6627. /**
  6628. * Get the actual opacity level, this property is computed from the opacity property, multiplied by the actualOpacity of its parent (if any)
  6629. */
  6630. get: function () {
  6631. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  6632. var cur = this.parent;
  6633. var op = this.opacity;
  6634. while (cur) {
  6635. op *= cur.opacity;
  6636. cur = cur.parent;
  6637. }
  6638. this._actualOpacity = op;
  6639. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  6640. }
  6641. return this._actualOpacity;
  6642. },
  6643. enumerable: true,
  6644. configurable: true
  6645. });
  6646. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  6647. /**
  6648. * Get/set the layout engine to use for this primitive.
  6649. * The default layout engine is the CanvasLayoutEngine.
  6650. */
  6651. get: function () {
  6652. if (!this._layoutEngine) {
  6653. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  6654. }
  6655. return this._layoutEngine;
  6656. },
  6657. set: function (value) {
  6658. if (this._layoutEngine === value) {
  6659. return;
  6660. }
  6661. this._changeLayoutEngine(value);
  6662. },
  6663. enumerable: true,
  6664. configurable: true
  6665. });
  6666. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  6667. /**
  6668. * Get/set the layout are of this primitive.
  6669. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  6670. * The setter should only be called by a Layout Engine class.
  6671. */
  6672. get: function () {
  6673. return this._layoutArea;
  6674. },
  6675. set: function (val) {
  6676. if (this._layoutArea.equals(val)) {
  6677. return;
  6678. }
  6679. this._positioningDirty();
  6680. if (this.parent) {
  6681. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  6682. }
  6683. this._layoutArea = val;
  6684. },
  6685. enumerable: true,
  6686. configurable: true
  6687. });
  6688. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  6689. /**
  6690. * Get/set the layout area position (relative to the parent primitive).
  6691. * The setter should only be called by a Layout Engine class.
  6692. */
  6693. get: function () {
  6694. if (!this._layoutAreaPos) {
  6695. this._layoutAreaPos = BABYLON.Vector2.Zero();
  6696. }
  6697. return this._layoutAreaPos;
  6698. },
  6699. set: function (val) {
  6700. if (this._layoutAreaPos && this._layoutAreaPos.equals(val)) {
  6701. return;
  6702. }
  6703. if (this.parent) {
  6704. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  6705. }
  6706. this._positioningDirty();
  6707. this._layoutAreaPos = val;
  6708. },
  6709. enumerable: true,
  6710. configurable: true
  6711. });
  6712. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  6713. /**
  6714. * Define if the Primitive can be subject to intersection test or not (default is true)
  6715. */
  6716. get: function () {
  6717. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  6718. },
  6719. set: function (value) {
  6720. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  6721. },
  6722. enumerable: true,
  6723. configurable: true
  6724. });
  6725. Object.defineProperty(Prim2DBase.prototype, "isContainer", {
  6726. /**
  6727. * Define if the Primitive acts as a container or not
  6728. * A container will encapsulate its children for interaction event.
  6729. * If it's not a container events will be process down to children if the primitive is not pickable.
  6730. * Default value is true
  6731. */
  6732. get: function () {
  6733. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsContainer);
  6734. },
  6735. set: function (value) {
  6736. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsContainer, value);
  6737. },
  6738. enumerable: true,
  6739. configurable: true
  6740. });
  6741. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  6742. /**
  6743. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  6744. */
  6745. get: function () {
  6746. return this._hierarchyDepth;
  6747. },
  6748. enumerable: true,
  6749. configurable: true
  6750. });
  6751. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  6752. /**
  6753. * Retrieve the Group that is responsible to render this primitive
  6754. */
  6755. get: function () {
  6756. return this._renderGroup;
  6757. },
  6758. enumerable: true,
  6759. configurable: true
  6760. });
  6761. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  6762. /**
  6763. * Get the global transformation matrix of the primitive
  6764. */
  6765. get: function () {
  6766. if (this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  6767. this.updateCachedStates(false);
  6768. }
  6769. return this._globalTransform;
  6770. },
  6771. enumerable: true,
  6772. configurable: true
  6773. });
  6774. /**
  6775. * return the global position of the primitive, relative to its canvas
  6776. */
  6777. Prim2DBase.prototype.getGlobalPosition = function () {
  6778. var v = new BABYLON.Vector2(0, 0);
  6779. this.getGlobalPositionByRef(v);
  6780. return v;
  6781. };
  6782. /**
  6783. * return the global position of the primitive, relative to its canvas
  6784. * @param v the valid Vector2 object where the global position will be stored
  6785. */
  6786. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  6787. v.x = this.globalTransform.m[12];
  6788. v.y = this.globalTransform.m[13];
  6789. };
  6790. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  6791. /**
  6792. * Get invert of the global transformation matrix of the primitive
  6793. */
  6794. get: function () {
  6795. this._updateLocalTransform();
  6796. return this._invGlobalTransform;
  6797. },
  6798. enumerable: true,
  6799. configurable: true
  6800. });
  6801. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  6802. /**
  6803. * Get the local transformation of the primitive
  6804. */
  6805. get: function () {
  6806. this._updateLocalTransform();
  6807. return this._localTransform;
  6808. },
  6809. enumerable: true,
  6810. configurable: true
  6811. });
  6812. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  6813. /**
  6814. * Get the boundingInfo associated to the primitive and its children.
  6815. * The value is supposed to be always up to date
  6816. */
  6817. get: function () {
  6818. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  6819. if (this.owner) {
  6820. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  6821. }
  6822. var sizedByContent = this.isSizedByContent;
  6823. if (sizedByContent) {
  6824. this._boundingInfo.clear();
  6825. }
  6826. else {
  6827. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  6828. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  6829. return this._boundingInfo;
  6830. }
  6831. }
  6832. var bi = this._boundingInfo;
  6833. var tps = new BABYLON.BoundingInfo2D();
  6834. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  6835. var curChild = _a[_i];
  6836. var bb = curChild.boundingInfo;
  6837. bb.transformToRef(curChild.localTransform, tps);
  6838. bi.unionToRef(tps, bi);
  6839. }
  6840. // If the size is determined by the content we have to update the contentArea
  6841. // and compute the size considering the padding (if any)
  6842. if (sizedByContent) {
  6843. bi.maxToRef(Prim2DBase_1._bMax);
  6844. this._contentArea.width = Prim2DBase_1._bMax.x;
  6845. this._contentArea.height = Prim2DBase_1._bMax.y;
  6846. if (this._hasPadding) {
  6847. var padding = this.padding;
  6848. var mm = Prim2DBase_1._bMinMax;
  6849. bi.minMaxToRef(mm);
  6850. mm.z += padding.leftPixels + padding.rightPixels;
  6851. mm.w += padding.bottomPixels + padding.topPixels;
  6852. this._paddingOffset.copyFromFloats(padding.leftPixels, padding.bottomPixels, padding.rightPixels, padding.topPixels);
  6853. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(mm.x, mm.z, mm.y, mm.w, bi);
  6854. }
  6855. }
  6856. this._boundingInfo.sizeToRef(Prim2DBase_1._bSize);
  6857. this._boundingSize.copyFromFloats((!this._size || this._size.width == null) ? Math.ceil(Prim2DBase_1._bSize.width) : this._size.width, (!this._size || this._size.height == null) ? Math.ceil(Prim2DBase_1._bSize.height) : this._size.height);
  6858. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  6859. }
  6860. return this._boundingInfo;
  6861. },
  6862. enumerable: true,
  6863. configurable: true
  6864. });
  6865. Object.defineProperty(Prim2DBase.prototype, "layoutBoundingInfo", {
  6866. /**
  6867. * Get the boundingInfo of the primitive's content arranged by a layout Engine
  6868. * If a particular child is not arranged by layout, it's boundingInfo is used instead to produce something as accurate as possible
  6869. */
  6870. get: function () {
  6871. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty)) {
  6872. if (!this._layoutBoundingInfo) {
  6873. this._layoutBoundingInfo = new BABYLON.BoundingInfo2D();
  6874. }
  6875. if (this.isSizedByContent) {
  6876. this._layoutBoundingInfo.clear();
  6877. }
  6878. else {
  6879. this._layoutBoundingInfo.copyFrom(this.levelBoundingInfo);
  6880. }
  6881. var bi = this._layoutBoundingInfo;
  6882. var tps = new BABYLON.BoundingInfo2D();
  6883. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  6884. var curChild = _a[_i];
  6885. var bb = void 0;
  6886. if (curChild._layoutAreaPos) {
  6887. var s = curChild._layoutArea;
  6888. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(0, s.width, 0, s.height, Prim2DBase_1._tpsBB);
  6889. bb = Prim2DBase_1._tpsBB;
  6890. }
  6891. else {
  6892. bb = curChild.boundingInfo;
  6893. }
  6894. bb.transformToRef(curChild.localTransform, tps);
  6895. bi.unionToRef(tps, bi);
  6896. }
  6897. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  6898. }
  6899. return this._layoutBoundingInfo;
  6900. },
  6901. enumerable: true,
  6902. configurable: true
  6903. });
  6904. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  6905. /**
  6906. * Determine if the size is automatically computed or fixed because manually specified.
  6907. * Use the actualSize property to get the final/real size of the primitive
  6908. * @returns true if the size is automatically computed, false if it were manually specified.
  6909. */
  6910. get: function () {
  6911. return this._size == null;
  6912. },
  6913. enumerable: true,
  6914. configurable: true
  6915. });
  6916. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  6917. /**
  6918. * Return true if this prim has an auto size which is set by the children's global bounding box
  6919. */
  6920. get: function () {
  6921. return (this._size == null) && (this._children.length > 0);
  6922. },
  6923. enumerable: true,
  6924. configurable: true
  6925. });
  6926. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  6927. /**
  6928. * Determine if the position is automatically computed or fixed because manually specified.
  6929. * Use the actualPosition property to get the final/real position of the primitive
  6930. * @returns true if the position is automatically computed, false if it were manually specified.
  6931. */
  6932. get: function () {
  6933. return this._position == null;
  6934. },
  6935. enumerable: true,
  6936. configurable: true
  6937. });
  6938. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  6939. /**
  6940. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  6941. */
  6942. get: function () {
  6943. return this._pointerEventObservable;
  6944. },
  6945. enumerable: true,
  6946. configurable: true
  6947. });
  6948. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  6949. get: function () {
  6950. if (!this._actualZOrderChangedObservable) {
  6951. this._actualZOrderChangedObservable = new BABYLON.Observable();
  6952. }
  6953. return this._actualZOrderChangedObservable;
  6954. },
  6955. enumerable: true,
  6956. configurable: true
  6957. });
  6958. Object.defineProperty(Prim2DBase.prototype, "displayDebugAreas", {
  6959. get: function () {
  6960. return this._displayDebugAreas;
  6961. },
  6962. set: function (value) {
  6963. if (this._displayDebugAreas === value) {
  6964. return;
  6965. }
  6966. if (value === false) {
  6967. this._debugAreaGroup.dispose();
  6968. this._debugAreaGroup = null;
  6969. }
  6970. else {
  6971. var layoutFill = "#F0808040"; // Red - Layout area
  6972. var layoutBorder = "#F08080FF";
  6973. var marginFill = "#F0F04040"; // Yellow - Margin area
  6974. var marginBorder = "#F0F040FF";
  6975. var paddingFill = "#F040F040"; // Magenta - Padding Area
  6976. var paddingBorder = "#F040F0FF";
  6977. var contentFill = "#40F0F040"; // Cyan - Content area
  6978. var contentBorder = "#40F0F0FF";
  6979. var s = new BABYLON.Size(10, 10);
  6980. var p = BABYLON.Vector2.Zero();
  6981. this._debugAreaGroup = new BABYLON.Group2D({ dontInheritParentScale: true,
  6982. parent: (this.parent != null) ? this.parent : this, id: "###DEBUG AREA GROUP###", children: [
  6983. new BABYLON.Group2D({
  6984. id: "###Layout Area###", position: p, size: s, children: [
  6985. new BABYLON.Rectangle2D({ id: "###Layout Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: layoutBorder }),
  6986. new BABYLON.Rectangle2D({ id: "###Layout Top###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  6987. new BABYLON.Rectangle2D({ id: "###Layout Left###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  6988. new BABYLON.Rectangle2D({ id: "###Layout Right###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  6989. new BABYLON.Rectangle2D({ id: "###Layout Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill })
  6990. ]
  6991. }),
  6992. new BABYLON.Group2D({
  6993. id: "###Margin Area###", position: p, size: s, children: [
  6994. new BABYLON.Rectangle2D({ id: "###Margin Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: marginBorder }),
  6995. new BABYLON.Rectangle2D({ id: "###Margin Top###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  6996. new BABYLON.Rectangle2D({ id: "###Margin Left###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  6997. new BABYLON.Rectangle2D({ id: "###Margin Right###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  6998. new BABYLON.Rectangle2D({ id: "###Margin Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill })
  6999. ]
  7000. }),
  7001. new BABYLON.Group2D({
  7002. id: "###Padding Area###", position: p, size: s, children: [
  7003. new BABYLON.Rectangle2D({ id: "###Padding Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: paddingBorder }),
  7004. new BABYLON.Rectangle2D({ id: "###Padding Top###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  7005. new BABYLON.Rectangle2D({ id: "###Padding Left###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  7006. new BABYLON.Rectangle2D({ id: "###Padding Right###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  7007. new BABYLON.Rectangle2D({ id: "###Padding Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill })
  7008. ]
  7009. }),
  7010. new BABYLON.Group2D({
  7011. id: "###Content Area###", position: p, size: s, children: [
  7012. new BABYLON.Rectangle2D({ id: "###Content Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: contentBorder }),
  7013. new BABYLON.Rectangle2D({ id: "###Content Top###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  7014. new BABYLON.Rectangle2D({ id: "###Content Left###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  7015. new BABYLON.Rectangle2D({ id: "###Content Right###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  7016. new BABYLON.Rectangle2D({ id: "###Content Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill })
  7017. ]
  7018. })
  7019. ]
  7020. });
  7021. this._debugAreaGroup._setFlags(BABYLON.SmartPropertyPrim.flagNoPartOfLayout);
  7022. this._updateDebugArea();
  7023. }
  7024. this._displayDebugAreas = value;
  7025. },
  7026. enumerable: true,
  7027. configurable: true
  7028. });
  7029. Prim2DBase.prototype._updateDebugArea = function () {
  7030. var areaNames = ["Layout", "Margin", "Padding", "Content"];
  7031. var areaZones = ["Area", "Frame", "Top", "Left", "Right", "Bottom"];
  7032. var prims = new Array(4);
  7033. // Get all the primitives used to display the areas
  7034. for (var i = 0; i < 4; i++) {
  7035. prims[i] = new Array(6);
  7036. for (var j = 0; j < 6; j++) {
  7037. prims[i][j] = this._debugAreaGroup.findById("###" + areaNames[i] + " " + areaZones[j] + "###");
  7038. if (j > 1) {
  7039. prims[i][j].levelVisible = false;
  7040. }
  7041. }
  7042. }
  7043. // Update the visibility status of layout/margin/padding
  7044. var hasLayout = this._layoutAreaPos != null;
  7045. var hasPos = (this.actualPosition.x !== 0) || (this.actualPosition.y !== 0);
  7046. var hasMargin = this._hasMargin;
  7047. var hasPadding = this._hasPadding;
  7048. prims[0][0].levelVisible = hasLayout;
  7049. prims[1][0].levelVisible = hasMargin;
  7050. prims[2][0].levelVisible = hasPadding;
  7051. prims[3][0].levelVisible = true;
  7052. // Current offset
  7053. var curOffset = BABYLON.Vector2.Zero();
  7054. // Store the area info of the layout area
  7055. var curAreaIndex = 0;
  7056. // Store data about each area
  7057. var areaInfo = new Array(4);
  7058. var storeAreaInfo = function (pos, size) {
  7059. var min = pos.clone();
  7060. var max = pos.clone();
  7061. if (size.width > 0) {
  7062. max.x += size.width;
  7063. }
  7064. if (size.height > 0) {
  7065. max.y += size.height;
  7066. }
  7067. areaInfo[curAreaIndex++] = { off: pos, size: size, min: min, max: max };
  7068. };
  7069. var isCanvas = this instanceof BABYLON.Canvas2D;
  7070. var marginH = this._marginOffset.x + this._marginOffset.z;
  7071. var marginV = this._marginOffset.y + this._marginOffset.w;
  7072. var actualSize = this.actualSize.multiplyByFloats(isCanvas ? 1 : this.scaleX, isCanvas ? 1 : this.scaleY);
  7073. var w = hasLayout ? (this.layoutAreaPos.x + this.layoutArea.width) : (marginH + actualSize.width);
  7074. var h = hasLayout ? (this.layoutAreaPos.y + this.layoutArea.height) : (marginV + actualSize.height);
  7075. var pos = (!hasLayout && !hasMargin && !hasPadding && hasPos) ? this.actualPosition : BABYLON.Vector2.Zero();
  7076. storeAreaInfo(pos, new BABYLON.Size(w, h));
  7077. // Compute the layout related data
  7078. if (hasLayout) {
  7079. var layoutOffset = this.layoutAreaPos.clone();
  7080. storeAreaInfo(layoutOffset, (hasMargin || hasPadding) ? this.layoutArea.clone() : actualSize.clone());
  7081. curOffset = layoutOffset.clone();
  7082. }
  7083. // Compute margin data
  7084. if (hasMargin) {
  7085. var marginOffset = curOffset.clone();
  7086. marginOffset.x += this._marginOffset.x;
  7087. marginOffset.y += this._marginOffset.y;
  7088. var marginArea = actualSize;
  7089. storeAreaInfo(marginOffset, marginArea);
  7090. curOffset = marginOffset.clone();
  7091. }
  7092. if (hasPadding) {
  7093. var contentOffset = curOffset.clone();
  7094. contentOffset.x += this._paddingOffset.x;
  7095. contentOffset.y += this._paddingOffset.y;
  7096. var contentArea = this.contentArea;
  7097. storeAreaInfo(contentOffset, contentArea);
  7098. curOffset = curOffset.add(contentOffset);
  7099. }
  7100. // Helper function that set the pos and size of a given prim
  7101. var setArea = function (i, j, pos, size) {
  7102. prims[i][j].position = pos;
  7103. prims[i][j].size = size;
  7104. };
  7105. var setFullRect = function (i, pos, size) {
  7106. var plist = prims[i];
  7107. plist[2].levelVisible = true;
  7108. plist[3].levelVisible = false;
  7109. plist[4].levelVisible = false;
  7110. plist[5].levelVisible = false;
  7111. setArea(i, 1, pos, size);
  7112. setArea(i, 2, pos, size);
  7113. };
  7114. var setQuadRect = function (i, areaIndex) {
  7115. var plist = prims[i];
  7116. plist[2].levelVisible = true;
  7117. plist[3].levelVisible = true;
  7118. plist[4].levelVisible = true;
  7119. plist[5].levelVisible = true;
  7120. var ca = areaInfo[areaIndex];
  7121. var na = areaInfo[areaIndex + 1];
  7122. var tp = new BABYLON.Vector2(ca.min.x, na.max.y);
  7123. var ts = new BABYLON.Size(ca.size.width, ca.max.y - tp.y);
  7124. var lp = new BABYLON.Vector2(ca.min.x, na.min.y);
  7125. var ls = new BABYLON.Size(na.min.x - ca.min.x, na.max.y - na.min.y);
  7126. var rp = new BABYLON.Vector2(na.max.x, na.min.y);
  7127. var rs = new BABYLON.Size(ca.max.x - na.max.x, na.max.y - na.min.y);
  7128. var bp = new BABYLON.Vector2(ca.min.x, ca.min.y);
  7129. var bs = new BABYLON.Size(ca.size.width, na.min.y - ca.min.y);
  7130. // Frame
  7131. plist[1].position = ca.off;
  7132. plist[1].size = ca.size;
  7133. // Top rect
  7134. plist[2].position = tp;
  7135. plist[2].size = ts;
  7136. // Left rect
  7137. plist[3].position = lp;
  7138. plist[3].size = ls;
  7139. // Right rect
  7140. plist[4].position = rp;
  7141. plist[4].size = rs;
  7142. // Bottom rect
  7143. plist[5].position = bp;
  7144. plist[5].size = bs;
  7145. };
  7146. var areaCount = curAreaIndex;
  7147. curAreaIndex = 0;
  7148. // Available zones
  7149. var availableZones = [false, hasLayout, hasMargin, hasPadding, true];
  7150. for (var k = 1; k < 5; k++) {
  7151. if (availableZones[k]) {
  7152. var ai = areaInfo[curAreaIndex];
  7153. setArea(k - 1, 0, BABYLON.Vector2.Zero(), ai.size);
  7154. // setArea(k-1, 1, Vector2.Zero(), ai.size);
  7155. if (k === 4) {
  7156. setFullRect(k - 1, ai.off, ai.size);
  7157. }
  7158. else {
  7159. setQuadRect(k - 1, curAreaIndex);
  7160. }
  7161. ++curAreaIndex;
  7162. }
  7163. }
  7164. };
  7165. Prim2DBase.prototype.findById = function (id) {
  7166. if (this._id === id) {
  7167. return this;
  7168. }
  7169. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7170. var child = _a[_i];
  7171. var r = child.findById(id);
  7172. if (r != null) {
  7173. return r;
  7174. }
  7175. }
  7176. };
  7177. Prim2DBase.prototype.onZOrderChanged = function () {
  7178. };
  7179. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  7180. return false;
  7181. };
  7182. /**
  7183. * Capture all the Events of the given PointerId for this primitive.
  7184. * Don't forget to call releasePointerEventsCapture when done.
  7185. * @param pointerId the Id of the pointer to capture the events from.
  7186. */
  7187. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  7188. return this.owner._setPointerCapture(pointerId, this);
  7189. };
  7190. /**
  7191. * Release a captured pointer made with setPointerEventCapture.
  7192. * @param pointerId the Id of the pointer to release the capture from.
  7193. */
  7194. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  7195. return this.owner._releasePointerCapture(pointerId, this);
  7196. };
  7197. /**
  7198. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  7199. * @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.
  7200. */
  7201. Prim2DBase.prototype.intersect = function (intersectInfo) {
  7202. if (!intersectInfo) {
  7203. return false;
  7204. }
  7205. // If this is null it means this method is call for the first level, initialize stuffs
  7206. var firstLevel = !intersectInfo._globalPickPosition;
  7207. if (firstLevel) {
  7208. // 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).
  7209. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  7210. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  7211. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  7212. intersectInfo.intersectedPrimitives = new Array();
  7213. intersectInfo.topMostIntersectedPrimitive = null;
  7214. }
  7215. if (!Prim2DBase_1._bypassGroup2DExclusion && this instanceof BABYLON.Group2D && this.isCachedGroup && !this.isRenderableGroup) {
  7216. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  7217. intersectInfo._exit(firstLevel);
  7218. return false;
  7219. }
  7220. if (!intersectInfo.intersectHidden && !this.isVisible) {
  7221. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  7222. intersectInfo._exit(firstLevel);
  7223. return false;
  7224. }
  7225. var id = this.id;
  7226. if (id != null && id.indexOf("__cachedSpriteOfGroup__") === 0) {
  7227. try {
  7228. Prim2DBase_1._bypassGroup2DExclusion = true;
  7229. var ownerGroup = this.getExternalData("__cachedGroup__");
  7230. return ownerGroup.intersect(intersectInfo);
  7231. }
  7232. finally {
  7233. Prim2DBase_1._bypassGroup2DExclusion = false;
  7234. }
  7235. }
  7236. // 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).
  7237. var isIntersectionTest = false;
  7238. if (this instanceof BABYLON.Group2D) {
  7239. var g = this;
  7240. isIntersectionTest = g.isCachedGroup;
  7241. }
  7242. if (isIntersectionTest && !this.levelBoundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  7243. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  7244. intersectInfo._exit(firstLevel);
  7245. return false;
  7246. }
  7247. // Fast rejection test with boundingInfo
  7248. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  7249. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  7250. intersectInfo._exit(firstLevel);
  7251. return false;
  7252. }
  7253. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  7254. var levelIntersectRes = false;
  7255. if (this.isPickable) {
  7256. levelIntersectRes = this.levelIntersect(intersectInfo);
  7257. if (levelIntersectRes) {
  7258. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  7259. intersectInfo.intersectedPrimitives.push(pii);
  7260. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  7261. intersectInfo.topMostIntersectedPrimitive = pii;
  7262. }
  7263. // If we must stop at the first intersection, we're done, quit!
  7264. if (intersectInfo.findFirstOnly) {
  7265. intersectInfo._exit(firstLevel);
  7266. return true;
  7267. }
  7268. }
  7269. }
  7270. // Recurse to children if needed
  7271. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  7272. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7273. var curChild = _a[_i];
  7274. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  7275. if ((!curChild.isPickable && curChild.isContainer) || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  7276. continue;
  7277. }
  7278. // Must compute the localPickLocation for the children level
  7279. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  7280. // If we got an intersection with the child and we only need to find the first one, quit!
  7281. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  7282. intersectInfo._exit(firstLevel);
  7283. return true;
  7284. }
  7285. }
  7286. }
  7287. intersectInfo._exit(firstLevel);
  7288. return intersectInfo.isIntersected;
  7289. };
  7290. Prim2DBase.prototype.intersectOtherPrim = function (other) {
  7291. var setA = this.triList;
  7292. var setB = other.triList;
  7293. return BABYLON.Tri2DArray.doesIntersect(setA, setB, other.globalTransform.multiply(this.globalTransform.clone().invert()));
  7294. };
  7295. Object.defineProperty(Prim2DBase.prototype, "triList", {
  7296. get: function () {
  7297. if (this._primTriArrayDirty) {
  7298. this.updateTriArray();
  7299. this._primTriArrayDirty = false;
  7300. }
  7301. return this._primTriArray;
  7302. },
  7303. enumerable: true,
  7304. configurable: true
  7305. });
  7306. // 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
  7307. Prim2DBase.prototype.updateTriArray = function () {
  7308. if (this._primTriArray == null) {
  7309. this._primTriArray = new BABYLON.Tri2DArray(2);
  7310. }
  7311. else {
  7312. this._primTriArray.clear(2);
  7313. }
  7314. var size = this.actualSize;
  7315. var lb = new BABYLON.Vector2(0, 0);
  7316. var rt = new BABYLON.Vector2(size.width, size.height);
  7317. var lt = new BABYLON.Vector2(0, size.height);
  7318. var rb = new BABYLON.Vector2(size.width, 0);
  7319. this._primTriArray.storeTriangle(0, lb, lt, rt);
  7320. this._primTriArray.storeTriangle(1, lb, rt, rb);
  7321. };
  7322. /**
  7323. * Move a child object into a new position regarding its siblings to change its rendering order.
  7324. * You can also use the shortcut methods to move top/bottom: moveChildToTop, moveChildToBottom, moveToTop, moveToBottom.
  7325. * @param child the object to move
  7326. * @param previous the object which will be before "child", if child has to be the first among sibling, set "previous" to null.
  7327. */
  7328. Prim2DBase.prototype.moveChild = function (child, previous) {
  7329. if (child.parent !== this) {
  7330. return false;
  7331. }
  7332. var childIndex = this._children.indexOf(child);
  7333. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  7334. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  7335. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  7336. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  7337. }
  7338. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  7339. return true;
  7340. };
  7341. /**
  7342. * Move the given child so it's displayed on the top of all its siblings
  7343. * @param child the primitive to move to the top
  7344. */
  7345. Prim2DBase.prototype.moveChildToTop = function (child) {
  7346. return this.moveChild(child, this._children[this._children.length - 1]);
  7347. };
  7348. /**
  7349. * Move the given child so it's displayed on the bottom of all its siblings
  7350. * @param child the primitive to move to the top
  7351. */
  7352. Prim2DBase.prototype.moveChildToBottom = function (child) {
  7353. return this.moveChild(child, null);
  7354. };
  7355. /**
  7356. * Move this primitive to be at the top among all its sibling
  7357. */
  7358. Prim2DBase.prototype.moveToTop = function () {
  7359. if (this.parent == null) {
  7360. return false;
  7361. }
  7362. return this.parent.moveChildToTop(this);
  7363. };
  7364. /**
  7365. * Move this primitive to be at the bottom among all its sibling
  7366. */
  7367. Prim2DBase.prototype.moveToBottom = function () {
  7368. if (this.parent == null) {
  7369. return false;
  7370. }
  7371. return this.parent.moveChildToBottom(this);
  7372. };
  7373. Prim2DBase.prototype.addChild = function (child) {
  7374. child._parent = this;
  7375. this._boundingBoxDirty();
  7376. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  7377. if (flat) {
  7378. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  7379. child._setZOrder(this._zOrder, true);
  7380. child._zMax = this._zOrder;
  7381. }
  7382. else {
  7383. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  7384. }
  7385. var length = this._children.push(child);
  7386. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  7387. };
  7388. /**
  7389. * Dispose the primitive, remove it from its parent.
  7390. */
  7391. Prim2DBase.prototype.dispose = function () {
  7392. if (!_super.prototype.dispose.call(this)) {
  7393. return false;
  7394. }
  7395. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagCollisionActor)) {
  7396. this.owner._primitiveCollisionManager.removeActor(this);
  7397. this._actorInfo = null;
  7398. }
  7399. if (this._pointerEventObservable) {
  7400. this._pointerEventObservable.clear();
  7401. this._pointerEventObservable = null;
  7402. }
  7403. if (this._actionManager) {
  7404. this._actionManager.dispose();
  7405. this._actionManager = null;
  7406. }
  7407. this.owner.scene.stopAnimation(this);
  7408. // If there's a parent, remove this object from its parent list
  7409. if (this._parent) {
  7410. if (this instanceof BABYLON.Group2D) {
  7411. var g = this;
  7412. if (g.isRenderableGroup) {
  7413. var parentRenderable = this.parent.traverseUp(function (p) { return (p instanceof BABYLON.Group2D && p.isRenderableGroup); });
  7414. if (parentRenderable != null) {
  7415. var l = parentRenderable._renderableData._childrenRenderableGroups;
  7416. var i_1 = l.indexOf(g);
  7417. if (i_1 !== -1) {
  7418. l.splice(i_1, 1);
  7419. }
  7420. }
  7421. }
  7422. }
  7423. var i = this._parent._children.indexOf(this);
  7424. if (i !== undefined) {
  7425. this._parent._children.splice(i, 1);
  7426. }
  7427. this._parent = null;
  7428. }
  7429. // Recurse dispose to children
  7430. if (this._children) {
  7431. while (this._children.length > 0) {
  7432. this._children[this._children.length - 1].dispose();
  7433. }
  7434. }
  7435. return true;
  7436. };
  7437. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  7438. if (this._renderGroup && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
  7439. this._renderGroup._addPrimToDirtyList(this);
  7440. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  7441. }
  7442. };
  7443. Prim2DBase.prototype._needPrepare = function () {
  7444. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty | BABYLON.SmartPropertyPrim.flagModelUpdate | BABYLON.SmartPropertyPrim.flagNeedRefresh) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  7445. };
  7446. Prim2DBase.prototype._prepareRender = function (context) {
  7447. this._prepareRenderPre(context);
  7448. this._prepareRenderPost(context);
  7449. };
  7450. Prim2DBase.prototype._prepareRenderPre = function (context) {
  7451. };
  7452. Prim2DBase.prototype._prepareRenderPost = function (context) {
  7453. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  7454. if (this instanceof BABYLON.Group2D) {
  7455. var self = this;
  7456. if (self.isRenderableGroup) {
  7457. return;
  7458. }
  7459. }
  7460. // Check if we need to recurse the prepare to children primitives
  7461. // - must have children
  7462. // - the global transform of this level have changed, or
  7463. // - the visible state of primitive has changed
  7464. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  7465. this.checkPropertiesDirty(Prim2DBase_1.isVisibleProperty.flagId))) {
  7466. this._children.forEach(function (c) {
  7467. // As usual stop the recursion if we meet a renderable group
  7468. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  7469. c._prepareRender(context);
  7470. }
  7471. });
  7472. }
  7473. // Finally reset the dirty flags as we've processed everything
  7474. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  7475. this._instanceDirtyFlags = 0;
  7476. };
  7477. Prim2DBase.prototype._canvasPreInit = function (settings) {
  7478. };
  7479. Prim2DBase.CheckParent = function (parent) {
  7480. //if (!Prim2DBase._isCanvasInit && !parent) {
  7481. // 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)");
  7482. //}
  7483. };
  7484. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  7485. for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
  7486. var cur = list_1[_i];
  7487. cur.updateCachedStates(recurse);
  7488. }
  7489. };
  7490. Prim2DBase.prototype._parentLayoutDirty = function () {
  7491. if (!this._parent || this._parent.isDisposed) {
  7492. return;
  7493. }
  7494. this._parent._setLayoutDirty();
  7495. };
  7496. Prim2DBase.prototype._setLayoutDirty = function () {
  7497. this.onPrimBecomesDirty();
  7498. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  7499. };
  7500. Prim2DBase.prototype._checkPositionChange = function () {
  7501. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  7502. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  7503. return false;
  7504. }
  7505. return true;
  7506. };
  7507. Prim2DBase.prototype._positioningDirty = function () {
  7508. this.onPrimBecomesDirty();
  7509. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  7510. };
  7511. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  7512. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7513. var child = _a[_i];
  7514. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  7515. child._updateRenderMode();
  7516. child.onPrimBecomesDirty();
  7517. child._spreadActualOpacityChanged();
  7518. }
  7519. };
  7520. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  7521. this._layoutEngine = engine;
  7522. };
  7523. Prim2DBase.prototype._updateLocalTransform = function () {
  7524. 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;
  7525. if (this.checkPropertiesDirty(tflags)) {
  7526. if (this.owner) {
  7527. this.owner.addupdateLocalTransformCounter(1);
  7528. }
  7529. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  7530. var local;
  7531. var pos = this._position ? this.position : this.layoutAreaPos;
  7532. if (this._origin.x === 0 && this._origin.y === 0) {
  7533. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale.x, this._scale.y, 1), rot, new BABYLON.Vector3(pos.x + this._marginOffset.x, pos.y + this._marginOffset.y, 0));
  7534. this._localTransform = local;
  7535. }
  7536. else {
  7537. // -Origin offset
  7538. var as = this.actualSize;
  7539. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase_1._t0);
  7540. // -Origin * rotation
  7541. rot.toRotationMatrix(Prim2DBase_1._t1);
  7542. Prim2DBase_1._t0.multiplyToRef(Prim2DBase_1._t1, Prim2DBase_1._t2);
  7543. // -Origin * rotation * scale
  7544. BABYLON.Matrix.ScalingToRef(this._scale.x, this._scale.y, 1, Prim2DBase_1._t0);
  7545. Prim2DBase_1._t2.multiplyToRef(Prim2DBase_1._t0, Prim2DBase_1._t1);
  7546. // -Origin * rotation * scale * (Origin + Position)
  7547. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + pos.x + this._marginOffset.x, (as.height * this._origin.y) + pos.y + this._marginOffset.y, 0, Prim2DBase_1._t2);
  7548. Prim2DBase_1._t1.multiplyToRef(Prim2DBase_1._t2, this._localTransform);
  7549. }
  7550. this.clearPropertiesDirty(tflags);
  7551. this._setFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  7552. return true;
  7553. }
  7554. return false;
  7555. };
  7556. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  7557. if (this.isDisposed) {
  7558. return;
  7559. }
  7560. this.owner.addCachedGroupRenderCounter(1);
  7561. // Check if the parent is synced
  7562. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  7563. this._parent.updateCachedStates(false);
  7564. }
  7565. // Update Z-Order if needed
  7566. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  7567. this._updateZOrder();
  7568. }
  7569. // Update actualSize only if there' not positioning to recompute and the size changed
  7570. // Otherwise positioning will take care of it.
  7571. var sizeDirty = this.checkPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
  7572. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  7573. var size = this.size;
  7574. if (size) {
  7575. if (this.size.width != null) {
  7576. this.actualSize.width = this.size.width;
  7577. }
  7578. if (this.size.height != null) {
  7579. this.actualSize.height = this.size.height;
  7580. }
  7581. this.clearPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
  7582. }
  7583. }
  7584. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  7585. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  7586. // Check for layout update
  7587. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  7588. this.owner.addUpdateLayoutCounter(1);
  7589. this._layoutEngine.updateLayout(this);
  7590. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  7591. }
  7592. var autoContentChanged = false;
  7593. if (this.isSizeAuto) {
  7594. if (!this._lastAutoSizeArea) {
  7595. autoContentChanged = this.actualSize !== null;
  7596. }
  7597. else {
  7598. autoContentChanged = (!this._lastAutoSizeArea.equals(this.actualSize));
  7599. }
  7600. }
  7601. // Check for positioning update
  7602. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  7603. this._updatePositioning();
  7604. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  7605. if (sizeDirty) {
  7606. this.clearPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
  7607. }
  7608. positioningComputed = true;
  7609. }
  7610. if (positioningComputed && this._parent) {
  7611. this._parentContentArea.copyFrom(this._parent.contentArea);
  7612. }
  7613. // Check if we must update this prim
  7614. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  7615. this.owner.addUpdateGlobalTransformCounter(1);
  7616. var curVisibleState = this.isVisible;
  7617. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  7618. // Detect a change of visibility
  7619. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  7620. // Get/compute the localTransform
  7621. var localDirty = this._updateLocalTransform();
  7622. var parentPaddingChanged = false;
  7623. var parentPaddingOffset = Prim2DBase_1._v0;
  7624. if (this._parent) {
  7625. parentPaddingOffset = new BABYLON.Vector2(this._parent._paddingOffset.x, this._parent._paddingOffset.y);
  7626. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  7627. }
  7628. // Check if there are changes in the parent that will force us to update the global matrix
  7629. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  7630. // Check if we have to update the globalTransform
  7631. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged || this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty)) {
  7632. var globalTransform = this._parent ? this._parent._globalTransform : null;
  7633. var localTransform = void 0;
  7634. Prim2DBase_1._transMtx.copyFrom(this._localTransform);
  7635. Prim2DBase_1._transMtx.m[12] += parentPaddingOffset.x;
  7636. Prim2DBase_1._transMtx.m[13] += parentPaddingOffset.y;
  7637. localTransform = Prim2DBase_1._transMtx;
  7638. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  7639. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  7640. this._levelBoundingInfo.dirtyWorldAABB();
  7641. this._boundingInfo.dirtyWorldAABB();
  7642. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  7643. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  7644. this._clearFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  7645. }
  7646. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  7647. }
  7648. if (recurse) {
  7649. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7650. var child = _a[_i];
  7651. // Stop the recursion if we meet a renderable group
  7652. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  7653. }
  7654. }
  7655. };
  7656. Prim2DBase.prototype._updatePositioning = function () {
  7657. if (this.owner) {
  7658. this.owner.addUpdatePositioningCounter(1);
  7659. }
  7660. // From this point we assume that the primitive layoutArea is computed and up to date.
  7661. // We know have to :
  7662. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  7663. // 2. Determine the contentArea based on the padding property.
  7664. var isSizeAuto = this.isSizeAuto;
  7665. // Auto Create PaddingArea if there's no actualSize on width&|height to allocate the whole content available to the paddingArea where the actualSize is null
  7666. if (!this._hasMarginAlignment && (isSizeAuto || (this.actualSize.width == null || this.actualSize.height == null))) {
  7667. if (isSizeAuto || this.actualSize.width == null) {
  7668. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  7669. }
  7670. if (isSizeAuto || this.actualSize.height == null) {
  7671. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  7672. }
  7673. }
  7674. // Apply margin
  7675. if (this._hasMargin) {
  7676. this.margin.computeWithAlignment(this.layoutArea, this.size || this.actualSize, this.marginAlignment, this._marginOffset, Prim2DBase_1._size);
  7677. this.actualSize = Prim2DBase_1._size.clone();
  7678. }
  7679. if (this._hasPadding) {
  7680. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so we resize the primitive itself
  7681. if (isSizeAuto) {
  7682. // Changing the padding has resize the prim, which forces us to recompute margin again
  7683. if (this._hasMargin) {
  7684. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase_1._size, this.marginAlignment, this._marginOffset, Prim2DBase_1._size);
  7685. }
  7686. }
  7687. else {
  7688. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase_1._icZone, Prim2DBase_1._icArea);
  7689. Prim2DBase_1._icArea.width = Math.max(0, Prim2DBase_1._icArea.width);
  7690. Prim2DBase_1._icArea.height = Math.max(0, Prim2DBase_1._icArea.height);
  7691. this.padding.compute(Prim2DBase_1._icArea, this._paddingOffset, Prim2DBase_1._size);
  7692. this._paddingOffset.x += Prim2DBase_1._icZone.x;
  7693. this._paddingOffset.y += Prim2DBase_1._icZone.y;
  7694. this._paddingOffset.z -= Prim2DBase_1._icZone.z;
  7695. this._paddingOffset.w -= Prim2DBase_1._icZone.w;
  7696. this._contentArea.copyFrom(Prim2DBase_1._size);
  7697. }
  7698. }
  7699. else {
  7700. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase_1._icZone, Prim2DBase_1._icArea);
  7701. Prim2DBase_1._icArea.width = Math.max(0, Prim2DBase_1._icArea.width);
  7702. Prim2DBase_1._icArea.height = Math.max(0, Prim2DBase_1._icArea.height);
  7703. this._paddingOffset.x = Prim2DBase_1._icZone.x;
  7704. this._paddingOffset.y = Prim2DBase_1._icZone.y;
  7705. this._paddingOffset.z = Prim2DBase_1._icZone.z;
  7706. this._paddingOffset.w = Prim2DBase_1._icZone.w;
  7707. this._contentArea.copyFrom(Prim2DBase_1._icArea);
  7708. }
  7709. if (!this._position) {
  7710. var aPos = new BABYLON.Vector2(this.layoutAreaPos.x + this._marginOffset.x, this.layoutAreaPos.y + this._marginOffset.y);
  7711. this.actualPosition = aPos;
  7712. }
  7713. if (isSizeAuto) {
  7714. this._lastAutoSizeArea = this.actualSize;
  7715. }
  7716. if (this.displayDebugAreas) {
  7717. this._updateDebugArea();
  7718. }
  7719. };
  7720. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  7721. /**
  7722. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  7723. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  7724. */
  7725. get: function () {
  7726. if (!this._size || this._size.width == null || this._size.height == null) {
  7727. if (Prim2DBase_1.boundinbBoxReentrency) {
  7728. return Prim2DBase_1.nullSize;
  7729. }
  7730. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  7731. return this._boundingSize;
  7732. }
  7733. Prim2DBase_1.boundinbBoxReentrency = true;
  7734. var b = this.boundingInfo;
  7735. Prim2DBase_1.boundinbBoxReentrency = false;
  7736. return this._contentArea;
  7737. }
  7738. else
  7739. // Check for positioning update
  7740. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  7741. this._updatePositioning();
  7742. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  7743. }
  7744. return this._contentArea;
  7745. },
  7746. enumerable: true,
  7747. configurable: true
  7748. });
  7749. Prim2DBase.prototype._patchHierarchy = function (owner) {
  7750. this._owner = owner;
  7751. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  7752. if (this._renderGroup != null) {
  7753. return;
  7754. }
  7755. if (this instanceof BABYLON.Group2D) {
  7756. var group = this;
  7757. group.detectGroupStates();
  7758. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  7759. group.owner._registerTrackedNode(this);
  7760. }
  7761. }
  7762. this._renderGroup = this.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  7763. if (this._parent) {
  7764. this._parentLayoutDirty();
  7765. }
  7766. // Make sure the prim is in the dirtyList if it should be
  7767. if (this._renderGroup && this.isDirty) {
  7768. var list = this._renderGroup._renderableData._primDirtyList;
  7769. var i = list.indexOf(this);
  7770. if (i === -1) {
  7771. list.push(this);
  7772. }
  7773. }
  7774. // Recurse
  7775. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7776. var child = _a[_i];
  7777. child._hierarchyDepth = this._hierarchyDepth + 1;
  7778. child._patchHierarchy(owner);
  7779. }
  7780. };
  7781. Prim2DBase.prototype._updateZOrder = function () {
  7782. var prevLinPos = this._primLinearPosition;
  7783. var startI = 0;
  7784. var startZ = this._zOrder;
  7785. // 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
  7786. var childrenCount = this._children.length;
  7787. if (this._firstZDirtyIndex > 0) {
  7788. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  7789. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  7790. prevLinPos = prevPrim._primLinearPosition;
  7791. startI = this._firstZDirtyIndex - 1;
  7792. startZ = prevPrim._zOrder;
  7793. }
  7794. }
  7795. var startPos = prevLinPos;
  7796. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  7797. Prim2DBase_1._totalCount = 0;
  7798. for (var i = startI; i < childrenCount; i++) {
  7799. var child = this._children[i];
  7800. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  7801. }
  7802. // Compute the new Z-Order for all the primitives
  7803. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  7804. var zDelta = (this._zMax - startZ) / (Prim2DBase_1._totalCount * (Prim2DBase_1._zRebuildReentrency ? 1 : 1.2));
  7805. // 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.
  7806. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  7807. // 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...
  7808. if (Prim2DBase_1._zRebuildReentrency) {
  7809. var p = this._parent;
  7810. if (p == null) {
  7811. // 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...)
  7812. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  7813. Prim2DBase_1._zRebuildReentrency = false;
  7814. return;
  7815. }
  7816. p._firstZDirtyIndex = 0;
  7817. return p._updateZOrder();
  7818. }
  7819. Prim2DBase_1._zRebuildReentrency = true;
  7820. this._firstZDirtyIndex = 0;
  7821. this._updateZOrder();
  7822. Prim2DBase_1._zRebuildReentrency = false;
  7823. }
  7824. for (var i = startI; i < childrenCount; i++) {
  7825. var child = this._children[i];
  7826. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  7827. }
  7828. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  7829. for (var _i = 0, _a = Prim2DBase_1._zOrderChangedNotifList; _i < _a.length; _i++) {
  7830. var p = _a[_i];
  7831. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  7832. }
  7833. Prim2DBase_1._zOrderChangedNotifList.splice(0);
  7834. this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  7835. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  7836. };
  7837. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  7838. if (this.isManualZOrder) {
  7839. return prevLinPos;
  7840. }
  7841. this._primLinearPosition = ++prevLinPos;
  7842. Prim2DBase_1._totalCount++;
  7843. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  7844. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  7845. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7846. var child = _a[_i];
  7847. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  7848. }
  7849. }
  7850. return prevLinPos;
  7851. };
  7852. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  7853. if (this.isManualZOrder) {
  7854. return null;
  7855. }
  7856. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  7857. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  7858. this._setZOrder(newZ, false);
  7859. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  7860. this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  7861. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  7862. }
  7863. var curZ = newZ;
  7864. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  7865. if (isFlat) {
  7866. if (this._children.length > 0) {
  7867. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  7868. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7869. var child = _a[_i];
  7870. child._updatePrimitiveFlatZOrder(this._zOrder);
  7871. }
  7872. }
  7873. }
  7874. else {
  7875. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  7876. var child = _c[_b];
  7877. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  7878. if (r != null) {
  7879. curZ = r;
  7880. }
  7881. }
  7882. }
  7883. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  7884. return curZ;
  7885. };
  7886. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  7887. if (this.isManualZOrder) {
  7888. return;
  7889. }
  7890. this._setZOrder(newZ, false);
  7891. this._zMax = newZ;
  7892. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  7893. this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  7894. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  7895. }
  7896. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7897. var child = _a[_i];
  7898. child._updatePrimitiveFlatZOrder(newZ);
  7899. }
  7900. };
  7901. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  7902. if (newZ !== this._zOrder) {
  7903. this._zOrder = newZ;
  7904. this.onPrimBecomesDirty();
  7905. this.onZOrderChanged();
  7906. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  7907. if (directEmit) {
  7908. this._actualZOrderChangedObservable.notifyObservers(newZ);
  7909. }
  7910. else {
  7911. Prim2DBase_1._zOrderChangedNotifList.push(this);
  7912. }
  7913. }
  7914. }
  7915. };
  7916. Prim2DBase.prototype._updateRenderMode = function () {
  7917. };
  7918. /**
  7919. * This method is used to alter the contentArea of the Primitive before margin is applied.
  7920. * 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.
  7921. * @param primSize the current size of the primitive
  7922. * @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
  7923. * @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!
  7924. */
  7925. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  7926. initialContentArea.copyFrom(primSize);
  7927. initialContentPosition.x = initialContentPosition.y = initialContentPosition.z = initialContentPosition.w = 0;
  7928. };
  7929. /**
  7930. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  7931. * Check the Rectangle2D implementation for a concrete application.
  7932. * @param primSize the current size of the primitive
  7933. * @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!
  7934. */
  7935. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  7936. newPrimSize.copyFrom(primSize);
  7937. };
  7938. return Prim2DBase;
  7939. }(BABYLON.SmartPropertyPrim));
  7940. Prim2DBase.PRIM2DBASE_PROPCOUNT = 25;
  7941. Prim2DBase._bigInt = Math.pow(2, 30);
  7942. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  7943. Prim2DBase.boundinbBoxReentrency = false;
  7944. Prim2DBase.nullSize = BABYLON.Size.Zero();
  7945. Prim2DBase._bMinMax = BABYLON.Vector4.Zero();
  7946. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  7947. Prim2DBase._bSize = BABYLON.Size.Zero();
  7948. Prim2DBase._tpsBB = new BABYLON.BoundingInfo2D();
  7949. Prim2DBase._bypassGroup2DExclusion = false;
  7950. Prim2DBase._isCanvasInit = false;
  7951. Prim2DBase._t0 = new BABYLON.Matrix();
  7952. Prim2DBase._t1 = new BABYLON.Matrix();
  7953. Prim2DBase._t2 = new BABYLON.Matrix();
  7954. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  7955. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  7956. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  7957. Prim2DBase._icZone = BABYLON.Vector4.Zero();
  7958. Prim2DBase._icArea = BABYLON.Size.Zero();
  7959. Prim2DBase._size = BABYLON.Size.Zero();
  7960. Prim2DBase._zOrderChangedNotifList = new Array();
  7961. Prim2DBase._zRebuildReentrency = false;
  7962. Prim2DBase._totalCount = 0;
  7963. __decorate([
  7964. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase_1.actualPositionProperty = pi; }, false, false, true)
  7965. ], Prim2DBase.prototype, "actualPosition", null);
  7966. __decorate([
  7967. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 1, function (pi) { return Prim2DBase_1.actualXProperty = pi; }, false, false, true)
  7968. ], Prim2DBase.prototype, "actualX", null);
  7969. __decorate([
  7970. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 2, function (pi) { return Prim2DBase_1.actualYProperty = pi; }, false, false, true)
  7971. ], Prim2DBase.prototype, "actualY", null);
  7972. __decorate([
  7973. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 3, function (pi) { return Prim2DBase_1.positionProperty = pi; }, false, false, true)
  7974. ], Prim2DBase.prototype, "position", null);
  7975. __decorate([
  7976. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 4, function (pi) { return Prim2DBase_1.xProperty = pi; }, false, false, true)
  7977. ], Prim2DBase.prototype, "x", null);
  7978. __decorate([
  7979. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 5, function (pi) { return Prim2DBase_1.yProperty = pi; }, false, false, true)
  7980. ], Prim2DBase.prototype, "y", null);
  7981. __decorate([
  7982. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 6, function (pi) { return Prim2DBase_1.sizeProperty = pi; }, false, true)
  7983. ], Prim2DBase.prototype, "size", null);
  7984. __decorate([
  7985. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 7, function (pi) { return Prim2DBase_1.widthProperty = pi; }, false, true)
  7986. ], Prim2DBase.prototype, "width", null);
  7987. __decorate([
  7988. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 8, function (pi) { return Prim2DBase_1.heightProperty = pi; }, false, true)
  7989. ], Prim2DBase.prototype, "height", null);
  7990. __decorate([
  7991. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 9, function (pi) { return Prim2DBase_1.rotationProperty = pi; }, false, true)
  7992. ], Prim2DBase.prototype, "rotation", null);
  7993. __decorate([
  7994. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 10, function (pi) { return Prim2DBase_1.scaleProperty = pi; }, false, true)
  7995. ], Prim2DBase.prototype, "scale", null);
  7996. __decorate([
  7997. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 11, function (pi) { return Prim2DBase_1.actualSizeProperty = pi; }, false, true)
  7998. ], Prim2DBase.prototype, "actualSize", null);
  7999. __decorate([
  8000. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 12, function (pi) { return Prim2DBase_1.actualWidthProperty = pi; }, false, true)
  8001. ], Prim2DBase.prototype, "actualWidth", null);
  8002. __decorate([
  8003. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 13, function (pi) { return Prim2DBase_1.actualHeightProperty = pi; }, false, true)
  8004. ], Prim2DBase.prototype, "actualHeight", null);
  8005. __decorate([
  8006. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 14, function (pi) { return Prim2DBase_1.originProperty = pi; }, false, true)
  8007. ], Prim2DBase.prototype, "origin", null);
  8008. __decorate([
  8009. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 15, function (pi) { return Prim2DBase_1.levelVisibleProperty = pi; })
  8010. ], Prim2DBase.prototype, "levelVisible", null);
  8011. __decorate([
  8012. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 16, function (pi) { return Prim2DBase_1.isVisibleProperty = pi; })
  8013. ], Prim2DBase.prototype, "isVisible", null);
  8014. __decorate([
  8015. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 17, function (pi) { return Prim2DBase_1.zOrderProperty = pi; })
  8016. ], Prim2DBase.prototype, "zOrder", null);
  8017. __decorate([
  8018. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 18, function (pi) { return Prim2DBase_1.marginProperty = pi; })
  8019. ], Prim2DBase.prototype, "margin", null);
  8020. __decorate([
  8021. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 19, function (pi) { return Prim2DBase_1.paddingProperty = pi; })
  8022. ], Prim2DBase.prototype, "padding", null);
  8023. __decorate([
  8024. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 20, function (pi) { return Prim2DBase_1.marginAlignmentProperty = pi; })
  8025. ], Prim2DBase.prototype, "marginAlignment", null);
  8026. __decorate([
  8027. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 21, function (pi) { return Prim2DBase_1.opacityProperty = pi; })
  8028. ], Prim2DBase.prototype, "opacity", null);
  8029. __decorate([
  8030. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 22, function (pi) { return Prim2DBase_1.scaleXProperty = pi; }, false, true)
  8031. ], Prim2DBase.prototype, "scaleX", null);
  8032. __decorate([
  8033. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 23, function (pi) { return Prim2DBase_1.scaleYProperty = pi; }, false, true)
  8034. ], Prim2DBase.prototype, "scaleY", null);
  8035. __decorate([
  8036. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 24, function (pi) { return Prim2DBase_1.actualScaleProperty = pi; }, false, true)
  8037. ], Prim2DBase.prototype, "actualScale", null);
  8038. Prim2DBase = Prim2DBase_1 = __decorate([
  8039. BABYLON.className("Prim2DBase", "BABYLON")
  8040. ], Prim2DBase);
  8041. BABYLON.Prim2DBase = Prim2DBase;
  8042. var PrimitiveAlignment_1, PrimitiveThickness_1, Prim2DBase_1;
  8043. })(BABYLON || (BABYLON = {}));
  8044. //# sourceMappingURL=babylon.prim2dBase.js.map
  8045. var __extends = (this && this.__extends) || function (d, b) {
  8046. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8047. function __() { this.constructor = d; }
  8048. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  8049. };
  8050. var BABYLON;
  8051. (function (BABYLON) {
  8052. var GroupInstanceInfo = (function () {
  8053. function GroupInstanceInfo(owner, mrc, partCount) {
  8054. this._partCount = partCount;
  8055. this.owner = owner;
  8056. this.modelRenderCache = mrc;
  8057. this.modelRenderCache.addRef();
  8058. this.partIndexFromId = new BABYLON.StringDictionary();
  8059. this._usedShaderCategories = new Array(partCount);
  8060. this._strides = new Array(partCount);
  8061. this._opaqueData = null;
  8062. this._alphaTestData = null;
  8063. this._transparentData = null;
  8064. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  8065. }
  8066. GroupInstanceInfo.prototype.dispose = function () {
  8067. if (this._isDisposed) {
  8068. return false;
  8069. }
  8070. if (this.modelRenderCache) {
  8071. this.modelRenderCache.dispose();
  8072. this.modelRenderCache = null;
  8073. }
  8074. var engine = this.owner.owner.engine;
  8075. if (this._opaqueData) {
  8076. this._opaqueData.forEach(function (d) { return d.dispose(engine); });
  8077. this._opaqueData = null;
  8078. }
  8079. if (this._alphaTestData) {
  8080. this._alphaTestData.forEach(function (d) { return d.dispose(engine); });
  8081. this._alphaTestData = null;
  8082. }
  8083. if (this._transparentData) {
  8084. this._transparentData.forEach(function (d) { return d.dispose(engine); });
  8085. this._transparentData = null;
  8086. }
  8087. this.partIndexFromId = null;
  8088. this._isDisposed = true;
  8089. return true;
  8090. };
  8091. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  8092. get: function () {
  8093. return this._opaqueData != null;
  8094. },
  8095. enumerable: true,
  8096. configurable: true
  8097. });
  8098. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  8099. get: function () {
  8100. return this._alphaTestData != null;
  8101. },
  8102. enumerable: true,
  8103. configurable: true
  8104. });
  8105. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  8106. get: function () {
  8107. return this._transparentData != null;
  8108. },
  8109. enumerable: true,
  8110. configurable: true
  8111. });
  8112. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  8113. get: function () {
  8114. if (!this._opaqueData) {
  8115. this._opaqueData = new Array(this._partCount);
  8116. for (var i = 0; i < this._partCount; i++) {
  8117. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  8118. }
  8119. }
  8120. return this._opaqueData;
  8121. },
  8122. enumerable: true,
  8123. configurable: true
  8124. });
  8125. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  8126. get: function () {
  8127. if (!this._alphaTestData) {
  8128. this._alphaTestData = new Array(this._partCount);
  8129. for (var i = 0; i < this._partCount; i++) {
  8130. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  8131. }
  8132. }
  8133. return this._alphaTestData;
  8134. },
  8135. enumerable: true,
  8136. configurable: true
  8137. });
  8138. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  8139. get: function () {
  8140. if (!this._transparentData) {
  8141. this._transparentData = new Array(this._partCount);
  8142. for (var i = 0; i < this._partCount; i++) {
  8143. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  8144. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  8145. }
  8146. }
  8147. return this._transparentData;
  8148. },
  8149. enumerable: true,
  8150. configurable: true
  8151. });
  8152. GroupInstanceInfo.prototype.sortTransparentData = function () {
  8153. if (!this.transparentOrderDirty) {
  8154. return;
  8155. }
  8156. for (var i = 0; i < this._transparentData.length; i++) {
  8157. var td = this._transparentData[i];
  8158. td._partData.sort();
  8159. }
  8160. this.transparentOrderDirty = false;
  8161. };
  8162. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  8163. get: function () {
  8164. return this._usedShaderCategories;
  8165. },
  8166. enumerable: true,
  8167. configurable: true
  8168. });
  8169. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  8170. get: function () {
  8171. return this._strides;
  8172. },
  8173. enumerable: true,
  8174. configurable: true
  8175. });
  8176. return GroupInstanceInfo;
  8177. }());
  8178. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  8179. var TransparentSegment = (function () {
  8180. function TransparentSegment() {
  8181. this.groupInsanceInfo = null;
  8182. this.startZ = 0;
  8183. this.endZ = 0;
  8184. this.startDataIndex = BABYLON.Prim2DBase._bigInt;
  8185. this.endDataIndex = 0;
  8186. this.partBuffers = null;
  8187. }
  8188. TransparentSegment.prototype.dispose = function (engine) {
  8189. if (this.partBuffers) {
  8190. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  8191. this.partBuffers.splice(0);
  8192. this.partBuffers = null;
  8193. }
  8194. };
  8195. return TransparentSegment;
  8196. }());
  8197. BABYLON.TransparentSegment = TransparentSegment;
  8198. var GroupInfoPartData = (function () {
  8199. function GroupInfoPartData(stride) {
  8200. this._partData = null;
  8201. this._partBuffer = null;
  8202. this._partBufferSize = 0;
  8203. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  8204. this._isDisposed = false;
  8205. }
  8206. GroupInfoPartData.prototype.dispose = function (engine) {
  8207. if (this._isDisposed) {
  8208. return false;
  8209. }
  8210. if (this._partBuffer) {
  8211. engine._releaseBuffer(this._partBuffer);
  8212. this._partBuffer = null;
  8213. }
  8214. this._partData = null;
  8215. this._isDisposed = true;
  8216. };
  8217. return GroupInfoPartData;
  8218. }());
  8219. BABYLON.GroupInfoPartData = GroupInfoPartData;
  8220. var TransparentGroupInfoPartData = (function (_super) {
  8221. __extends(TransparentGroupInfoPartData, _super);
  8222. function TransparentGroupInfoPartData(stride, zoff) {
  8223. var _this = _super.call(this, stride) || this;
  8224. _this._partData.compareValueOffset = zoff;
  8225. _this._partData.sortingAscending = false;
  8226. return _this;
  8227. }
  8228. return TransparentGroupInfoPartData;
  8229. }(GroupInfoPartData));
  8230. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  8231. var ModelRenderCache = (function () {
  8232. function ModelRenderCache(engine, modelKey) {
  8233. this._engine = engine;
  8234. this._modelKey = modelKey;
  8235. this._nextKey = 1;
  8236. this._refCounter = 1;
  8237. this._partData = null;
  8238. }
  8239. ModelRenderCache.prototype.dispose = function () {
  8240. if (--this._refCounter !== 0) {
  8241. return false;
  8242. }
  8243. // Remove the Model Render Cache from the global dictionary
  8244. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  8245. if (edata) {
  8246. edata.DisposeModelRenderCache(this);
  8247. }
  8248. return true;
  8249. };
  8250. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  8251. get: function () {
  8252. return this._refCounter <= 0;
  8253. },
  8254. enumerable: true,
  8255. configurable: true
  8256. });
  8257. ModelRenderCache.prototype.addRef = function () {
  8258. return ++this._refCounter;
  8259. };
  8260. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  8261. get: function () {
  8262. return this._modelKey;
  8263. },
  8264. enumerable: true,
  8265. configurable: true
  8266. });
  8267. ModelRenderCache.prototype.updateModelRenderCache = function (prim) {
  8268. return false;
  8269. };
  8270. /**
  8271. * Render the model instances
  8272. * @param instanceInfo
  8273. * @param context
  8274. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  8275. */
  8276. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  8277. return true;
  8278. };
  8279. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  8280. for (var i = 0; i < this._partData.length; i++) {
  8281. if (this._partData[i]._partId === partId) {
  8282. return i;
  8283. }
  8284. }
  8285. return null;
  8286. };
  8287. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  8288. var i = this.getPartIndexFromId(partId);
  8289. if (i === null) {
  8290. return null;
  8291. }
  8292. var ci = this._partsClassInfo[i];
  8293. var categories = this._partData[i]._partUsedCategories;
  8294. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  8295. return res;
  8296. };
  8297. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  8298. var pd = this._partData[partIndex];
  8299. var offset = (pd._partDataStride / 4) * elementCount;
  8300. var pci = this._partsClassInfo[partIndex];
  8301. var self = this;
  8302. pci.fullContent.forEach(function (k, v) {
  8303. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  8304. switch (v.dataType) {
  8305. case 4 /* float */:
  8306. {
  8307. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  8308. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  8309. break;
  8310. }
  8311. case 0 /* Vector2 */:
  8312. {
  8313. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  8314. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  8315. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  8316. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  8317. break;
  8318. }
  8319. case 5 /* Color3 */:
  8320. case 1 /* Vector3 */:
  8321. {
  8322. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  8323. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  8324. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  8325. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  8326. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  8327. break;
  8328. }
  8329. case 6 /* Color4 */:
  8330. case 2 /* Vector4 */:
  8331. {
  8332. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  8333. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  8334. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  8335. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  8336. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  8337. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  8338. break;
  8339. }
  8340. default:
  8341. }
  8342. }
  8343. });
  8344. };
  8345. return ModelRenderCache;
  8346. }());
  8347. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  8348. // let i = this.getPartIndexFromId(partId);
  8349. // if (i === null) {
  8350. // return null;
  8351. // }
  8352. // let pci = this._partsClassInfo[i];
  8353. // pci.fullContent.forEach((k, v) => {
  8354. // if (uniforms.indexOf(v.attributeName) !== -1) {
  8355. // v.uniformLocation = effect.getUniform(v.attributeName);
  8356. // }
  8357. // });
  8358. //}
  8359. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  8360. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  8361. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  8362. BABYLON.ModelRenderCache = ModelRenderCache;
  8363. var ModelRenderCachePartData = (function () {
  8364. function ModelRenderCachePartData() {
  8365. }
  8366. return ModelRenderCachePartData;
  8367. }());
  8368. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  8369. })(BABYLON || (BABYLON = {}));
  8370. //# sourceMappingURL=babylon.modelRenderCache.js.map
  8371. var __extends = (this && this.__extends) || function (d, b) {
  8372. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8373. function __() { this.constructor = d; }
  8374. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  8375. };
  8376. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  8377. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  8378. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  8379. 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;
  8380. return c > 3 && r && Object.defineProperty(target, key, r), r;
  8381. };
  8382. var BABYLON;
  8383. (function (BABYLON) {
  8384. var InstanceClassInfo = (function () {
  8385. function InstanceClassInfo(base) {
  8386. this._baseInfo = base;
  8387. this._nextOffset = new BABYLON.StringDictionary();
  8388. this._attributes = new Array();
  8389. }
  8390. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  8391. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  8392. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  8393. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  8394. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  8395. if (push) {
  8396. this._attributes.push(propInfo);
  8397. }
  8398. };
  8399. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  8400. var catInline = ";" + categories.join(";") + ";";
  8401. var res = new Array();
  8402. var curInfo = this;
  8403. while (curInfo) {
  8404. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  8405. var attrib = _a[_i];
  8406. // 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
  8407. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  8408. var index = effect.getAttributeLocationByName(attrib.attributeName);
  8409. if (index === -1) {
  8410. throw new Error("Attribute " + attrib.attributeName + " was not found in Effect: " + effect.name + ". It's certainly no longer used in the Effect's Shaders");
  8411. }
  8412. var iai = new BABYLON.InstancingAttributeInfo();
  8413. iai.index = index;
  8414. 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)
  8415. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  8416. iai.attributeName = attrib.attributeName;
  8417. res.push(iai);
  8418. }
  8419. }
  8420. curInfo = curInfo._baseInfo;
  8421. }
  8422. return res;
  8423. };
  8424. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  8425. var res = new Array();
  8426. var curInfo = this;
  8427. while (curInfo) {
  8428. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  8429. var attrib = _a[_i];
  8430. // 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
  8431. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  8432. res.push(attrib.attributeName);
  8433. }
  8434. }
  8435. curInfo = curInfo._baseInfo;
  8436. }
  8437. return res;
  8438. };
  8439. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  8440. var curOffset = 0;
  8441. var curBase = this._baseInfo;
  8442. while (curBase) {
  8443. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  8444. curBase = curBase._baseInfo;
  8445. }
  8446. return curOffset;
  8447. };
  8448. return InstanceClassInfo;
  8449. }());
  8450. BABYLON.InstanceClassInfo = InstanceClassInfo;
  8451. var InstancePropInfo = (function () {
  8452. function InstancePropInfo() {
  8453. this.instanceOffset = new BABYLON.StringDictionary();
  8454. }
  8455. InstancePropInfo.prototype.setSize = function (val) {
  8456. if (val instanceof BABYLON.Vector2) {
  8457. this.size = 8;
  8458. this.dataType = 0 /* Vector2 */;
  8459. return;
  8460. }
  8461. if (val instanceof BABYLON.Vector3) {
  8462. this.size = 12;
  8463. this.dataType = 1 /* Vector3 */;
  8464. return;
  8465. }
  8466. if (val instanceof BABYLON.Vector4) {
  8467. this.size = 16;
  8468. this.dataType = 2 /* Vector4 */;
  8469. return;
  8470. }
  8471. if (val instanceof BABYLON.Matrix) {
  8472. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  8473. }
  8474. if (typeof (val) === "number") {
  8475. this.size = 4;
  8476. this.dataType = 4 /* float */;
  8477. return;
  8478. }
  8479. if (val instanceof BABYLON.Color3) {
  8480. this.size = 12;
  8481. this.dataType = 5 /* Color3 */;
  8482. return;
  8483. }
  8484. if (val instanceof BABYLON.Color4) {
  8485. this.size = 16;
  8486. this.dataType = 6 /* Color4 */;
  8487. return;
  8488. }
  8489. if (val instanceof BABYLON.Size) {
  8490. this.size = 8;
  8491. this.dataType = 7 /* Size */;
  8492. return;
  8493. }
  8494. return;
  8495. };
  8496. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  8497. switch (this.dataType) {
  8498. case 0 /* Vector2 */:
  8499. {
  8500. var v = val;
  8501. array[offset + 0] = v.x;
  8502. array[offset + 1] = v.y;
  8503. break;
  8504. }
  8505. case 1 /* Vector3 */:
  8506. {
  8507. var v = val;
  8508. array[offset + 0] = v.x;
  8509. array[offset + 1] = v.y;
  8510. array[offset + 2] = v.z;
  8511. break;
  8512. }
  8513. case 2 /* Vector4 */:
  8514. {
  8515. var v = val;
  8516. array[offset + 0] = v.x;
  8517. array[offset + 1] = v.y;
  8518. array[offset + 2] = v.z;
  8519. array[offset + 3] = v.w;
  8520. break;
  8521. }
  8522. case 5 /* Color3 */:
  8523. {
  8524. var v = val;
  8525. array[offset + 0] = v.r;
  8526. array[offset + 1] = v.g;
  8527. array[offset + 2] = v.b;
  8528. break;
  8529. }
  8530. case 6 /* Color4 */:
  8531. {
  8532. var v = val;
  8533. array[offset + 0] = v.r;
  8534. array[offset + 1] = v.g;
  8535. array[offset + 2] = v.b;
  8536. array[offset + 3] = v.a;
  8537. break;
  8538. }
  8539. case 4 /* float */:
  8540. {
  8541. var v = val;
  8542. array[offset] = v;
  8543. break;
  8544. }
  8545. case 3 /* Matrix */:
  8546. {
  8547. var v = val;
  8548. for (var i = 0; i < 16; i++) {
  8549. array[offset + i] = v.m[i];
  8550. }
  8551. break;
  8552. }
  8553. case 7 /* Size */:
  8554. {
  8555. var s = val;
  8556. array[offset + 0] = s.width;
  8557. array[offset + 1] = s.height;
  8558. break;
  8559. }
  8560. }
  8561. };
  8562. return InstancePropInfo;
  8563. }());
  8564. BABYLON.InstancePropInfo = InstancePropInfo;
  8565. function instanceData(category, shaderAttributeName) {
  8566. return function (target, propName, descriptor) {
  8567. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  8568. var node = dic.getLevelOf(target);
  8569. var instanceDataName = propName;
  8570. shaderAttributeName = shaderAttributeName || instanceDataName;
  8571. var info = node.levelContent.get(instanceDataName);
  8572. if (info) {
  8573. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  8574. }
  8575. info = new InstancePropInfo();
  8576. info.attributeName = shaderAttributeName;
  8577. info.category = category || null;
  8578. if (info.category) {
  8579. info.delimitedCategory = ";" + info.category + ";";
  8580. }
  8581. node.levelContent.add(instanceDataName, info);
  8582. descriptor.get = function () {
  8583. return null;
  8584. };
  8585. descriptor.set = function (val) {
  8586. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  8587. // Quit if it's the case, otherwise we could overwrite data somewhere...
  8588. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  8589. return;
  8590. }
  8591. if (!info.size) {
  8592. info.setSize(val);
  8593. node.classContent.mapProperty(info, true);
  8594. }
  8595. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  8596. node.classContent.mapProperty(info, false);
  8597. }
  8598. var obj = this;
  8599. if (obj.dataBuffer && obj.dataElements) {
  8600. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  8601. info.writeData(obj.dataBuffer.buffer, offset, val);
  8602. }
  8603. };
  8604. };
  8605. }
  8606. BABYLON.instanceData = instanceData;
  8607. var InstanceDataBase = (function () {
  8608. function InstanceDataBase(partId, dataElementCount) {
  8609. this.id = partId;
  8610. this.curElement = 0;
  8611. this._dataElementCount = dataElementCount;
  8612. this.renderMode = 0;
  8613. this.arrayLengthChanged = false;
  8614. }
  8615. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  8616. get: function () {
  8617. return null;
  8618. },
  8619. set: function (value) {
  8620. },
  8621. enumerable: true,
  8622. configurable: true
  8623. });
  8624. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  8625. get: function () {
  8626. return null;
  8627. },
  8628. set: function (value) {
  8629. },
  8630. enumerable: true,
  8631. configurable: true
  8632. });
  8633. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  8634. get: function () {
  8635. return null;
  8636. },
  8637. set: function (value) {
  8638. },
  8639. enumerable: true,
  8640. configurable: true
  8641. });
  8642. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  8643. get: function () {
  8644. return null;
  8645. },
  8646. set: function (value) {
  8647. },
  8648. enumerable: true,
  8649. configurable: true
  8650. });
  8651. InstanceDataBase.prototype.getClassTreeInfo = function () {
  8652. if (!this.typeInfo) {
  8653. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  8654. }
  8655. return this.typeInfo;
  8656. };
  8657. InstanceDataBase.prototype.allocElements = function () {
  8658. if (!this.dataBuffer || this.dataElements) {
  8659. return;
  8660. }
  8661. var res = new Array(this.dataElementCount);
  8662. for (var i = 0; i < this.dataElementCount; i++) {
  8663. res[i] = this.dataBuffer.allocElement();
  8664. }
  8665. this.dataElements = res;
  8666. };
  8667. InstanceDataBase.prototype.freeElements = function () {
  8668. if (!this.dataElements) {
  8669. return;
  8670. }
  8671. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  8672. var ei = _a[_i];
  8673. this.dataBuffer.freeElement(ei);
  8674. }
  8675. this.dataElements = null;
  8676. };
  8677. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  8678. get: function () {
  8679. return this._dataElementCount;
  8680. },
  8681. set: function (value) {
  8682. if (value === this._dataElementCount) {
  8683. return;
  8684. }
  8685. this.arrayLengthChanged = true;
  8686. this.freeElements();
  8687. this._dataElementCount = value;
  8688. this.allocElements();
  8689. },
  8690. enumerable: true,
  8691. configurable: true
  8692. });
  8693. return InstanceDataBase;
  8694. }());
  8695. __decorate([
  8696. instanceData()
  8697. ], InstanceDataBase.prototype, "zBias", null);
  8698. __decorate([
  8699. instanceData()
  8700. ], InstanceDataBase.prototype, "transformX", null);
  8701. __decorate([
  8702. instanceData()
  8703. ], InstanceDataBase.prototype, "transformY", null);
  8704. __decorate([
  8705. instanceData()
  8706. ], InstanceDataBase.prototype, "opacity", null);
  8707. BABYLON.InstanceDataBase = InstanceDataBase;
  8708. var RenderablePrim2D = RenderablePrim2D_1 = (function (_super) {
  8709. __extends(RenderablePrim2D, _super);
  8710. function RenderablePrim2D(settings) {
  8711. var _this = _super.call(this, settings) || this;
  8712. _this._transparentPrimitiveInfo = null;
  8713. return _this;
  8714. }
  8715. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  8716. get: function () {
  8717. return this._useTextureAlpha() || this._isPrimAlphaTest();
  8718. },
  8719. enumerable: true,
  8720. configurable: true
  8721. });
  8722. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  8723. get: function () {
  8724. return (this.actualOpacity < 1) || this._shouldUseAlphaFromTexture() || this._isPrimTransparent();
  8725. },
  8726. enumerable: true,
  8727. configurable: true
  8728. });
  8729. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  8730. get: function () {
  8731. return this._renderMode;
  8732. },
  8733. enumerable: true,
  8734. configurable: true
  8735. });
  8736. /**
  8737. * Dispose the primitive and its resources, remove it from its parent
  8738. */
  8739. RenderablePrim2D.prototype.dispose = function () {
  8740. if (!_super.prototype.dispose.call(this)) {
  8741. return false;
  8742. }
  8743. if (this.renderGroup) {
  8744. this.renderGroup._setCacheGroupDirty();
  8745. }
  8746. if (this._transparentPrimitiveInfo) {
  8747. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  8748. this._transparentPrimitiveInfo = null;
  8749. }
  8750. if (this._instanceDataParts) {
  8751. this._cleanupInstanceDataParts();
  8752. }
  8753. if (this._modelRenderCache) {
  8754. this._modelRenderCache.dispose();
  8755. this._modelRenderCache = null;
  8756. }
  8757. if (this._instanceDataParts) {
  8758. this._instanceDataParts.forEach(function (p) {
  8759. p.freeElements();
  8760. });
  8761. this._instanceDataParts = null;
  8762. }
  8763. return true;
  8764. };
  8765. RenderablePrim2D.prototype._cleanupInstanceDataParts = function () {
  8766. var gii = null;
  8767. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  8768. var part = _a[_i];
  8769. part.freeElements();
  8770. gii = part.groupInstanceInfo;
  8771. }
  8772. if (gii) {
  8773. var usedCount = 0;
  8774. if (gii.hasOpaqueData) {
  8775. var od = gii.opaqueData[0];
  8776. usedCount += od._partData.usedElementCount;
  8777. gii.opaqueDirty = true;
  8778. }
  8779. if (gii.hasAlphaTestData) {
  8780. var atd = gii.alphaTestData[0];
  8781. usedCount += atd._partData.usedElementCount;
  8782. gii.alphaTestDirty = true;
  8783. }
  8784. if (gii.hasTransparentData) {
  8785. var td = gii.transparentData[0];
  8786. usedCount += td._partData.usedElementCount;
  8787. gii.transparentDirty = true;
  8788. }
  8789. if (usedCount === 0 && gii.modelRenderCache != null) {
  8790. this.renderGroup._renderableData._renderGroupInstancesInfo.remove(gii.modelRenderCache.modelKey);
  8791. gii.dispose();
  8792. }
  8793. if (this._modelRenderCache) {
  8794. this._modelRenderCache.dispose();
  8795. this._modelRenderCache = null;
  8796. }
  8797. }
  8798. this._instanceDataParts = null;
  8799. };
  8800. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  8801. _super.prototype._prepareRenderPre.call(this, context);
  8802. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  8803. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._instanceDataParts) {
  8804. this._cleanupInstanceDataParts();
  8805. }
  8806. // Need to create the model?
  8807. var setupModelRenderCache = false;
  8808. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  8809. setupModelRenderCache = this._createModelRenderCache();
  8810. }
  8811. var gii = null;
  8812. var newInstance = false;
  8813. // Need to create the instance data parts?
  8814. if (!this._instanceDataParts) {
  8815. // Yes, flag it for later, more processing will have to be done
  8816. newInstance = true;
  8817. gii = this._createModelDataParts();
  8818. }
  8819. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  8820. if (setupModelRenderCache) {
  8821. this.setupModelRenderCache(this._modelRenderCache);
  8822. }
  8823. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelUpdate)) {
  8824. if (this._modelRenderCache.updateModelRenderCache(this)) {
  8825. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelUpdate);
  8826. }
  8827. }
  8828. // 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.
  8829. // 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.
  8830. if (this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagNeedRefresh) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep) || this._mustUpdateInstance()) {
  8831. this._updateInstanceDataParts(gii);
  8832. }
  8833. };
  8834. RenderablePrim2D.prototype._createModelRenderCache = function () {
  8835. var _this = this;
  8836. var setupModelRenderCache = false;
  8837. if (this._modelRenderCache) {
  8838. this._modelRenderCache.dispose();
  8839. }
  8840. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  8841. var mrc = _this.createModelRenderCache(key);
  8842. setupModelRenderCache = true;
  8843. return mrc;
  8844. });
  8845. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  8846. // if this is still false it means the MRC already exists, so we add a reference to it
  8847. if (!setupModelRenderCache) {
  8848. this._modelRenderCache.addRef();
  8849. }
  8850. return setupModelRenderCache;
  8851. };
  8852. RenderablePrim2D.prototype._createModelDataParts = function () {
  8853. var _this = this;
  8854. // Create the instance data parts of the primitive and store them
  8855. var parts = this.createInstanceDataParts();
  8856. this._instanceDataParts = parts;
  8857. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  8858. if (!this._modelRenderCache._partData) {
  8859. this._setupModelRenderCache(parts);
  8860. }
  8861. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  8862. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  8863. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  8864. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  8865. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  8866. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  8867. var part = _this._instanceDataParts[j];
  8868. res.partIndexFromId.add(part.id.toString(), j);
  8869. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  8870. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  8871. }
  8872. return res;
  8873. });
  8874. // Get the GroupInfoDataPart corresponding to the render category of the part
  8875. var rm = 0;
  8876. var gipd = null;
  8877. if (this.isTransparent) {
  8878. gipd = gii.transparentData;
  8879. rm = BABYLON.Render2DContext.RenderModeTransparent;
  8880. }
  8881. else if (this.isAlphaTest) {
  8882. gipd = gii.alphaTestData;
  8883. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  8884. }
  8885. else {
  8886. gipd = gii.opaqueData;
  8887. rm = BABYLON.Render2DContext.RenderModeOpaque;
  8888. }
  8889. // For each instance data part of the primitive, allocate the instanced element it needs for render
  8890. for (var i = 0; i < parts.length; i++) {
  8891. var part = parts[i];
  8892. part.dataBuffer = gipd[i]._partData;
  8893. part.allocElements();
  8894. part.renderMode = rm;
  8895. part.groupInstanceInfo = gii;
  8896. }
  8897. return gii;
  8898. };
  8899. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  8900. var ctiArray = new Array();
  8901. this._modelRenderCache._partData = new Array();
  8902. for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
  8903. var dataPart = parts_1[_i];
  8904. var pd = new BABYLON.ModelRenderCachePartData();
  8905. this._modelRenderCache._partData.push(pd);
  8906. var cat = this.getUsedShaderCategories(dataPart);
  8907. var cti = dataPart.getClassTreeInfo();
  8908. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  8909. var curVisible = this.isVisible;
  8910. this.isVisible = true;
  8911. // 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.
  8912. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  8913. var joinCat = ";" + cat.join(";") + ";";
  8914. pd._partJoinedUsedCategories = joinCat;
  8915. InstanceClassInfo._CurCategories = joinCat;
  8916. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  8917. if (!this.refreshInstanceDataPart(dataPart)) {
  8918. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  8919. }
  8920. this.afterRefreshForLayoutConstruction(dataPart, obj);
  8921. this.isVisible = curVisible;
  8922. var size = 0;
  8923. cti.fullContent.forEach(function (k, v) {
  8924. if (!v.category || cat.indexOf(v.category) !== -1) {
  8925. if (v.attributeName === "zBias") {
  8926. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  8927. }
  8928. if (!v.size) {
  8929. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  8930. }
  8931. else {
  8932. size += v.size;
  8933. }
  8934. }
  8935. });
  8936. pd._partDataStride = size;
  8937. pd._partUsedCategories = cat;
  8938. pd._partId = dataPart.id;
  8939. ctiArray.push(cti);
  8940. }
  8941. this._modelRenderCache._partsClassInfo = ctiArray;
  8942. };
  8943. RenderablePrim2D.prototype.onZOrderChanged = function () {
  8944. if (this.isTransparent && this._transparentPrimitiveInfo) {
  8945. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  8946. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  8947. // Flag the transparentData dirty has will have to sort it again
  8948. gii.transparentOrderDirty = true;
  8949. }
  8950. };
  8951. RenderablePrim2D.prototype._mustUpdateInstance = function () {
  8952. return false;
  8953. };
  8954. RenderablePrim2D.prototype._useTextureAlpha = function () {
  8955. return false;
  8956. };
  8957. RenderablePrim2D.prototype._shouldUseAlphaFromTexture = function () {
  8958. return false;
  8959. };
  8960. RenderablePrim2D.prototype._isPrimAlphaTest = function () {
  8961. return false;
  8962. };
  8963. RenderablePrim2D.prototype._isPrimTransparent = function () {
  8964. return false;
  8965. };
  8966. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  8967. // Fetch the GroupInstanceInfo if we don't already have it
  8968. var rd = this.renderGroup._renderableData;
  8969. if (!gii) {
  8970. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  8971. }
  8972. var isTransparent = this.isTransparent;
  8973. var isAlphaTest = this.isAlphaTest;
  8974. var wereTransparent = false;
  8975. // Check a render mode change
  8976. var rmChanged = false;
  8977. if (this._instanceDataParts.length > 0) {
  8978. var firstPart = this._instanceDataParts[0];
  8979. var partRM = firstPart.renderMode;
  8980. var curRM = this.renderMode;
  8981. if (partRM !== curRM) {
  8982. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  8983. rmChanged = true;
  8984. var gipd = void 0;
  8985. switch (curRM) {
  8986. case BABYLON.Render2DContext.RenderModeTransparent:
  8987. gipd = gii.transparentData;
  8988. break;
  8989. case BABYLON.Render2DContext.RenderModeAlphaTest:
  8990. gipd = gii.alphaTestData;
  8991. break;
  8992. default:
  8993. gipd = gii.opaqueData;
  8994. }
  8995. for (var i = 0; i < this._instanceDataParts.length; i++) {
  8996. var part = this._instanceDataParts[i];
  8997. part.freeElements();
  8998. part.dataBuffer = gipd[i]._partData;
  8999. part.renderMode = curRM;
  9000. }
  9001. }
  9002. }
  9003. // Handle changes related to ZOffset
  9004. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  9005. if (isTransparent || wereTransparent) {
  9006. // Handle visibility change, which is also triggered when the primitive just got created
  9007. if (visChanged || rmChanged) {
  9008. if (this.isVisible && !wereTransparent) {
  9009. if (!this._transparentPrimitiveInfo) {
  9010. // Add the primitive to the list of transparent ones in the group that render is
  9011. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  9012. }
  9013. }
  9014. else {
  9015. if (this._transparentPrimitiveInfo) {
  9016. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  9017. this._transparentPrimitiveInfo = null;
  9018. }
  9019. }
  9020. gii.transparentOrderDirty = true;
  9021. }
  9022. }
  9023. var rebuildTrans = false;
  9024. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  9025. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  9026. var part = _a[_i];
  9027. var justAllocated = false;
  9028. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  9029. if (!part.dataElements && (visChanged || rmChanged || this.isVisible)) {
  9030. part.allocElements();
  9031. justAllocated = true;
  9032. }
  9033. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  9034. // Will return false if the instance should not be rendered (not visible or other any reasons)
  9035. part.arrayLengthChanged = false;
  9036. if (!this.refreshInstanceDataPart(part)) {
  9037. // Free the data element
  9038. if (part.dataElements) {
  9039. part.freeElements();
  9040. }
  9041. // The refresh couldn't succeed, push the primitive to be dirty again for the next render
  9042. if (this.isVisible) {
  9043. rd._primNewDirtyList.push(this);
  9044. }
  9045. }
  9046. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  9047. }
  9048. this._instanceDirtyFlags = 0;
  9049. // Make the appropriate data dirty
  9050. if (isTransparent) {
  9051. gii.transparentDirty = true;
  9052. if (rebuildTrans) {
  9053. rd._transparentListChanged = true;
  9054. }
  9055. }
  9056. else if (isAlphaTest) {
  9057. gii.alphaTestDirty = true;
  9058. }
  9059. else {
  9060. gii.opaqueDirty = true;
  9061. }
  9062. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  9063. };
  9064. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  9065. var minOff = BABYLON.Prim2DBase._bigInt;
  9066. var maxOff = 0;
  9067. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  9068. var part = _a[_i];
  9069. if (part && part.dataElements) {
  9070. part.dataBuffer.pack();
  9071. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  9072. var el = _c[_b];
  9073. minOff = Math.min(minOff, el.offset);
  9074. maxOff = Math.max(maxOff, el.offset);
  9075. }
  9076. ts.startDataIndex = Math.min(ts.startDataIndex, minOff / part.dataBuffer.stride);
  9077. ts.endDataIndex = Math.max(ts.endDataIndex, (maxOff / part.dataBuffer.stride) + 1); // +1 for exclusive
  9078. }
  9079. }
  9080. };
  9081. // This internal method is mainly used for transparency processing
  9082. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  9083. var length = this._instanceDataParts.length;
  9084. for (var i = 0; i < length; i++) {
  9085. var part = this._instanceDataParts[i];
  9086. if (part) {
  9087. var stride = part.dataBuffer.stride;
  9088. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  9089. // check if it's the last in the DFA
  9090. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  9091. return null;
  9092. }
  9093. // Return the Z of the next primitive that lies in the DFA
  9094. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  9095. }
  9096. }
  9097. return null;
  9098. };
  9099. // This internal method is mainly used for transparency processing
  9100. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  9101. var length = this._instanceDataParts.length;
  9102. for (var i = 0; i < length; i++) {
  9103. var part = this._instanceDataParts[i];
  9104. if (part) {
  9105. var stride = part.dataBuffer.stride;
  9106. var firstElementOffset = part.dataElements[0].offset;
  9107. // check if it's the first in the DFA
  9108. if (firstElementOffset === 0) {
  9109. return null;
  9110. }
  9111. // Return the Z of the previous primitive that lies in the DFA
  9112. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  9113. }
  9114. }
  9115. return null;
  9116. };
  9117. /**
  9118. * Transform a given point using the Primitive's origin setting.
  9119. * This method requires the Primitive's actualSize to be accurate
  9120. * @param p the point to transform
  9121. * @param originOffset an offset applied on the current origin before performing the transformation. Depending on which frame of reference your data is expressed you may have to apply a offset. (if you data is expressed from the bottom/left, no offset is required. If it's expressed from the center the a [-0.5;-0.5] offset has to be applied.
  9122. * @param res an allocated Vector2 that will receive the transformed content
  9123. */
  9124. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  9125. var actualSize = this.actualSize;
  9126. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  9127. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  9128. };
  9129. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  9130. this.transformPointWithOriginByRef(p, originOffset, res);
  9131. return res;
  9132. };
  9133. /**
  9134. * Get the info for a given effect based on the dataPart metadata
  9135. * @param dataPartId partId in part list to get the info
  9136. * @param vertexBufferAttributes vertex buffer attributes to manually add
  9137. * @param uniforms uniforms to manually add
  9138. * @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
  9139. */
  9140. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, uniforms, useInstanced) {
  9141. if (uniforms === void 0) { uniforms = null; }
  9142. if (useInstanced === void 0) { useInstanced = null; }
  9143. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  9144. if (!dataPart) {
  9145. return null;
  9146. }
  9147. var instancedArray = this.owner.supportInstancedArray;
  9148. if (useInstanced != null) {
  9149. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  9150. if (useInstanced && instancedArray === false) {
  9151. return null;
  9152. }
  9153. // Use the caller's setting
  9154. instancedArray = useInstanced;
  9155. }
  9156. var cti = dataPart.getClassTreeInfo();
  9157. var categories = this.getUsedShaderCategories(dataPart);
  9158. var att = cti.classContent.getShaderAttributes(categories);
  9159. var defines = "";
  9160. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  9161. if (instancedArray) {
  9162. defines += "#define Instanced\n";
  9163. }
  9164. return {
  9165. attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes,
  9166. uniforms: instancedArray ? (uniforms != null ? uniforms : []) : ((uniforms != null) ? att.concat(uniforms) : (att != null ? att : [])),
  9167. defines: defines
  9168. };
  9169. };
  9170. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  9171. get: function () {
  9172. return this._modelRenderCache;
  9173. },
  9174. enumerable: true,
  9175. configurable: true
  9176. });
  9177. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  9178. return null;
  9179. };
  9180. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  9181. };
  9182. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  9183. return null;
  9184. };
  9185. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  9186. return [];
  9187. };
  9188. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  9189. };
  9190. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  9191. };
  9192. RenderablePrim2D.prototype.applyActualScaleOnTransform = function () {
  9193. return true;
  9194. };
  9195. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  9196. if (!this.isVisible) {
  9197. return false;
  9198. }
  9199. part.isVisible = this.isVisible;
  9200. // 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)
  9201. if (part.dataElementCount === 1) {
  9202. part.curElement = 0;
  9203. this.updateInstanceDataPart(part);
  9204. }
  9205. return true;
  9206. };
  9207. /**
  9208. * Update the instanceDataBase level properties of a part
  9209. * @param part the part to update
  9210. * @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).
  9211. */
  9212. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  9213. if (positionOffset === void 0) { positionOffset = null; }
  9214. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform); // Compute the transformation into the renderGroup's space
  9215. var rgScale = this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? RenderablePrim2D_1._uV : this.renderGroup.actualScale; // We still need to apply the scale of the renderGroup to our rendering, so get it.
  9216. var size = this.renderGroup.viewportSize;
  9217. var zBias = this.actualZOffset;
  9218. var offX = 0;
  9219. var offY = 0;
  9220. // If there's an offset, apply the global transformation matrix on it to get a global offset
  9221. if (positionOffset) {
  9222. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  9223. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  9224. }
  9225. // 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
  9226. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  9227. // So for X:
  9228. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  9229. // - 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].
  9230. // At last we don't forget to apply the actualScale of the Render Group to tx[0] and ty[1] to propagate scaling correctly
  9231. var w = size.width;
  9232. var h = size.height;
  9233. var invZBias = 1 / zBias;
  9234. var tx = new BABYLON.Vector4(t.m[0] * rgScale.x * 2 /* / w*/, t.m[4] * rgScale.x * 2 /* / w*/, 0 /*t.m[8]*/, ((t.m[12] + offX) * rgScale.x * 2 / w) - 1);
  9235. var ty = new BABYLON.Vector4(t.m[1] * rgScale.y * 2 /* / h*/, t.m[5] * rgScale.y * 2 /* / h*/, 0 /*t.m[9]*/, ((t.m[13] + offY) * rgScale.y * 2 / h) - 1);
  9236. if (!this.applyActualScaleOnTransform()) {
  9237. t.m[0] = tx.x, t.m[4] = tx.y, t.m[12] = tx.w;
  9238. t.m[1] = ty.x, t.m[5] = ty.y, t.m[13] = ty.w;
  9239. var las = this.actualScale;
  9240. t.decompose(RenderablePrim2D_1._s, RenderablePrim2D_1._r, RenderablePrim2D_1._t);
  9241. var scale = new BABYLON.Vector3(RenderablePrim2D_1._s.x / las.x, RenderablePrim2D_1._s.y / las.y, 1);
  9242. t = BABYLON.Matrix.Compose(scale, RenderablePrim2D_1._r, RenderablePrim2D_1._t);
  9243. tx = new BABYLON.Vector4(t.m[0], t.m[4], 0, t.m[12]);
  9244. ty = new BABYLON.Vector4(t.m[1], t.m[5], 0, t.m[13]);
  9245. }
  9246. tx.x /= w;
  9247. tx.y /= w;
  9248. ty.x /= h;
  9249. ty.y /= h;
  9250. part.transformX = tx;
  9251. part.transformY = ty;
  9252. part.opacity = this.actualOpacity;
  9253. // 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)
  9254. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  9255. };
  9256. RenderablePrim2D.prototype._updateRenderMode = function () {
  9257. if (this.isTransparent) {
  9258. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  9259. }
  9260. else if (this.isAlphaTest) {
  9261. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  9262. }
  9263. else {
  9264. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  9265. }
  9266. };
  9267. return RenderablePrim2D;
  9268. }(BABYLON.Prim2DBase));
  9269. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  9270. RenderablePrim2D._uV = new BABYLON.Vector2(1, 1);
  9271. RenderablePrim2D._s = BABYLON.Vector3.Zero();
  9272. RenderablePrim2D._r = BABYLON.Quaternion.Identity();
  9273. RenderablePrim2D._t = BABYLON.Vector3.Zero();
  9274. RenderablePrim2D._uV3 = new BABYLON.Vector3(1, 1, 1);
  9275. __decorate([
  9276. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D_1.isAlphaTestProperty = pi; })
  9277. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  9278. __decorate([
  9279. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D_1.isTransparentProperty = pi; })
  9280. ], RenderablePrim2D.prototype, "isTransparent", null);
  9281. RenderablePrim2D = RenderablePrim2D_1 = __decorate([
  9282. BABYLON.className("RenderablePrim2D", "BABYLON")
  9283. ], RenderablePrim2D);
  9284. BABYLON.RenderablePrim2D = RenderablePrim2D;
  9285. var RenderablePrim2D_1;
  9286. })(BABYLON || (BABYLON = {}));
  9287. //# sourceMappingURL=babylon.renderablePrim2d.js.map
  9288. var __extends = (this && this.__extends) || function (d, b) {
  9289. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9290. function __() { this.constructor = d; }
  9291. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  9292. };
  9293. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  9294. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  9295. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  9296. 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;
  9297. return c > 3 && r && Object.defineProperty(target, key, r), r;
  9298. };
  9299. var BABYLON;
  9300. (function (BABYLON) {
  9301. var Shape2D = Shape2D_1 = (function (_super) {
  9302. __extends(Shape2D, _super);
  9303. function Shape2D(settings) {
  9304. var _this = _super.call(this, settings) || this;
  9305. if (!settings) {
  9306. settings = {};
  9307. }
  9308. var borderBrush = null;
  9309. if (settings.border) {
  9310. if (typeof (settings.border) === "string") {
  9311. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  9312. }
  9313. else {
  9314. borderBrush = settings.border;
  9315. }
  9316. }
  9317. var fillBrush = null;
  9318. if (settings.fill) {
  9319. if (typeof (settings.fill) === "string") {
  9320. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  9321. }
  9322. else {
  9323. fillBrush = settings.fill;
  9324. }
  9325. }
  9326. _this._isTransparent = false;
  9327. _this._oldTransparent = false;
  9328. _this.border = borderBrush;
  9329. _this.fill = fillBrush;
  9330. _this._updateTransparencyStatus();
  9331. _this.borderThickness = settings.borderThickness;
  9332. return _this;
  9333. }
  9334. Object.defineProperty(Shape2D.prototype, "border", {
  9335. get: function () {
  9336. return this._border;
  9337. },
  9338. set: function (value) {
  9339. this._border = value;
  9340. this._updateTransparencyStatus();
  9341. },
  9342. enumerable: true,
  9343. configurable: true
  9344. });
  9345. Object.defineProperty(Shape2D.prototype, "fill", {
  9346. /**
  9347. * Get/set the brush to render the Fill part of the Primitive
  9348. */
  9349. get: function () {
  9350. return this._fill;
  9351. },
  9352. set: function (value) {
  9353. this._fill = value;
  9354. this._updateTransparencyStatus();
  9355. },
  9356. enumerable: true,
  9357. configurable: true
  9358. });
  9359. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  9360. get: function () {
  9361. return this._borderThickness;
  9362. },
  9363. set: function (value) {
  9364. this._borderThickness = value;
  9365. },
  9366. enumerable: true,
  9367. configurable: true
  9368. });
  9369. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  9370. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  9371. // Fill Part
  9372. if (dataPart.id === Shape2D_1.SHAPE2D_FILLPARTID) {
  9373. var fill = this.fill;
  9374. if (fill instanceof BABYLON.SolidColorBrush2D) {
  9375. cat.push(Shape2D_1.SHAPE2D_CATEGORY_FILLSOLID);
  9376. }
  9377. if (fill instanceof BABYLON.GradientColorBrush2D) {
  9378. cat.push(Shape2D_1.SHAPE2D_CATEGORY_FILLGRADIENT);
  9379. }
  9380. }
  9381. // Border Part
  9382. if (dataPart.id === Shape2D_1.SHAPE2D_BORDERPARTID) {
  9383. cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDER);
  9384. var border = this.border;
  9385. if (border instanceof BABYLON.SolidColorBrush2D) {
  9386. cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDERSOLID);
  9387. }
  9388. if (border instanceof BABYLON.GradientColorBrush2D) {
  9389. cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDERGRADIENT);
  9390. }
  9391. }
  9392. return cat;
  9393. };
  9394. Shape2D.prototype.applyActualScaleOnTransform = function () {
  9395. return false;
  9396. };
  9397. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  9398. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  9399. return false;
  9400. }
  9401. // Fill Part
  9402. if (part.id === Shape2D_1.SHAPE2D_FILLPARTID) {
  9403. var d = part;
  9404. if (this.fill) {
  9405. var fill = this.fill;
  9406. if (fill instanceof BABYLON.SolidColorBrush2D) {
  9407. d.fillSolidColor = fill.color;
  9408. }
  9409. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  9410. d.fillGradientColor1 = fill.color1;
  9411. d.fillGradientColor2 = fill.color2;
  9412. 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));
  9413. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  9414. d.fillGradientTY = ty;
  9415. }
  9416. }
  9417. }
  9418. else if (part.id === Shape2D_1.SHAPE2D_BORDERPARTID) {
  9419. var d = part;
  9420. if (this.border) {
  9421. d.borderThickness = this.borderThickness;
  9422. var border = this.border;
  9423. if (border instanceof BABYLON.SolidColorBrush2D) {
  9424. d.borderSolidColor = border.color;
  9425. }
  9426. else if (border instanceof BABYLON.GradientColorBrush2D) {
  9427. d.borderGradientColor1 = border.color1;
  9428. d.borderGradientColor2 = border.color2;
  9429. 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));
  9430. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  9431. d.borderGradientTY = ty;
  9432. }
  9433. }
  9434. }
  9435. return true;
  9436. };
  9437. Shape2D.prototype._updateTransparencyStatus = function () {
  9438. this._isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  9439. if (this._isTransparent !== this._oldTransparent) {
  9440. this._oldTransparent = this._isTransparent;
  9441. this._updateRenderMode();
  9442. }
  9443. };
  9444. Shape2D.prototype._mustUpdateInstance = function () {
  9445. var res = this._oldTransparent !== this._isTransparent;
  9446. if (res) {
  9447. this._updateRenderMode();
  9448. this._oldTransparent = this._isTransparent;
  9449. }
  9450. return res;
  9451. };
  9452. Shape2D.prototype._isPrimTransparent = function () {
  9453. return this._isTransparent;
  9454. };
  9455. return Shape2D;
  9456. }(BABYLON.RenderablePrim2D));
  9457. Shape2D.SHAPE2D_BORDERPARTID = 1;
  9458. Shape2D.SHAPE2D_FILLPARTID = 2;
  9459. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  9460. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  9461. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  9462. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  9463. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  9464. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  9465. __decorate([
  9466. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D_1.borderProperty = pi; }, true)
  9467. ], Shape2D.prototype, "border", null);
  9468. __decorate([
  9469. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D_1.fillProperty = pi; }, true)
  9470. ], Shape2D.prototype, "fill", null);
  9471. __decorate([
  9472. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D_1.borderThicknessProperty = pi; })
  9473. ], Shape2D.prototype, "borderThickness", null);
  9474. Shape2D = Shape2D_1 = __decorate([
  9475. BABYLON.className("Shape2D", "BABYLON")
  9476. ], Shape2D);
  9477. BABYLON.Shape2D = Shape2D;
  9478. var Shape2DInstanceData = (function (_super) {
  9479. __extends(Shape2DInstanceData, _super);
  9480. function Shape2DInstanceData() {
  9481. return _super.apply(this, arguments) || this;
  9482. }
  9483. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  9484. // FILL ATTRIBUTES
  9485. get: function () {
  9486. return null;
  9487. },
  9488. set: function (value) {
  9489. },
  9490. enumerable: true,
  9491. configurable: true
  9492. });
  9493. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  9494. get: function () {
  9495. return null;
  9496. },
  9497. set: function (value) {
  9498. },
  9499. enumerable: true,
  9500. configurable: true
  9501. });
  9502. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  9503. get: function () {
  9504. return null;
  9505. },
  9506. set: function (value) {
  9507. },
  9508. enumerable: true,
  9509. configurable: true
  9510. });
  9511. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  9512. get: function () {
  9513. return null;
  9514. },
  9515. set: function (value) {
  9516. },
  9517. enumerable: true,
  9518. configurable: true
  9519. });
  9520. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  9521. // BORDER ATTRIBUTES
  9522. get: function () {
  9523. return null;
  9524. },
  9525. set: function (value) {
  9526. },
  9527. enumerable: true,
  9528. configurable: true
  9529. });
  9530. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  9531. get: function () {
  9532. return null;
  9533. },
  9534. set: function (value) {
  9535. },
  9536. enumerable: true,
  9537. configurable: true
  9538. });
  9539. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  9540. get: function () {
  9541. return null;
  9542. },
  9543. set: function (value) {
  9544. },
  9545. enumerable: true,
  9546. configurable: true
  9547. });
  9548. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  9549. get: function () {
  9550. return null;
  9551. },
  9552. set: function (value) {
  9553. },
  9554. enumerable: true,
  9555. configurable: true
  9556. });
  9557. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  9558. get: function () {
  9559. return null;
  9560. },
  9561. set: function (value) {
  9562. },
  9563. enumerable: true,
  9564. configurable: true
  9565. });
  9566. return Shape2DInstanceData;
  9567. }(BABYLON.InstanceDataBase));
  9568. __decorate([
  9569. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  9570. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  9571. __decorate([
  9572. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  9573. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  9574. __decorate([
  9575. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  9576. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  9577. __decorate([
  9578. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  9579. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  9580. __decorate([
  9581. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  9582. ], Shape2DInstanceData.prototype, "borderThickness", null);
  9583. __decorate([
  9584. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  9585. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  9586. __decorate([
  9587. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  9588. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  9589. __decorate([
  9590. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  9591. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  9592. __decorate([
  9593. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  9594. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  9595. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  9596. var Shape2D_1;
  9597. })(BABYLON || (BABYLON = {}));
  9598. //# sourceMappingURL=babylon.shape2d.js.map
  9599. var __extends = (this && this.__extends) || function (d, b) {
  9600. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9601. function __() { this.constructor = d; }
  9602. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  9603. };
  9604. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  9605. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  9606. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  9607. 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;
  9608. return c > 3 && r && Object.defineProperty(target, key, r), r;
  9609. };
  9610. var BABYLON;
  9611. (function (BABYLON) {
  9612. var Group2D = Group2D_1 = (function (_super) {
  9613. __extends(Group2D, _super);
  9614. /**
  9615. * Create an Logical or Renderable Group.
  9616. * @param settings a combination of settings, possible ones are
  9617. * - 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)
  9618. * - children: an array of direct children
  9619. * - id a text identifier, for information purpose
  9620. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  9621. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  9622. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  9623. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  9624. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  9625. * - zOrder: override the zOrder with the specified value
  9626. * - origin: define the normalized origin point location, default [0.5;0.5]
  9627. * - 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.
  9628. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  9629. * - 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).
  9630. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  9631. * - 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.
  9632. * - 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.
  9633. * - 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!
  9634. * - 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.
  9635. * - 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).
  9636. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  9637. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9638. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9639. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9640. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9641. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  9642. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  9643. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  9644. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  9645. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9646. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9647. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9648. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9649. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  9650. */
  9651. function Group2D(settings) {
  9652. var _this;
  9653. if (settings == null) {
  9654. settings = {};
  9655. }
  9656. if (settings.origin == null) {
  9657. settings.origin = new BABYLON.Vector2(0, 0);
  9658. }
  9659. _this = _super.call(this, settings) || this;
  9660. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  9661. _this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  9662. if (_this._trackedNode && _this.owner) {
  9663. _this.owner._registerTrackedNode(_this);
  9664. }
  9665. _this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D_1.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  9666. var rd = _this._renderableData;
  9667. if (rd) {
  9668. rd._noResizeOnScale = (_this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  9669. }
  9670. _this.size = size;
  9671. _this._viewportPosition = BABYLON.Vector2.Zero();
  9672. _this._viewportSize = BABYLON.Size.Zero();
  9673. return _this;
  9674. }
  9675. Group2D._createCachedCanvasGroup = function (owner) {
  9676. 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 });
  9677. return g;
  9678. };
  9679. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  9680. this._bindCacheTarget();
  9681. if (vertexData) {
  9682. var uv = vertexData.uvs;
  9683. var nodeuv = this._renderableData._cacheNodeUVs;
  9684. for (var i = 0; i < 4; i++) {
  9685. uv[i * 2 + 0] = nodeuv[i].x;
  9686. uv[i * 2 + 1] = nodeuv[i].y;
  9687. }
  9688. }
  9689. if (material) {
  9690. material.diffuseTexture = this._renderableData._cacheTexture;
  9691. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  9692. }
  9693. this._renderableData._cacheTexture.hasAlpha = true;
  9694. this._unbindCacheTarget();
  9695. };
  9696. Object.defineProperty(Group2D.prototype, "cachedRect", {
  9697. /**
  9698. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  9699. * 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.
  9700. */
  9701. get: function () {
  9702. if (!this._renderableData) {
  9703. return null;
  9704. }
  9705. return this._renderableData._cacheNode;
  9706. },
  9707. enumerable: true,
  9708. configurable: true
  9709. });
  9710. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  9711. /**
  9712. * The UVs into the MapTexture that map the cached group
  9713. */
  9714. get: function () {
  9715. if (!this._renderableData) {
  9716. return null;
  9717. }
  9718. return this._renderableData._cacheNodeUVs;
  9719. },
  9720. enumerable: true,
  9721. configurable: true
  9722. });
  9723. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  9724. get: function () {
  9725. if (!this._renderableData) {
  9726. return null;
  9727. }
  9728. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  9729. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  9730. }
  9731. return this._renderableData._cacheNodeUVsChangedObservable;
  9732. },
  9733. enumerable: true,
  9734. configurable: true
  9735. });
  9736. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  9737. /**
  9738. * Access the texture that maintains a cached version of the Group2D.
  9739. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  9740. */
  9741. get: function () {
  9742. if (!this._renderableData) {
  9743. return null;
  9744. }
  9745. return this._renderableData._cacheTexture;
  9746. },
  9747. enumerable: true,
  9748. configurable: true
  9749. });
  9750. /**
  9751. * Call this method to remove this Group and its children from the Canvas
  9752. */
  9753. Group2D.prototype.dispose = function () {
  9754. if (!_super.prototype.dispose.call(this)) {
  9755. return false;
  9756. }
  9757. if (this._trackedNode != null) {
  9758. this.owner._unregisterTrackedNode(this);
  9759. this._trackedNode = null;
  9760. }
  9761. if (this._renderableData) {
  9762. this._renderableData.dispose(this.owner);
  9763. this._renderableData = null;
  9764. }
  9765. return true;
  9766. };
  9767. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  9768. /**
  9769. * @returns Returns true if the Group render content, false if it's a logical group only
  9770. */
  9771. get: function () {
  9772. return this._isRenderableGroup;
  9773. },
  9774. enumerable: true,
  9775. configurable: true
  9776. });
  9777. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  9778. /**
  9779. * @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
  9780. */
  9781. get: function () {
  9782. return this._isCachedGroup;
  9783. },
  9784. enumerable: true,
  9785. configurable: true
  9786. });
  9787. Object.defineProperty(Group2D.prototype, "size", {
  9788. get: function () {
  9789. return this._size;
  9790. },
  9791. /**
  9792. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  9793. * 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.
  9794. */
  9795. set: function (val) {
  9796. this._size = val;
  9797. },
  9798. enumerable: true,
  9799. configurable: true
  9800. });
  9801. Object.defineProperty(Group2D.prototype, "viewportSize", {
  9802. get: function () {
  9803. return this._viewportSize;
  9804. },
  9805. enumerable: true,
  9806. configurable: true
  9807. });
  9808. Object.defineProperty(Group2D.prototype, "actualSize", {
  9809. get: function () {
  9810. // The computed size will be floor on both width and height
  9811. var actualSize;
  9812. // Return the actualSize if set
  9813. if (this._actualSize) {
  9814. return this._actualSize;
  9815. }
  9816. // Return the size if set by the user
  9817. if (this._size) {
  9818. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  9819. }
  9820. else {
  9821. var m = this.layoutBoundingInfo.max();
  9822. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  9823. }
  9824. // Compare the size with the one we previously had, if it differs we set the property dirty and trigger a GroupChanged to synchronize a displaySprite (if any)
  9825. if (!actualSize.equals(this._actualSize)) {
  9826. this.onPrimitivePropertyDirty(Group2D_1.actualSizeProperty.flagId);
  9827. this._actualSize = actualSize;
  9828. this.handleGroupChanged(Group2D_1.actualSizeProperty);
  9829. }
  9830. return actualSize;
  9831. },
  9832. set: function (value) {
  9833. this._actualSize = value;
  9834. },
  9835. enumerable: true,
  9836. configurable: true
  9837. });
  9838. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  9839. /**
  9840. * 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.
  9841. * GROUPCACHEBEHAVIOR_NORESIZEONSCALE can also be set if you set it at creation time.
  9842. * 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.
  9843. */
  9844. get: function () {
  9845. return this._cacheBehavior;
  9846. },
  9847. enumerable: true,
  9848. configurable: true
  9849. });
  9850. Group2D.prototype._addPrimToDirtyList = function (prim) {
  9851. this._renderableData._primDirtyList.push(prim);
  9852. };
  9853. Group2D.prototype._renderCachedCanvas = function () {
  9854. this.owner._addGroupRenderCount(1);
  9855. this.updateCachedStates(true);
  9856. var context = new BABYLON.PrepareRender2DContext();
  9857. this._prepareGroupRender(context);
  9858. this._groupRender();
  9859. };
  9860. Object.defineProperty(Group2D.prototype, "trackedNode", {
  9861. /**
  9862. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  9863. */
  9864. get: function () {
  9865. return this._trackedNode;
  9866. },
  9867. set: function (val) {
  9868. if (val != null) {
  9869. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  9870. this.owner._registerTrackedNode(this);
  9871. }
  9872. this._trackedNode = val;
  9873. }
  9874. else {
  9875. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  9876. this.owner._unregisterTrackedNode(this);
  9877. }
  9878. this._trackedNode = null;
  9879. }
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. Group2D.prototype.levelIntersect = function (intersectInfo) {
  9885. // 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
  9886. return true;
  9887. };
  9888. Group2D.prototype.updateLevelBoundingInfo = function () {
  9889. var size;
  9890. // If the size is set by the user, the boundingInfo is computed from this value
  9891. if (this.size) {
  9892. size = this.size;
  9893. }
  9894. else {
  9895. size = new BABYLON.Size(0, 0);
  9896. }
  9897. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  9898. return true;
  9899. };
  9900. // Method called only on renderable groups to prepare the rendering
  9901. Group2D.prototype._prepareGroupRender = function (context) {
  9902. var sortedDirtyList = null;
  9903. // Update the Global Transformation and visibility status of the changed primitives
  9904. var rd = this._renderableData;
  9905. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  9906. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  9907. this.updateCachedStatesOf(sortedDirtyList, true);
  9908. }
  9909. var s = this.actualSize;
  9910. var a = this.actualScale;
  9911. var sw = Math.ceil(s.width * a.x);
  9912. var sh = Math.ceil(s.height * a.y);
  9913. // 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.
  9914. // So we set the width/height to the rendering's one because that's what we want for the viewport!
  9915. if ((this instanceof BABYLON.Canvas2D || this.id === "__cachedCanvasGroup__") && this.owner.designSize != null) {
  9916. sw = this.owner.engine.getRenderWidth();
  9917. sh = this.owner.engine.getRenderHeight();
  9918. }
  9919. // Setup the size of the rendering viewport
  9920. // 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
  9921. if (!this._isCachedGroup) {
  9922. // Compute the WebGL viewport's location/size
  9923. var t = this._globalTransform.getTranslation();
  9924. var rs = this.owner._renderingSize;
  9925. sh = Math.min(sh, rs.height - t.y);
  9926. sw = Math.min(sw, rs.width - t.x);
  9927. var x = t.x;
  9928. var y = t.y;
  9929. // 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
  9930. this._viewportPosition.x = x;
  9931. this._viewportPosition.y = y;
  9932. }
  9933. // 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.
  9934. if (this._viewportSize.width !== sw || this._viewportSize.height !== sh) {
  9935. context.forceRefreshPrimitive = true;
  9936. this._viewportSize.width = sw;
  9937. this._viewportSize.height = sh;
  9938. }
  9939. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  9940. // If the group is cached, set the dirty flag to true because of the incoming changes
  9941. this._cacheGroupDirty = this._isCachedGroup;
  9942. rd._primNewDirtyList.splice(0);
  9943. // If it's a force refresh, prepare all the children
  9944. if (context.forceRefreshPrimitive) {
  9945. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9946. var p = _a[_i];
  9947. p._prepareRender(context);
  9948. }
  9949. }
  9950. else {
  9951. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  9952. // the hierarchyDepth in order to prepare primitives from top to bottom
  9953. if (!sortedDirtyList) {
  9954. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  9955. }
  9956. sortedDirtyList.forEach(function (p) {
  9957. // 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.
  9958. // 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.
  9959. if (!p.isDisposed && p._needPrepare()) {
  9960. p._prepareRender(context);
  9961. }
  9962. });
  9963. }
  9964. // Everything is updated, clear the dirty list
  9965. rd._primDirtyList.forEach(function (p) {
  9966. if (rd._primNewDirtyList.indexOf(p) === -1) {
  9967. p._resetPropertiesDirty();
  9968. }
  9969. else {
  9970. p._setFlags(BABYLON.SmartPropertyPrim.flagNeedRefresh);
  9971. }
  9972. });
  9973. rd._primDirtyList.splice(0);
  9974. rd._primDirtyList = rd._primDirtyList.concat(rd._primNewDirtyList);
  9975. }
  9976. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  9977. rd._childrenRenderableGroups.forEach(function (g) {
  9978. g._prepareGroupRender(context);
  9979. });
  9980. };
  9981. Group2D.prototype._groupRender = function () {
  9982. var _this = this;
  9983. var engine = this.owner.engine;
  9984. var failedCount = 0;
  9985. // First recurse to children render group to render them (in their cache or on screen)
  9986. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  9987. var childGroup = _a[_i];
  9988. childGroup._groupRender();
  9989. }
  9990. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  9991. if (!this.isCachedGroup || this._cacheGroupDirty) {
  9992. this.owner._addGroupRenderCount(1);
  9993. if (this.isCachedGroup) {
  9994. this._bindCacheTarget();
  9995. }
  9996. else {
  9997. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  9998. }
  9999. var curAlphaTest = engine.getAlphaTesting() === true;
  10000. var curDepthWrite = engine.getDepthWrite() === true;
  10001. // ===================================================================
  10002. // First pass, update the InstancedArray and render Opaque primitives
  10003. // Disable Alpha Testing, Enable Depth Write
  10004. engine.setAlphaTesting(false);
  10005. engine.setDepthWrite(true);
  10006. // For each different model of primitive to render
  10007. var context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  10008. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  10009. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  10010. var renderCount = _this._prepareContext(engine, context_1, v);
  10011. // If null is returned, there's no opaque data to render
  10012. if (renderCount === null) {
  10013. return;
  10014. }
  10015. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  10016. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  10017. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  10018. var renderFailed = !v.modelRenderCache.render(v, context_1);
  10019. // Update dirty flag/related
  10020. v.opaqueDirty = renderFailed;
  10021. failedCount += renderFailed ? 1 : 0;
  10022. }
  10023. });
  10024. // =======================================================================
  10025. // Second pass, update the InstancedArray and render AlphaTest primitives
  10026. // Enable Alpha Testing, Enable Depth Write
  10027. engine.setAlphaTesting(true);
  10028. engine.setDepthWrite(true);
  10029. // For each different model of primitive to render
  10030. context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  10031. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  10032. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  10033. var renderCount = _this._prepareContext(engine, context_1, v);
  10034. // If null is returned, there's no opaque data to render
  10035. if (renderCount === null) {
  10036. return;
  10037. }
  10038. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  10039. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  10040. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  10041. var renderFailed = !v.modelRenderCache.render(v, context_1);
  10042. // Update dirty flag/related
  10043. v.opaqueDirty = renderFailed;
  10044. failedCount += renderFailed ? 1 : 0;
  10045. }
  10046. });
  10047. // =======================================================================
  10048. // Third pass, transparent primitive rendering
  10049. // Enable Alpha Testing, Disable Depth Write
  10050. engine.setAlphaTesting(true);
  10051. engine.setDepthWrite(false);
  10052. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  10053. if (this._renderableData._transparentListChanged) {
  10054. this._updateTransparentData();
  10055. }
  10056. // From this point on we have up to date data to render, so let's go
  10057. failedCount += this._renderTransparentData();
  10058. // =======================================================================
  10059. // Unbind target/restore viewport setting, clear dirty flag, and quit
  10060. // The group's content is no longer dirty
  10061. this._cacheGroupDirty = failedCount !== 0;
  10062. if (this.isCachedGroup) {
  10063. this._unbindCacheTarget();
  10064. }
  10065. else {
  10066. if (curVP) {
  10067. engine.setViewport(curVP);
  10068. }
  10069. }
  10070. // Restore saved states
  10071. engine.setAlphaTesting(curAlphaTest);
  10072. engine.setDepthWrite(curDepthWrite);
  10073. }
  10074. };
  10075. Group2D.prototype._setCacheGroupDirty = function () {
  10076. this._cacheGroupDirty = true;
  10077. };
  10078. Group2D.prototype._updateTransparentData = function () {
  10079. this.owner._addUpdateTransparentDataCount(1);
  10080. var rd = this._renderableData;
  10081. // Sort all the primitive from their depth, max (bottom) to min (top)
  10082. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  10083. var checkAndAddPrimInSegment = function (seg, tpiI) {
  10084. var tpi = rd._transparentPrimitives[tpiI];
  10085. // Fast rejection: if gii are different
  10086. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  10087. return false;
  10088. }
  10089. //let tpiZ = tpi._primitive.actualZOffset;
  10090. // We've made it so far, the tpi can be part of the segment, add it
  10091. tpi._transparentSegment = seg;
  10092. tpi._primitive._updateTransparentSegmentIndices(seg);
  10093. return true;
  10094. };
  10095. // Free the existing TransparentSegments
  10096. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  10097. var ts = _a[_i];
  10098. ts.dispose(this.owner.engine);
  10099. }
  10100. rd._transparentSegments.splice(0);
  10101. var prevSeg = null;
  10102. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  10103. var tpi = rd._transparentPrimitives[tpiI];
  10104. // Check if the Data in which the primitive is stored is not sorted properly
  10105. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  10106. tpi._groupInstanceInfo.sortTransparentData();
  10107. }
  10108. // Reset the segment, we have to create/rebuild it
  10109. tpi._transparentSegment = null;
  10110. // If there's a previous valid segment, check if this prim can be part of it
  10111. if (prevSeg) {
  10112. checkAndAddPrimInSegment(prevSeg, tpiI);
  10113. }
  10114. // If we couldn't insert in the adjacent segments, he have to create one
  10115. if (!tpi._transparentSegment) {
  10116. var ts = new BABYLON.TransparentSegment();
  10117. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  10118. var prim = tpi._primitive;
  10119. ts.startZ = prim.actualZOffset;
  10120. prim._updateTransparentSegmentIndices(ts);
  10121. ts.endZ = ts.startZ;
  10122. tpi._transparentSegment = ts;
  10123. rd._transparentSegments.push(ts);
  10124. }
  10125. // Update prevSeg
  10126. prevSeg = tpi._transparentSegment;
  10127. }
  10128. //rd._firstChangedPrim = null;
  10129. rd._transparentListChanged = false;
  10130. };
  10131. Group2D.prototype._renderTransparentData = function () {
  10132. var failedCount = 0;
  10133. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  10134. var rd = this._renderableData;
  10135. var useInstanced = this.owner.supportInstancedArray;
  10136. var length = rd._transparentSegments.length;
  10137. for (var i = 0; i < length; i++) {
  10138. context.instancedBuffers = null;
  10139. var ts = rd._transparentSegments[i];
  10140. var gii = ts.groupInsanceInfo;
  10141. var mrc = gii.modelRenderCache;
  10142. var engine = this.owner.engine;
  10143. var count = ts.endDataIndex - ts.startDataIndex;
  10144. // Use Instanced Array if it's supported and if there's at least minPartCountToUseInstancedArray prims to draw.
  10145. // We don't want to create an Instanced Buffer for less that minPartCountToUseInstancedArray prims
  10146. if (useInstanced && count >= this.owner.minPartCountToUseInstancedArray) {
  10147. if (!ts.partBuffers) {
  10148. var buffers = new Array();
  10149. for (var j = 0; j < gii.transparentData.length; j++) {
  10150. var gitd = gii.transparentData[j];
  10151. var dfa = gitd._partData;
  10152. var data = dfa.pack();
  10153. var stride = dfa.stride;
  10154. var neededSize = count * stride * 4;
  10155. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  10156. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  10157. engine.updateArrayBuffer(segData);
  10158. buffers.push(buffer);
  10159. }
  10160. ts.partBuffers = buffers;
  10161. }
  10162. else if (gii.transparentDirty) {
  10163. for (var j = 0; j < gii.transparentData.length; j++) {
  10164. var gitd = gii.transparentData[j];
  10165. var dfa = gitd._partData;
  10166. var data = dfa.pack();
  10167. var stride = dfa.stride;
  10168. var buffer = ts.partBuffers[j];
  10169. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  10170. engine.bindArrayBuffer(buffer);
  10171. engine.updateArrayBuffer(segData);
  10172. }
  10173. }
  10174. context.useInstancing = true;
  10175. context.instancesCount = count;
  10176. context.instancedBuffers = ts.partBuffers;
  10177. context.groupInfoPartData = gii.transparentData;
  10178. var renderFailed = !mrc.render(gii, context);
  10179. failedCount += renderFailed ? 1 : 0;
  10180. }
  10181. else {
  10182. context.useInstancing = false;
  10183. context.partDataStartIndex = ts.startDataIndex;
  10184. context.partDataEndIndex = ts.endDataIndex;
  10185. context.groupInfoPartData = gii.transparentData;
  10186. var renderFailed = !mrc.render(gii, context);
  10187. failedCount += renderFailed ? 1 : 0;
  10188. }
  10189. }
  10190. return failedCount;
  10191. };
  10192. Group2D.prototype._prepareContext = function (engine, context, gii) {
  10193. var gipd = null;
  10194. var setDirty;
  10195. var getDirty;
  10196. // Render Mode specifics
  10197. switch (context.renderMode) {
  10198. case BABYLON.Render2DContext.RenderModeOpaque:
  10199. {
  10200. if (!gii.hasOpaqueData) {
  10201. return null;
  10202. }
  10203. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  10204. getDirty = function () { return gii.opaqueDirty; };
  10205. context.groupInfoPartData = gii.opaqueData;
  10206. gipd = gii.opaqueData;
  10207. break;
  10208. }
  10209. case BABYLON.Render2DContext.RenderModeAlphaTest:
  10210. {
  10211. if (!gii.hasAlphaTestData) {
  10212. return null;
  10213. }
  10214. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  10215. getDirty = function () { return gii.alphaTestDirty; };
  10216. context.groupInfoPartData = gii.alphaTestData;
  10217. gipd = gii.alphaTestData;
  10218. break;
  10219. }
  10220. default:
  10221. throw new Error("_prepareContext is only for opaque or alphaTest");
  10222. }
  10223. var renderCount = 0;
  10224. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  10225. // Skip it if instanced arrays are not supported
  10226. if (this.owner.supportInstancedArray) {
  10227. // Flag for instancing
  10228. context.useInstancing = true;
  10229. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  10230. for (var i = 0; i < gipd.length; i++) {
  10231. var pid = gipd[i];
  10232. // If the instances of the model was changed, pack the data
  10233. var array = pid._partData;
  10234. var instanceData_1 = array.pack();
  10235. renderCount += array.usedElementCount;
  10236. // Compute the size the instance buffer should have
  10237. var neededSize = array.usedElementCount * array.stride * 4;
  10238. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  10239. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  10240. if (pid._partBuffer) {
  10241. engine.deleteInstancesBuffer(pid._partBuffer);
  10242. }
  10243. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  10244. pid._partBufferSize = neededSize;
  10245. setDirty(false);
  10246. // Update the WebGL buffer to match the new content of the instances data
  10247. engine.updateArrayBuffer(instanceData_1);
  10248. }
  10249. else if (getDirty()) {
  10250. // Update the WebGL buffer to match the new content of the instances data
  10251. engine.bindArrayBuffer(pid._partBuffer);
  10252. engine.updateArrayBuffer(instanceData_1);
  10253. }
  10254. }
  10255. setDirty(false);
  10256. }
  10257. else {
  10258. context.partDataStartIndex = 0;
  10259. // Find the first valid object to get the count
  10260. if (context.groupInfoPartData.length > 0) {
  10261. var i = 0;
  10262. while (!context.groupInfoPartData[i]) {
  10263. i++;
  10264. }
  10265. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  10266. }
  10267. }
  10268. return renderCount;
  10269. };
  10270. Group2D.prototype._setRenderingScale = function (scale) {
  10271. if (this._renderableData._renderingScale === scale) {
  10272. return;
  10273. }
  10274. this._renderableData._renderingScale = scale;
  10275. };
  10276. Group2D.prototype._bindCacheTarget = function () {
  10277. var curWidth;
  10278. var curHeight;
  10279. var rd = this._renderableData;
  10280. var rs = rd._renderingScale;
  10281. var noResizeScale = rd._noResizeOnScale;
  10282. var isCanvas = this.parent == null;
  10283. var scale;
  10284. if (noResizeScale) {
  10285. scale = isCanvas ? Group2D_1._uV : this.parent.actualScale;
  10286. }
  10287. else {
  10288. scale = this.actualScale;
  10289. }
  10290. if (isCanvas && this.owner.cachingStrategy === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS && this.owner.isScreenSpace) {
  10291. if (this.owner.designSize || this.owner.fitRenderingDevice) {
  10292. Group2D_1._s.width = this.owner.engine.getRenderWidth();
  10293. Group2D_1._s.height = this.owner.engine.getRenderHeight();
  10294. }
  10295. else {
  10296. Group2D_1._s.copyFrom(this.owner.size);
  10297. }
  10298. }
  10299. else {
  10300. Group2D_1._s.width = Math.ceil(this.actualSize.width * scale.x * rs);
  10301. Group2D_1._s.height = Math.ceil(this.actualSize.height * scale.y * rs);
  10302. }
  10303. var sizeChanged = !Group2D_1._s.equals(rd._cacheSize);
  10304. if (rd._cacheNode) {
  10305. var size = rd._cacheNode.contentSize;
  10306. // Check if we have to deallocate because the size is too small
  10307. if ((size.width < Group2D_1._s.width) || (size.height < Group2D_1._s.height)) {
  10308. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  10309. // For World space: no over-provisioning
  10310. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  10311. curWidth = Math.floor(Group2D_1._s.width * overprovisioning);
  10312. curHeight = Math.floor(Group2D_1._s.height * overprovisioning);
  10313. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  10314. rd._cacheTexture.freeRect(rd._cacheNode);
  10315. rd._cacheNode = null;
  10316. }
  10317. }
  10318. if (!rd._cacheNode) {
  10319. // Check if we have to allocate a rendering zone in the global cache texture
  10320. var res = this.owner._allocateGroupCache(this, this.parent && this.parent.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  10321. rd._cacheNode = res.node;
  10322. rd._cacheTexture = res.texture;
  10323. if (rd._cacheRenderSprite) {
  10324. rd._cacheRenderSprite.dispose();
  10325. }
  10326. rd._cacheRenderSprite = res.sprite;
  10327. sizeChanged = true;
  10328. }
  10329. if (sizeChanged) {
  10330. rd._cacheSize.copyFrom(Group2D_1._s);
  10331. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  10332. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  10333. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  10334. }
  10335. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  10336. }
  10337. var n = rd._cacheNode;
  10338. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D_1._s, true);
  10339. };
  10340. Group2D.prototype._unbindCacheTarget = function () {
  10341. if (this._renderableData._cacheTexture) {
  10342. this._renderableData._cacheTexture.unbindTexture();
  10343. }
  10344. };
  10345. Group2D.prototype._spreadActualScaleDirty = function () {
  10346. if (this._renderableData && this._renderableData._cacheRenderSprite) {
  10347. this.handleGroupChanged(BABYLON.Prim2DBase.actualScaleProperty);
  10348. }
  10349. _super.prototype._spreadActualScaleDirty.call(this);
  10350. };
  10351. Group2D.prototype.handleGroupChanged = function (prop) {
  10352. // This method is only for cachedGroup
  10353. var rd = this._renderableData;
  10354. if (!rd) {
  10355. return;
  10356. }
  10357. var cachedSprite = rd._cacheRenderSprite;
  10358. if (!this.isCachedGroup || !cachedSprite) {
  10359. return;
  10360. }
  10361. // For now we only support these property changes
  10362. // TODO: add more! :)
  10363. switch (prop.id) {
  10364. case BABYLON.Prim2DBase.actualPositionProperty.id:
  10365. cachedSprite.actualPosition = this.actualPosition.clone();
  10366. if (cachedSprite.position != null) {
  10367. cachedSprite.position = cachedSprite.actualPosition.clone();
  10368. }
  10369. break;
  10370. case BABYLON.Prim2DBase.rotationProperty.id:
  10371. cachedSprite.rotation = this.rotation;
  10372. break;
  10373. case BABYLON.Prim2DBase.scaleProperty.id:
  10374. cachedSprite.scale = this.scale;
  10375. break;
  10376. case BABYLON.Prim2DBase.originProperty.id:
  10377. cachedSprite.origin = this.origin.clone();
  10378. break;
  10379. case Group2D_1.actualSizeProperty.id:
  10380. cachedSprite.size = this.actualSize.clone();
  10381. break;
  10382. }
  10383. };
  10384. Group2D.prototype.detectGroupStates = function () {
  10385. var isCanvas = this instanceof BABYLON.Canvas2D;
  10386. var canvasStrat = this.owner.cachingStrategy;
  10387. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  10388. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  10389. this._isRenderableGroup = isCanvas;
  10390. this._isCachedGroup = false;
  10391. }
  10392. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  10393. if (isCanvas) {
  10394. this._isRenderableGroup = true;
  10395. this._isCachedGroup = true;
  10396. }
  10397. else {
  10398. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  10399. this._isCachedGroup = false;
  10400. }
  10401. }
  10402. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  10403. if (isCanvas) {
  10404. this._isRenderableGroup = true;
  10405. this._isCachedGroup = false;
  10406. }
  10407. else {
  10408. if (this.hierarchyDepth === 1) {
  10409. this._isRenderableGroup = true;
  10410. this._isCachedGroup = true;
  10411. }
  10412. else {
  10413. this._isRenderableGroup = false;
  10414. this._isCachedGroup = false;
  10415. }
  10416. }
  10417. }
  10418. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  10419. if (isCanvas) {
  10420. this._isRenderableGroup = true;
  10421. this._isCachedGroup = false;
  10422. }
  10423. else {
  10424. var gcb = this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_OPTIONMASK;
  10425. if ((gcb === Group2D_1.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D_1.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  10426. this._isRenderableGroup = gcb === Group2D_1.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  10427. this._isCachedGroup = false;
  10428. }
  10429. if (gcb === Group2D_1.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  10430. this._isRenderableGroup = true;
  10431. this._isCachedGroup = true;
  10432. }
  10433. }
  10434. }
  10435. if (this._isRenderableGroup) {
  10436. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  10437. if (!this._renderableData) {
  10438. this._renderableData = new RenderableGroupData();
  10439. }
  10440. }
  10441. // If the group is tagged as renderable we add it to the renderable tree
  10442. if (this._isCachedGroup) {
  10443. this._renderableData._noResizeOnScale = (this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  10444. var cur = this.parent;
  10445. while (cur) {
  10446. if (cur instanceof Group2D_1 && cur._isRenderableGroup) {
  10447. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  10448. cur._renderableData._childrenRenderableGroups.push(this);
  10449. }
  10450. break;
  10451. }
  10452. cur = cur.parent;
  10453. }
  10454. }
  10455. };
  10456. return Group2D;
  10457. }(BABYLON.Prim2DBase));
  10458. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  10459. /**
  10460. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  10461. */
  10462. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  10463. /**
  10464. * When used, this group's content won't be cached, no matter which strategy used.
  10465. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  10466. */
  10467. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  10468. /**
  10469. * When used, the group's content will be cached in the nearest cached parent group/canvas
  10470. */
  10471. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  10472. /**
  10473. * 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
  10474. */
  10475. Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE = 0x100;
  10476. Group2D.GROUPCACHEBEHAVIOR_OPTIONMASK = 0xFF;
  10477. Group2D._uV = new BABYLON.Vector2(1, 1);
  10478. Group2D._s = BABYLON.Size.Zero();
  10479. Group2D._unS = new BABYLON.Vector2(1, 1);
  10480. __decorate([
  10481. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D_1.sizeProperty = pi; }, false, true)
  10482. ], Group2D.prototype, "size", null);
  10483. __decorate([
  10484. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D_1.actualSizeProperty = pi; })
  10485. ], Group2D.prototype, "actualSize", null);
  10486. Group2D = Group2D_1 = __decorate([
  10487. BABYLON.className("Group2D", "BABYLON")
  10488. ], Group2D);
  10489. BABYLON.Group2D = Group2D;
  10490. var RenderableGroupData = (function () {
  10491. function RenderableGroupData() {
  10492. this._primDirtyList = new Array();
  10493. this._primNewDirtyList = new Array();
  10494. this._childrenRenderableGroups = new Array();
  10495. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  10496. this._transparentPrimitives = new Array();
  10497. this._transparentSegments = new Array();
  10498. this._transparentListChanged = false;
  10499. this._cacheNode = null;
  10500. this._cacheTexture = null;
  10501. this._cacheRenderSprite = null;
  10502. this._renderingScale = 1;
  10503. this._cacheNodeUVs = null;
  10504. this._cacheNodeUVsChangedObservable = null;
  10505. this._cacheSize = BABYLON.Size.Zero();
  10506. this._useMipMap = false;
  10507. this._anisotropicLevel = 1;
  10508. this._noResizeOnScale = false;
  10509. }
  10510. RenderableGroupData.prototype.dispose = function (owner) {
  10511. var engine = owner.engine;
  10512. if (this._cacheRenderSprite) {
  10513. this._cacheRenderSprite.dispose();
  10514. this._cacheRenderSprite = null;
  10515. }
  10516. if (this._cacheTexture && this._cacheNode) {
  10517. this._cacheTexture.freeRect(this._cacheNode);
  10518. this._cacheTexture = null;
  10519. this._cacheNode = null;
  10520. }
  10521. if (this._primDirtyList) {
  10522. this._primDirtyList.splice(0);
  10523. this._primDirtyList = null;
  10524. }
  10525. if (this._renderGroupInstancesInfo) {
  10526. this._renderGroupInstancesInfo.forEach(function (k, v) {
  10527. v.dispose();
  10528. });
  10529. this._renderGroupInstancesInfo = null;
  10530. }
  10531. if (this._cacheNodeUVsChangedObservable) {
  10532. this._cacheNodeUVsChangedObservable.clear();
  10533. this._cacheNodeUVsChangedObservable = null;
  10534. }
  10535. if (this._transparentSegments) {
  10536. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  10537. var ts = _a[_i];
  10538. ts.dispose(engine);
  10539. }
  10540. this._transparentSegments.splice(0);
  10541. this._transparentSegments = null;
  10542. }
  10543. };
  10544. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  10545. var tpi = new TransparentPrimitiveInfo();
  10546. tpi._primitive = prim;
  10547. tpi._groupInstanceInfo = gii;
  10548. tpi._transparentSegment = null;
  10549. this._transparentPrimitives.push(tpi);
  10550. this._transparentListChanged = true;
  10551. return tpi;
  10552. };
  10553. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  10554. var index = this._transparentPrimitives.indexOf(tpi);
  10555. if (index !== -1) {
  10556. this._transparentPrimitives.splice(index, 1);
  10557. this._transparentListChanged = true;
  10558. }
  10559. };
  10560. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  10561. this._transparentListChanged = true;
  10562. //this.updateSmallestZChangedPrim(tpi);
  10563. };
  10564. return RenderableGroupData;
  10565. }());
  10566. BABYLON.RenderableGroupData = RenderableGroupData;
  10567. var TransparentPrimitiveInfo = (function () {
  10568. function TransparentPrimitiveInfo() {
  10569. }
  10570. return TransparentPrimitiveInfo;
  10571. }());
  10572. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  10573. var Group2D_1;
  10574. })(BABYLON || (BABYLON = {}));
  10575. //# sourceMappingURL=babylon.group2d.js.map
  10576. var __extends = (this && this.__extends) || function (d, b) {
  10577. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10578. function __() { this.constructor = d; }
  10579. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  10580. };
  10581. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  10582. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  10583. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  10584. 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;
  10585. return c > 3 && r && Object.defineProperty(target, key, r), r;
  10586. };
  10587. var BABYLON;
  10588. (function (BABYLON) {
  10589. var WireFrame2DRenderCache = (function (_super) {
  10590. __extends(WireFrame2DRenderCache, _super);
  10591. function WireFrame2DRenderCache() {
  10592. var _this = _super.apply(this, arguments) || this;
  10593. _this.effectsReady = false;
  10594. _this.vb = null;
  10595. _this.vtxCount = 0;
  10596. _this.instancingAttributes = null;
  10597. _this.effect = null;
  10598. _this.effectInstanced = null;
  10599. return _this;
  10600. }
  10601. WireFrame2DRenderCache.prototype.render = function (instanceInfo, context) {
  10602. // Do nothing if the shader is still loading/preparing
  10603. if (!this.effectsReady) {
  10604. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  10605. return false;
  10606. }
  10607. this.effectsReady = true;
  10608. }
  10609. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  10610. var canvas = instanceInfo.owner.owner;
  10611. var engine = canvas.engine;
  10612. var cur = engine.getAlphaMode();
  10613. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  10614. engine.enableEffect(effect);
  10615. engine.bindBuffersDirectly(this.vb, null, [2, 4], 24, effect);
  10616. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  10617. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  10618. }
  10619. var pid = context.groupInfoPartData[0];
  10620. if (context.useInstancing) {
  10621. if (!this.instancingAttributes) {
  10622. this.instancingAttributes = this.loadInstancingAttributes(WireFrame2D.WIREFRAME2D_MAINPARTID, effect);
  10623. }
  10624. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  10625. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  10626. canvas._addDrawCallCount(1, context.renderMode);
  10627. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  10628. engine.drawUnIndexed(false, 0, this.vtxCount, count);
  10629. // engine.draw(true, 0, 6, count);
  10630. engine.unbindInstanceAttributes();
  10631. }
  10632. else {
  10633. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  10634. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  10635. this.setupUniforms(effect, 0, pid._partData, i);
  10636. engine.drawUnIndexed(false, 0, this.vtxCount);
  10637. }
  10638. }
  10639. engine.setAlphaMode(cur, true);
  10640. return true;
  10641. };
  10642. WireFrame2DRenderCache.prototype.updateModelRenderCache = function (prim) {
  10643. var w = prim;
  10644. w._updateVertexBuffer(this);
  10645. return true;
  10646. };
  10647. WireFrame2DRenderCache.prototype.dispose = function () {
  10648. if (!_super.prototype.dispose.call(this)) {
  10649. return false;
  10650. }
  10651. if (this.vb) {
  10652. this._engine._releaseBuffer(this.vb);
  10653. this.vb = null;
  10654. }
  10655. this.effect = null;
  10656. this.effectInstanced = null;
  10657. return true;
  10658. };
  10659. return WireFrame2DRenderCache;
  10660. }(BABYLON.ModelRenderCache));
  10661. BABYLON.WireFrame2DRenderCache = WireFrame2DRenderCache;
  10662. var WireFrameVertex2D = (function () {
  10663. function WireFrameVertex2D(p, c) {
  10664. if (c === void 0) { c = null; }
  10665. this.fromVector2(p);
  10666. if (c != null) {
  10667. this.fromColor4(c);
  10668. }
  10669. else {
  10670. this.r = this.g = this.b = this.a = 1;
  10671. }
  10672. }
  10673. WireFrameVertex2D.prototype.fromVector2 = function (p) {
  10674. this.x = p.x;
  10675. this.y = p.y;
  10676. };
  10677. WireFrameVertex2D.prototype.fromColor3 = function (c) {
  10678. this.r = c.r;
  10679. this.g = c.g;
  10680. this.b = c.b;
  10681. this.a = 1;
  10682. };
  10683. WireFrameVertex2D.prototype.fromColor4 = function (c) {
  10684. this.r = c.r;
  10685. this.g = c.g;
  10686. this.b = c.b;
  10687. this.a = c.a;
  10688. };
  10689. return WireFrameVertex2D;
  10690. }());
  10691. WireFrameVertex2D = __decorate([
  10692. BABYLON.className("WireFrameVertex2D", "BABYLON")
  10693. ], WireFrameVertex2D);
  10694. BABYLON.WireFrameVertex2D = WireFrameVertex2D;
  10695. var WireFrameGroup2D = (function () {
  10696. /**
  10697. * Construct a WireFrameGroup2D object
  10698. * @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.
  10699. * @param defaultColor specify the default color that will be used when a vertex is pushed, white will be used if not specified.
  10700. */
  10701. function WireFrameGroup2D(id, defaultColor) {
  10702. if (id === void 0) { id = null; }
  10703. if (defaultColor === void 0) { defaultColor = null; }
  10704. this._id = (id == null) ? BABYLON.Tools.RandomId() : id;
  10705. this._uid = BABYLON.Tools.RandomId();
  10706. this._defaultColor = (defaultColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : defaultColor;
  10707. this._buildingStrip = false;
  10708. this._vertices = new Array();
  10709. }
  10710. Object.defineProperty(WireFrameGroup2D.prototype, "uid", {
  10711. get: function () {
  10712. return this._uid;
  10713. },
  10714. enumerable: true,
  10715. configurable: true
  10716. });
  10717. Object.defineProperty(WireFrameGroup2D.prototype, "id", {
  10718. /**
  10719. * Retrieve the ID of the group
  10720. */
  10721. get: function () {
  10722. return this._id;
  10723. },
  10724. enumerable: true,
  10725. configurable: true
  10726. });
  10727. /**
  10728. * Push a vertex in the array of vertices.
  10729. * 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.
  10730. * @param p Position of the vertex
  10731. * @param c Color of the vertex, if null the default color of the group will be used
  10732. */
  10733. WireFrameGroup2D.prototype.pushVertex = function (p, c) {
  10734. if (c === void 0) { c = null; }
  10735. var v = new WireFrameVertex2D(p, (c == null) ? this._defaultColor : c);
  10736. this._vertices.push(v);
  10737. if (this._buildingStrip) {
  10738. var v2 = new WireFrameVertex2D(p, (c == null) ? this._defaultColor : c);
  10739. this._vertices.push(v2);
  10740. }
  10741. };
  10742. /**
  10743. * 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!!!
  10744. * @param p Position of the vertex
  10745. * @param c Color of the vertex, if null the default color of the group will be used
  10746. */
  10747. WireFrameGroup2D.prototype.startLineStrip = function (p, c) {
  10748. if (c === void 0) { c = null; }
  10749. this.pushVertex(p, (c == null) ? this._defaultColor : c);
  10750. this._buildingStrip = true;
  10751. };
  10752. /**
  10753. * Close the Strip by storing a last vertex
  10754. * @param p Position of the vertex
  10755. * @param c Color of the vertex, if null the default color of the group will be used
  10756. */
  10757. WireFrameGroup2D.prototype.endLineStrip = function (p, c) {
  10758. if (c === void 0) { c = null; }
  10759. this._buildingStrip = false;
  10760. this.pushVertex(p, (c == null) ? this._defaultColor : c);
  10761. };
  10762. Object.defineProperty(WireFrameGroup2D.prototype, "vertices", {
  10763. /**
  10764. * Access to the array of Vertices, you can manipulate its content but BEWARE of what you're doing!
  10765. */
  10766. get: function () {
  10767. return this._vertices;
  10768. },
  10769. enumerable: true,
  10770. configurable: true
  10771. });
  10772. return WireFrameGroup2D;
  10773. }());
  10774. WireFrameGroup2D = __decorate([
  10775. BABYLON.className("WireFrameGroup2D", "BABYLON")
  10776. ], WireFrameGroup2D);
  10777. BABYLON.WireFrameGroup2D = WireFrameGroup2D;
  10778. var WireFrame2D = WireFrame2D_1 = (function (_super) {
  10779. __extends(WireFrame2D, _super);
  10780. /**
  10781. * Create an WireFrame 2D primitive
  10782. * @param wireFrameGroups an array of WireFrameGroup.
  10783. * @param settings a combination of settings, possible ones are
  10784. * - 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)
  10785. * - children: an array of direct children
  10786. * - id a text identifier, for information purpose
  10787. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  10788. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  10789. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  10790. * - size: the size of the sprite displayed in the canvas, if not specified the spriteSize will be used
  10791. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  10792. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  10793. * - zOrder: override the zOrder with the specified value
  10794. * - origin: define the normalized origin point location, default [0.5;0.5]
  10795. * - alignToPixel: the rendered lines will be aligned to the rendering device' pixels
  10796. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  10797. * - 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.
  10798. * - 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.
  10799. * - 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!
  10800. * - 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.
  10801. * - 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).
  10802. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  10803. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10804. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10805. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10806. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10807. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  10808. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  10809. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  10810. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  10811. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10812. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10813. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10814. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10815. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  10816. */
  10817. function WireFrame2D(wireFrameGroups, settings) {
  10818. var _this;
  10819. if (!settings) {
  10820. settings = {};
  10821. }
  10822. _this = _super.call(this, settings) || this;
  10823. _this._wireFrameGroups = new BABYLON.StringDictionary();
  10824. for (var _i = 0, wireFrameGroups_1 = wireFrameGroups; _i < wireFrameGroups_1.length; _i++) {
  10825. var wfg = wireFrameGroups_1[_i];
  10826. _this._wireFrameGroups.add(wfg.id, wfg);
  10827. }
  10828. _this._vtxTransparent = false;
  10829. if (settings.size != null) {
  10830. _this.size = settings.size;
  10831. }
  10832. _this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  10833. return _this;
  10834. }
  10835. Object.defineProperty(WireFrame2D.prototype, "wireFrameGroups", {
  10836. get: function () {
  10837. return this._wireFrameGroups;
  10838. },
  10839. enumerable: true,
  10840. configurable: true
  10841. });
  10842. /**
  10843. * If you change the content of the wireFrameGroups you MUST call this method for the changes to be reflected during rendering
  10844. */
  10845. WireFrame2D.prototype.wireFrameGroupsDirty = function () {
  10846. this._setFlags(BABYLON.SmartPropertyPrim.flagModelUpdate);
  10847. this.onPrimBecomesDirty();
  10848. };
  10849. Object.defineProperty(WireFrame2D.prototype, "size", {
  10850. get: function () {
  10851. if (this._size == null) {
  10852. this._computeMinMaxTrans();
  10853. }
  10854. return this._size;
  10855. },
  10856. set: function (value) {
  10857. this.internalSetSize(value);
  10858. },
  10859. enumerable: true,
  10860. configurable: true
  10861. });
  10862. Object.defineProperty(WireFrame2D.prototype, "actualSize", {
  10863. get: function () {
  10864. if (this._actualSize) {
  10865. return this._actualSize;
  10866. }
  10867. return this.size;
  10868. },
  10869. set: function (value) {
  10870. this._actualSize = value;
  10871. },
  10872. enumerable: true,
  10873. configurable: true
  10874. });
  10875. WireFrame2D.prototype.updateLevelBoundingInfo = function () {
  10876. var v = this._computeMinMaxTrans();
  10877. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(v.x, v.z, v.y, v.w, this._levelBoundingInfo);
  10878. return true;
  10879. };
  10880. WireFrame2D.prototype.levelIntersect = function (intersectInfo) {
  10881. // TODO !
  10882. return true;
  10883. };
  10884. Object.defineProperty(WireFrame2D.prototype, "alignToPixel", {
  10885. /**
  10886. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  10887. */
  10888. get: function () {
  10889. return this._alignToPixel;
  10890. },
  10891. set: function (value) {
  10892. this._alignToPixel = value;
  10893. },
  10894. enumerable: true,
  10895. configurable: true
  10896. });
  10897. WireFrame2D.prototype.createModelRenderCache = function (modelKey) {
  10898. var renderCache = new WireFrame2DRenderCache(this.owner.engine, modelKey);
  10899. return renderCache;
  10900. };
  10901. WireFrame2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  10902. var renderCache = modelRenderCache;
  10903. var engine = this.owner.engine;
  10904. // Create the VertexBuffer
  10905. this._updateVertexBuffer(renderCache);
  10906. // 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
  10907. var ei = this.getDataPartEffectInfo(WireFrame2D_1.WIREFRAME2D_MAINPARTID, ["pos", "col"], [], true);
  10908. if (ei) {
  10909. renderCache.effectInstanced = engine.createEffect("wireframe2D", ei.attributes, ei.uniforms, [], ei.defines, null);
  10910. }
  10911. ei = this.getDataPartEffectInfo(WireFrame2D_1.WIREFRAME2D_MAINPARTID, ["pos", "col"], [], false);
  10912. renderCache.effect = engine.createEffect("wireframe2D", ei.attributes, ei.uniforms, [], ei.defines, null);
  10913. return renderCache;
  10914. };
  10915. WireFrame2D.prototype._updateVertexBuffer = function (mrc) {
  10916. var engine = this.owner.engine;
  10917. if (mrc.vb != null) {
  10918. engine._releaseBuffer(mrc.vb);
  10919. }
  10920. var vtxCount = 0;
  10921. this._wireFrameGroups.forEach(function (k, v) { return vtxCount += v.vertices.length; });
  10922. var vb = new Float32Array(vtxCount * 6);
  10923. var i = 0;
  10924. this._wireFrameGroups.forEach(function (k, v) {
  10925. for (var _i = 0, _a = v.vertices; _i < _a.length; _i++) {
  10926. var vtx = _a[_i];
  10927. vb[i++] = vtx.x;
  10928. vb[i++] = vtx.y;
  10929. vb[i++] = vtx.r;
  10930. vb[i++] = vtx.g;
  10931. vb[i++] = vtx.b;
  10932. vb[i++] = vtx.a;
  10933. }
  10934. });
  10935. mrc.vb = engine.createVertexBuffer(vb);
  10936. mrc.vtxCount = vtxCount;
  10937. };
  10938. WireFrame2D.prototype.refreshInstanceDataPart = function (part) {
  10939. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  10940. return false;
  10941. }
  10942. if (part.id === WireFrame2D_1.WIREFRAME2D_MAINPARTID) {
  10943. var d = this._instanceDataParts[0];
  10944. d.properties = new BABYLON.Vector3(this.alignToPixel ? 1 : 0, 2 / this.renderGroup.actualWidth, 2 / this.renderGroup.actualHeight);
  10945. }
  10946. return true;
  10947. };
  10948. WireFrame2D.prototype._computeMinMaxTrans = function () {
  10949. var xmin = Number.MAX_VALUE;
  10950. var xmax = Number.MIN_VALUE;
  10951. var ymin = Number.MAX_VALUE;
  10952. var ymax = Number.MIN_VALUE;
  10953. var transparent = false;
  10954. this._wireFrameGroups.forEach(function (k, v) {
  10955. for (var _i = 0, _a = v.vertices; _i < _a.length; _i++) {
  10956. var vtx = _a[_i];
  10957. xmin = Math.min(xmin, vtx.x);
  10958. xmax = Math.max(xmax, vtx.x);
  10959. ymin = Math.min(ymin, vtx.y);
  10960. ymax = Math.max(ymax, vtx.y);
  10961. if (vtx.a < 1) {
  10962. transparent = true;
  10963. }
  10964. }
  10965. });
  10966. this._vtxTransparent = transparent;
  10967. this._size = new BABYLON.Size(xmax - xmin, ymax - ymin);
  10968. return new BABYLON.Vector4(xmin, ymin, xmax, ymax);
  10969. };
  10970. WireFrame2D.prototype.createInstanceDataParts = function () {
  10971. return [new WireFrame2DInstanceData(WireFrame2D_1.WIREFRAME2D_MAINPARTID)];
  10972. };
  10973. return WireFrame2D;
  10974. }(BABYLON.RenderablePrim2D));
  10975. WireFrame2D.WIREFRAME2D_MAINPARTID = 1;
  10976. __decorate([
  10977. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return WireFrame2D_1.wireFrameGroupsProperty = pi; })
  10978. ], WireFrame2D.prototype, "wireFrameGroups", null);
  10979. __decorate([
  10980. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return WireFrame2D_1.actualSizeProperty = pi; }, false, true)
  10981. ], WireFrame2D.prototype, "actualSize", null);
  10982. WireFrame2D = WireFrame2D_1 = __decorate([
  10983. BABYLON.className("WireFrame2D", "BABYLON")
  10984. ], WireFrame2D);
  10985. BABYLON.WireFrame2D = WireFrame2D;
  10986. var WireFrame2DInstanceData = (function (_super) {
  10987. __extends(WireFrame2DInstanceData, _super);
  10988. function WireFrame2DInstanceData(partId) {
  10989. return _super.call(this, partId, 1) || this;
  10990. }
  10991. Object.defineProperty(WireFrame2DInstanceData.prototype, "properties", {
  10992. // the properties is for now the alignedToPixel value
  10993. get: function () {
  10994. return null;
  10995. },
  10996. set: function (value) {
  10997. },
  10998. enumerable: true,
  10999. configurable: true
  11000. });
  11001. return WireFrame2DInstanceData;
  11002. }(BABYLON.InstanceDataBase));
  11003. __decorate([
  11004. BABYLON.instanceData()
  11005. ], WireFrame2DInstanceData.prototype, "properties", null);
  11006. BABYLON.WireFrame2DInstanceData = WireFrame2DInstanceData;
  11007. var WireFrame2D_1;
  11008. })(BABYLON || (BABYLON = {}));
  11009. //# sourceMappingURL=babylon.wireFrame2d.js.map
  11010. var __extends = (this && this.__extends) || function (d, b) {
  11011. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11012. function __() { this.constructor = d; }
  11013. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  11014. };
  11015. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  11016. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  11017. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  11018. 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;
  11019. return c > 3 && r && Object.defineProperty(target, key, r), r;
  11020. };
  11021. var BABYLON;
  11022. (function (BABYLON) {
  11023. var Rectangle2DRenderCache = (function (_super) {
  11024. __extends(Rectangle2DRenderCache, _super);
  11025. function Rectangle2DRenderCache(engine, modelKey) {
  11026. var _this = _super.call(this, engine, modelKey) || this;
  11027. _this.effectsReady = false;
  11028. _this.fillVB = null;
  11029. _this.fillIB = null;
  11030. _this.fillIndicesCount = 0;
  11031. _this.instancingFillAttributes = null;
  11032. _this.effectFill = null;
  11033. _this.effectFillInstanced = null;
  11034. _this.borderVB = null;
  11035. _this.borderIB = null;
  11036. _this.borderIndicesCount = 0;
  11037. _this.instancingBorderAttributes = null;
  11038. _this.effectBorder = null;
  11039. _this.effectBorderInstanced = null;
  11040. return _this;
  11041. }
  11042. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  11043. // Do nothing if the shader is still loading/preparing
  11044. if (!this.effectsReady) {
  11045. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  11046. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  11047. return false;
  11048. }
  11049. this.effectsReady = true;
  11050. }
  11051. var canvas = instanceInfo.owner.owner;
  11052. var engine = canvas.engine;
  11053. var depthFunction = 0;
  11054. if (this.effectFill && this.effectBorder) {
  11055. depthFunction = engine.getDepthFunction();
  11056. engine.setDepthFunctionToLessOrEqual();
  11057. }
  11058. var curAlphaMode = engine.getAlphaMode();
  11059. if (this.effectFill) {
  11060. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  11061. var pid = context.groupInfoPartData[partIndex];
  11062. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  11063. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  11064. }
  11065. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  11066. engine.enableEffect(effect);
  11067. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  11068. if (context.useInstancing) {
  11069. if (!this.instancingFillAttributes) {
  11070. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  11071. }
  11072. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  11073. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  11074. canvas._addDrawCallCount(1, context.renderMode);
  11075. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  11076. engine.draw(true, 0, this.fillIndicesCount, count);
  11077. engine.unbindInstanceAttributes();
  11078. }
  11079. else {
  11080. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  11081. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  11082. this.setupUniforms(effect, partIndex, pid._partData, i);
  11083. engine.draw(true, 0, this.fillIndicesCount);
  11084. }
  11085. }
  11086. }
  11087. if (this.effectBorder) {
  11088. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  11089. var pid = context.groupInfoPartData[partIndex];
  11090. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  11091. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  11092. }
  11093. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  11094. engine.enableEffect(effect);
  11095. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  11096. if (context.useInstancing) {
  11097. if (!this.instancingBorderAttributes) {
  11098. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  11099. }
  11100. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  11101. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  11102. canvas._addDrawCallCount(1, context.renderMode);
  11103. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  11104. engine.draw(true, 0, this.borderIndicesCount, count);
  11105. engine.unbindInstanceAttributes();
  11106. }
  11107. else {
  11108. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  11109. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  11110. this.setupUniforms(effect, partIndex, pid._partData, i);
  11111. engine.draw(true, 0, this.borderIndicesCount);
  11112. }
  11113. }
  11114. }
  11115. engine.setAlphaMode(curAlphaMode, true);
  11116. if (this.effectFill && this.effectBorder) {
  11117. engine.setDepthFunction(depthFunction);
  11118. }
  11119. return true;
  11120. };
  11121. Rectangle2DRenderCache.prototype.dispose = function () {
  11122. if (!_super.prototype.dispose.call(this)) {
  11123. return false;
  11124. }
  11125. if (this.fillVB) {
  11126. this._engine._releaseBuffer(this.fillVB);
  11127. this.fillVB = null;
  11128. }
  11129. if (this.fillIB) {
  11130. this._engine._releaseBuffer(this.fillIB);
  11131. this.fillIB = null;
  11132. }
  11133. this.effectFill = null;
  11134. this.effectFillInstanced = null;
  11135. this.effectBorder = null;
  11136. this.effectBorderInstanced = null;
  11137. if (this.borderVB) {
  11138. this._engine._releaseBuffer(this.borderVB);
  11139. this.borderVB = null;
  11140. }
  11141. if (this.borderIB) {
  11142. this._engine._releaseBuffer(this.borderIB);
  11143. this.borderIB = null;
  11144. }
  11145. return true;
  11146. };
  11147. return Rectangle2DRenderCache;
  11148. }(BABYLON.ModelRenderCache));
  11149. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  11150. var Rectangle2DInstanceData = (function (_super) {
  11151. __extends(Rectangle2DInstanceData, _super);
  11152. function Rectangle2DInstanceData(partId) {
  11153. return _super.call(this, partId, 1) || this;
  11154. }
  11155. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  11156. get: function () {
  11157. return null;
  11158. },
  11159. set: function (value) {
  11160. },
  11161. enumerable: true,
  11162. configurable: true
  11163. });
  11164. return Rectangle2DInstanceData;
  11165. }(BABYLON.Shape2DInstanceData));
  11166. __decorate([
  11167. BABYLON.instanceData()
  11168. ], Rectangle2DInstanceData.prototype, "properties", null);
  11169. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  11170. var Rectangle2D = Rectangle2D_1 = (function (_super) {
  11171. __extends(Rectangle2D, _super);
  11172. /**
  11173. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  11174. * @param settings a combination of settings, possible ones are
  11175. * - 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)
  11176. * - children: an array of direct children
  11177. * - id a text identifier, for information purpose
  11178. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  11179. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  11180. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  11181. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  11182. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  11183. * - zOrder: override the zOrder with the specified value
  11184. * - origin: define the normalized origin point location, default [0.5;0.5]
  11185. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  11186. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  11187. * - 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)
  11188. * - 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)
  11189. * - borderThickness: the thickness of the drawn border, default is 1.
  11190. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  11191. * - 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.
  11192. * - 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.
  11193. * - 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!
  11194. * - 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.
  11195. * - 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).
  11196. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  11197. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11198. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11199. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11200. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11201. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  11202. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  11203. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  11204. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  11205. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11206. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11207. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11208. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11209. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  11210. */
  11211. function Rectangle2D(settings) {
  11212. var _this;
  11213. // Avoid checking every time if the object exists
  11214. if (settings == null) {
  11215. settings = {};
  11216. }
  11217. _this = _super.call(this, settings) || this;
  11218. if (settings.size != null) {
  11219. _this.size = settings.size;
  11220. }
  11221. else if (settings.width || settings.height) {
  11222. var size = new BABYLON.Size(settings.width, settings.height);
  11223. _this.size = size;
  11224. }
  11225. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  11226. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  11227. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  11228. //this.size = size;
  11229. _this.roundRadius = roundRadius;
  11230. _this.borderThickness = borderThickness;
  11231. return _this;
  11232. }
  11233. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  11234. get: function () {
  11235. if (this._actualSize) {
  11236. return this._actualSize;
  11237. }
  11238. return this.size;
  11239. },
  11240. set: function (value) {
  11241. this._actualSize = value;
  11242. },
  11243. enumerable: true,
  11244. configurable: true
  11245. });
  11246. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  11247. get: function () {
  11248. return this._notRounded;
  11249. },
  11250. set: function (value) {
  11251. this._notRounded = value;
  11252. },
  11253. enumerable: true,
  11254. configurable: true
  11255. });
  11256. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  11257. get: function () {
  11258. return this._roundRadius;
  11259. },
  11260. set: function (value) {
  11261. this._roundRadius = value;
  11262. this.notRounded = value === 0;
  11263. this._positioningDirty();
  11264. },
  11265. enumerable: true,
  11266. configurable: true
  11267. });
  11268. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  11269. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  11270. if (this.notRounded) {
  11271. return true;
  11272. }
  11273. // 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.
  11274. // 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)
  11275. // 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.
  11276. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  11277. var size = this.size;
  11278. Rectangle2D_1._i0.x = intersectInfo._localPickPosition.x;
  11279. Rectangle2D_1._i0.y = intersectInfo._localPickPosition.y;
  11280. var rr = this.roundRadius;
  11281. var rrs = rr * rr;
  11282. // Check if the point is in the bottom/left quarter area
  11283. Rectangle2D_1._i1.x = rr;
  11284. Rectangle2D_1._i1.y = rr;
  11285. if (Rectangle2D_1._i0.x <= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y <= Rectangle2D_1._i1.y) {
  11286. // Compute the intersection point in the quarter local space
  11287. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  11288. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  11289. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  11290. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  11291. }
  11292. // Check if the point is in the top/left quarter area
  11293. Rectangle2D_1._i1.x = rr;
  11294. Rectangle2D_1._i1.y = size.height - rr;
  11295. if (Rectangle2D_1._i0.x <= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y >= Rectangle2D_1._i1.y) {
  11296. // Compute the intersection point in the quarter local space
  11297. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  11298. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  11299. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  11300. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  11301. }
  11302. // Check if the point is in the top/right quarter area
  11303. Rectangle2D_1._i1.x = size.width - rr;
  11304. Rectangle2D_1._i1.y = size.height - rr;
  11305. if (Rectangle2D_1._i0.x >= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y >= Rectangle2D_1._i1.y) {
  11306. // Compute the intersection point in the quarter local space
  11307. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  11308. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  11309. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  11310. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  11311. }
  11312. // Check if the point is in the bottom/right quarter area
  11313. Rectangle2D_1._i1.x = size.width - rr;
  11314. Rectangle2D_1._i1.y = rr;
  11315. if (Rectangle2D_1._i0.x >= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y <= Rectangle2D_1._i1.y) {
  11316. // Compute the intersection point in the quarter local space
  11317. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  11318. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  11319. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  11320. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  11321. }
  11322. // At any other locations the point is guarantied to be inside
  11323. return true;
  11324. };
  11325. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  11326. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  11327. return true;
  11328. };
  11329. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  11330. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  11331. return renderCache;
  11332. };
  11333. Rectangle2D.prototype.updateTriArray = function () {
  11334. // Not Rounded = sharp edge rect, the default implementation is the right one!
  11335. if (this.notRounded) {
  11336. _super.prototype.updateTriArray.call(this);
  11337. return;
  11338. }
  11339. // Rounded Corner? It's more complicated! :)
  11340. var subDiv = Rectangle2D_1.roundSubdivisions * 4;
  11341. if (this._primTriArray == null) {
  11342. this._primTriArray = new BABYLON.Tri2DArray(subDiv);
  11343. }
  11344. else {
  11345. this._primTriArray.clear(subDiv);
  11346. }
  11347. var size = this.actualSize;
  11348. var w = size.width;
  11349. var h = size.height;
  11350. var r = this.roundRadius;
  11351. var rsub0 = subDiv * 0.25;
  11352. var rsub1 = subDiv * 0.50;
  11353. var rsub2 = subDiv * 0.75;
  11354. var center = new BABYLON.Vector2(0.5 * size.width, 0.5 * size.height);
  11355. var twopi = Math.PI * 2;
  11356. var nru = r / w;
  11357. var nrv = r / h;
  11358. var computePos = function (index, p) {
  11359. // right/bottom
  11360. if (index < rsub0) {
  11361. p.x = 1.0 - nru;
  11362. p.y = nrv;
  11363. }
  11364. else if (index < rsub1) {
  11365. p.x = nru;
  11366. p.y = nrv;
  11367. }
  11368. else if (index < rsub2) {
  11369. p.x = nru;
  11370. p.y = 1.0 - nrv;
  11371. }
  11372. else {
  11373. p.x = 1.0 - nru;
  11374. p.y = 1.0 - nrv;
  11375. }
  11376. var angle = twopi - (index * twopi / (subDiv - 0.5));
  11377. p.x += Math.cos(angle) * nru;
  11378. p.y += Math.sin(angle) * nrv;
  11379. p.x *= w;
  11380. p.y *= h;
  11381. };
  11382. console.log("Genetre TriList for " + this.id);
  11383. var first = BABYLON.Vector2.Zero();
  11384. var cur = BABYLON.Vector2.Zero();
  11385. computePos(0, first);
  11386. var prev = first.clone();
  11387. for (var index = 1; index < subDiv; index++) {
  11388. computePos(index, cur);
  11389. this._primTriArray.storeTriangle(index - 1, center, prev, cur);
  11390. console.log(index - 1 + ", " + center + ", " + prev + ", " + cur);
  11391. prev.copyFrom(cur);
  11392. }
  11393. this._primTriArray.storeTriangle(subDiv - 1, center, first, prev);
  11394. console.log(subDiv - 1 + ", " + center + ", " + prev + ", " + first);
  11395. };
  11396. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  11397. var renderCache = modelRenderCache;
  11398. var engine = this.owner.engine;
  11399. // Need to create WebGL resources for fill part?
  11400. if (this.fill) {
  11401. var vbSize = ((this.notRounded ? 1 : Rectangle2D_1.roundSubdivisions) * 4) + 1;
  11402. var vb = new Float32Array(vbSize);
  11403. for (var i = 0; i < vbSize; i++) {
  11404. vb[i] = i;
  11405. }
  11406. renderCache.fillVB = engine.createVertexBuffer(vb);
  11407. var triCount = vbSize - 1;
  11408. var ib = new Float32Array(triCount * 3);
  11409. for (var i = 0; i < triCount; i++) {
  11410. ib[i * 3 + 0] = 0;
  11411. ib[i * 3 + 2] = i + 1;
  11412. ib[i * 3 + 1] = i + 2;
  11413. }
  11414. ib[triCount * 3 - 2] = 1;
  11415. renderCache.fillIB = engine.createIndexBuffer(ib);
  11416. renderCache.fillIndicesCount = triCount * 3;
  11417. // 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
  11418. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  11419. if (ei) {
  11420. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11421. }
  11422. // Get the non instanced version
  11423. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  11424. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11425. }
  11426. // Need to create WebGL resource for border part?
  11427. if (this.border) {
  11428. var vbSize = (this.notRounded ? 1 : Rectangle2D_1.roundSubdivisions) * 4 * 2;
  11429. var vb = new Float32Array(vbSize);
  11430. for (var i = 0; i < vbSize; i++) {
  11431. vb[i] = i;
  11432. }
  11433. renderCache.borderVB = engine.createVertexBuffer(vb);
  11434. var triCount = vbSize;
  11435. var rs = triCount / 2;
  11436. var ib = new Float32Array(triCount * 3);
  11437. for (var i = 0; i < rs; i++) {
  11438. var r0 = i;
  11439. var r1 = (i + 1) % rs;
  11440. ib[i * 6 + 0] = rs + r1;
  11441. ib[i * 6 + 1] = rs + r0;
  11442. ib[i * 6 + 2] = r0;
  11443. ib[i * 6 + 3] = r1;
  11444. ib[i * 6 + 4] = rs + r1;
  11445. ib[i * 6 + 5] = r0;
  11446. }
  11447. renderCache.borderIB = engine.createIndexBuffer(ib);
  11448. renderCache.borderIndicesCount = triCount * 3;
  11449. // 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
  11450. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  11451. if (ei) {
  11452. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11453. }
  11454. // Get the non instanced version
  11455. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  11456. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11457. }
  11458. return renderCache;
  11459. };
  11460. // 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
  11461. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  11462. // Fall back to default implementation if there's no round Radius
  11463. if (this._notRounded) {
  11464. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  11465. }
  11466. else {
  11467. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  11468. initialContentPosition.x = initialContentPosition.y = rr;
  11469. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  11470. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  11471. initialContentPosition.z = primSize.width - (initialContentPosition.x + initialContentArea.width);
  11472. initialContentPosition.w = primSize.height - (initialContentPosition.y + initialContentArea.height);
  11473. }
  11474. };
  11475. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  11476. // Fall back to default implementation if there's no round Radius
  11477. if (this._notRounded) {
  11478. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
  11479. }
  11480. else {
  11481. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  11482. newPrimSize.copyFrom(primSize);
  11483. newPrimSize.width += rr * 2;
  11484. newPrimSize.height += rr * 2;
  11485. }
  11486. };
  11487. Rectangle2D.prototype.createInstanceDataParts = function () {
  11488. var res = new Array();
  11489. if (this.border) {
  11490. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  11491. }
  11492. if (this.fill) {
  11493. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  11494. }
  11495. return res;
  11496. };
  11497. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  11498. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  11499. return false;
  11500. }
  11501. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  11502. var d = part;
  11503. var size = this.actualSize;
  11504. var s = this.actualScale;
  11505. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  11506. }
  11507. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  11508. var d = part;
  11509. var size = this.actualSize;
  11510. var s = this.actualScale;
  11511. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  11512. }
  11513. return true;
  11514. };
  11515. return Rectangle2D;
  11516. }(BABYLON.Shape2D));
  11517. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  11518. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  11519. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  11520. Rectangle2D.roundSubdivisions = 16;
  11521. __decorate([
  11522. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D_1.actualSizeProperty = pi; }, false, true)
  11523. ], Rectangle2D.prototype, "actualSize", null);
  11524. __decorate([
  11525. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D_1.notRoundedProperty = pi; })
  11526. ], Rectangle2D.prototype, "notRounded", null);
  11527. __decorate([
  11528. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D_1.roundRadiusProperty = pi; })
  11529. ], Rectangle2D.prototype, "roundRadius", null);
  11530. Rectangle2D = Rectangle2D_1 = __decorate([
  11531. BABYLON.className("Rectangle2D", "BABYLON")
  11532. ], Rectangle2D);
  11533. BABYLON.Rectangle2D = Rectangle2D;
  11534. var Rectangle2D_1;
  11535. })(BABYLON || (BABYLON = {}));
  11536. var __extends = (this && this.__extends) || function (d, b) {
  11537. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11538. function __() { this.constructor = d; }
  11539. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  11540. };
  11541. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  11542. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  11543. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  11544. 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;
  11545. return c > 3 && r && Object.defineProperty(target, key, r), r;
  11546. };
  11547. var BABYLON;
  11548. (function (BABYLON) {
  11549. var Ellipse2DRenderCache = (function (_super) {
  11550. __extends(Ellipse2DRenderCache, _super);
  11551. function Ellipse2DRenderCache(engine, modelKey) {
  11552. var _this = _super.call(this, engine, modelKey) || this;
  11553. _this.effectsReady = false;
  11554. _this.fillVB = null;
  11555. _this.fillIB = null;
  11556. _this.fillIndicesCount = 0;
  11557. _this.instancingFillAttributes = null;
  11558. _this.effectFillInstanced = null;
  11559. _this.effectFill = null;
  11560. _this.borderVB = null;
  11561. _this.borderIB = null;
  11562. _this.borderIndicesCount = 0;
  11563. _this.instancingBorderAttributes = null;
  11564. _this.effectBorderInstanced = null;
  11565. _this.effectBorder = null;
  11566. return _this;
  11567. }
  11568. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  11569. // Do nothing if the shader is still loading/preparing
  11570. if (!this.effectsReady) {
  11571. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  11572. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  11573. return false;
  11574. }
  11575. this.effectsReady = true;
  11576. }
  11577. var canvas = instanceInfo.owner.owner;
  11578. var engine = canvas.engine;
  11579. var depthFunction = 0;
  11580. if (this.effectFill && this.effectBorder) {
  11581. depthFunction = engine.getDepthFunction();
  11582. engine.setDepthFunctionToLessOrEqual();
  11583. }
  11584. var curAlphaMode = engine.getAlphaMode();
  11585. if (this.effectFill) {
  11586. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  11587. var pid = context.groupInfoPartData[partIndex];
  11588. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  11589. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  11590. }
  11591. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  11592. engine.enableEffect(effect);
  11593. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  11594. if (context.useInstancing) {
  11595. if (!this.instancingFillAttributes) {
  11596. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  11597. }
  11598. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  11599. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  11600. canvas._addDrawCallCount(1, context.renderMode);
  11601. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  11602. engine.draw(true, 0, this.fillIndicesCount, count);
  11603. engine.unbindInstanceAttributes();
  11604. }
  11605. else {
  11606. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  11607. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  11608. this.setupUniforms(effect, partIndex, pid._partData, i);
  11609. engine.draw(true, 0, this.fillIndicesCount);
  11610. }
  11611. }
  11612. }
  11613. if (this.effectBorder) {
  11614. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  11615. var pid = context.groupInfoPartData[partIndex];
  11616. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  11617. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  11618. }
  11619. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  11620. engine.enableEffect(effect);
  11621. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  11622. if (context.useInstancing) {
  11623. if (!this.instancingBorderAttributes) {
  11624. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  11625. }
  11626. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  11627. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  11628. canvas._addDrawCallCount(1, context.renderMode);
  11629. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  11630. engine.draw(true, 0, this.borderIndicesCount, count);
  11631. engine.unbindInstanceAttributes();
  11632. }
  11633. else {
  11634. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  11635. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  11636. this.setupUniforms(effect, partIndex, pid._partData, i);
  11637. engine.draw(true, 0, this.borderIndicesCount);
  11638. }
  11639. }
  11640. }
  11641. engine.setAlphaMode(curAlphaMode, true);
  11642. if (this.effectFill && this.effectBorder) {
  11643. engine.setDepthFunction(depthFunction);
  11644. }
  11645. return true;
  11646. };
  11647. Ellipse2DRenderCache.prototype.dispose = function () {
  11648. if (!_super.prototype.dispose.call(this)) {
  11649. return false;
  11650. }
  11651. if (this.fillVB) {
  11652. this._engine._releaseBuffer(this.fillVB);
  11653. this.fillVB = null;
  11654. }
  11655. if (this.fillIB) {
  11656. this._engine._releaseBuffer(this.fillIB);
  11657. this.fillIB = null;
  11658. }
  11659. this.effectFill = null;
  11660. this.effectFillInstanced = null;
  11661. this.effectBorder = null;
  11662. this.effectBorderInstanced = null;
  11663. if (this.borderVB) {
  11664. this._engine._releaseBuffer(this.borderVB);
  11665. this.borderVB = null;
  11666. }
  11667. if (this.borderIB) {
  11668. this._engine._releaseBuffer(this.borderIB);
  11669. this.borderIB = null;
  11670. }
  11671. return true;
  11672. };
  11673. return Ellipse2DRenderCache;
  11674. }(BABYLON.ModelRenderCache));
  11675. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  11676. var Ellipse2DInstanceData = (function (_super) {
  11677. __extends(Ellipse2DInstanceData, _super);
  11678. function Ellipse2DInstanceData(partId) {
  11679. return _super.call(this, partId, 1) || this;
  11680. }
  11681. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  11682. get: function () {
  11683. return null;
  11684. },
  11685. set: function (value) {
  11686. },
  11687. enumerable: true,
  11688. configurable: true
  11689. });
  11690. return Ellipse2DInstanceData;
  11691. }(BABYLON.Shape2DInstanceData));
  11692. __decorate([
  11693. BABYLON.instanceData()
  11694. ], Ellipse2DInstanceData.prototype, "properties", null);
  11695. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  11696. var Ellipse2D = Ellipse2D_1 = (function (_super) {
  11697. __extends(Ellipse2D, _super);
  11698. /**
  11699. * Create an Ellipse 2D Shape primitive
  11700. * @param settings a combination of settings, possible ones are
  11701. * - 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)
  11702. * - children: an array of direct children
  11703. * - id: a text identifier, for information purpose
  11704. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  11705. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  11706. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  11707. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  11708. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  11709. * - zOrder: override the zOrder with the specified value
  11710. * - origin: define the normalized origin point location, default [0.5;0.5]
  11711. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  11712. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  11713. * - 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)
  11714. * - 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)
  11715. * - borderThickness: the thickness of the drawn border, default is 1.
  11716. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  11717. * - 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.
  11718. * - 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.
  11719. * - 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!
  11720. * - 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.
  11721. * - 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).
  11722. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  11723. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11724. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11725. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11726. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11727. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  11728. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  11729. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  11730. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  11731. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11732. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11733. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11734. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11735. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  11736. */
  11737. function Ellipse2D(settings) {
  11738. var _this;
  11739. // Avoid checking every time if the object exists
  11740. if (settings == null) {
  11741. settings = {};
  11742. }
  11743. _this = _super.call(this, settings) || this;
  11744. if (settings.size != null) {
  11745. _this.size = settings.size;
  11746. }
  11747. else if (settings.width || settings.height) {
  11748. var size = new BABYLON.Size(settings.width, settings.height);
  11749. _this.size = size;
  11750. }
  11751. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  11752. _this.subdivisions = sub;
  11753. return _this;
  11754. }
  11755. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  11756. get: function () {
  11757. if (this._actualSize) {
  11758. return this._actualSize;
  11759. }
  11760. return this.size;
  11761. },
  11762. set: function (value) {
  11763. this._actualSize = value;
  11764. },
  11765. enumerable: true,
  11766. configurable: true
  11767. });
  11768. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  11769. get: function () {
  11770. return this._subdivisions;
  11771. },
  11772. set: function (value) {
  11773. this._subdivisions = value;
  11774. },
  11775. enumerable: true,
  11776. configurable: true
  11777. });
  11778. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  11779. var w = this.size.width / 2;
  11780. var h = this.size.height / 2;
  11781. var x = intersectInfo._localPickPosition.x - w;
  11782. var y = intersectInfo._localPickPosition.y - h;
  11783. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  11784. };
  11785. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  11786. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  11787. return true;
  11788. };
  11789. Ellipse2D.prototype.updateTriArray = function () {
  11790. var subDiv = this._subdivisions;
  11791. if (this._primTriArray == null) {
  11792. this._primTriArray = new BABYLON.Tri2DArray(subDiv);
  11793. }
  11794. else {
  11795. this._primTriArray.clear(subDiv);
  11796. }
  11797. var size = this.actualSize;
  11798. var center = new BABYLON.Vector2(0.5 * size.width, 0.5 * size.height);
  11799. var v1 = BABYLON.Vector2.Zero();
  11800. var v2 = BABYLON.Vector2.Zero();
  11801. for (var i = 0; i < subDiv; i++) {
  11802. var angle1 = Math.PI * 2 * (i - 1) / subDiv;
  11803. var angle2 = Math.PI * 2 * i / subDiv;
  11804. v1.x = ((Math.cos(angle1) / 2.0) + 0.5) * size.width;
  11805. v1.y = ((Math.sin(angle1) / 2.0) + 0.5) * size.height;
  11806. v2.x = ((Math.cos(angle2) / 2.0) + 0.5) * size.width;
  11807. v2.y = ((Math.sin(angle2) / 2.0) + 0.5) * size.height;
  11808. this._primTriArray.storeTriangle(i, center, v1, v2);
  11809. }
  11810. };
  11811. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  11812. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  11813. return renderCache;
  11814. };
  11815. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  11816. var renderCache = modelRenderCache;
  11817. var engine = this.owner.engine;
  11818. // Need to create WebGL resources for fill part?
  11819. if (this.fill) {
  11820. var vbSize = this.subdivisions + 1;
  11821. var vb = new Float32Array(vbSize);
  11822. for (var i = 0; i < vbSize; i++) {
  11823. vb[i] = i;
  11824. }
  11825. renderCache.fillVB = engine.createVertexBuffer(vb);
  11826. var triCount = vbSize - 1;
  11827. var ib = new Float32Array(triCount * 3);
  11828. for (var i = 0; i < triCount; i++) {
  11829. ib[i * 3 + 0] = 0;
  11830. ib[i * 3 + 2] = i + 1;
  11831. ib[i * 3 + 1] = i + 2;
  11832. }
  11833. ib[triCount * 3 - 2] = 1;
  11834. renderCache.fillIB = engine.createIndexBuffer(ib);
  11835. renderCache.fillIndicesCount = triCount * 3;
  11836. // 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
  11837. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  11838. if (ei) {
  11839. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  11840. }
  11841. // Get the non instanced version
  11842. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  11843. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  11844. }
  11845. // Need to create WebGL resource for border part?
  11846. if (this.border) {
  11847. var vbSize = this.subdivisions * 2;
  11848. var vb = new Float32Array(vbSize);
  11849. for (var i = 0; i < vbSize; i++) {
  11850. vb[i] = i;
  11851. }
  11852. renderCache.borderVB = engine.createVertexBuffer(vb);
  11853. var triCount = vbSize;
  11854. var rs = triCount / 2;
  11855. var ib = new Float32Array(triCount * 3);
  11856. for (var i = 0; i < rs; i++) {
  11857. var r0 = i;
  11858. var r1 = (i + 1) % rs;
  11859. ib[i * 6 + 0] = rs + r1;
  11860. ib[i * 6 + 1] = rs + r0;
  11861. ib[i * 6 + 2] = r0;
  11862. ib[i * 6 + 3] = r1;
  11863. ib[i * 6 + 4] = rs + r1;
  11864. ib[i * 6 + 5] = r0;
  11865. }
  11866. renderCache.borderIB = engine.createIndexBuffer(ib);
  11867. renderCache.borderIndicesCount = (triCount * 3);
  11868. // 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
  11869. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  11870. if (ei) {
  11871. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11872. }
  11873. // Get the non instanced version
  11874. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  11875. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11876. }
  11877. return renderCache;
  11878. };
  11879. Ellipse2D.prototype.createInstanceDataParts = function () {
  11880. var res = new Array();
  11881. if (this.border) {
  11882. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  11883. }
  11884. if (this.fill) {
  11885. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  11886. }
  11887. return res;
  11888. };
  11889. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  11890. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  11891. return false;
  11892. }
  11893. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  11894. var d = part;
  11895. var size = this.actualSize;
  11896. var s = this.actualScale;
  11897. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  11898. }
  11899. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  11900. var d = part;
  11901. var size = this.actualSize;
  11902. var s = this.actualScale;
  11903. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  11904. }
  11905. return true;
  11906. };
  11907. return Ellipse2D;
  11908. }(BABYLON.Shape2D));
  11909. __decorate([
  11910. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D_1.acutalSizeProperty = pi; }, false, true)
  11911. ], Ellipse2D.prototype, "actualSize", null);
  11912. __decorate([
  11913. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D_1.subdivisionsProperty = pi; })
  11914. ], Ellipse2D.prototype, "subdivisions", null);
  11915. Ellipse2D = Ellipse2D_1 = __decorate([
  11916. BABYLON.className("Ellipse2D", "BABYLON")
  11917. ], Ellipse2D);
  11918. BABYLON.Ellipse2D = Ellipse2D;
  11919. var Ellipse2D_1;
  11920. })(BABYLON || (BABYLON = {}));
  11921. var __extends = (this && this.__extends) || function (d, b) {
  11922. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11923. function __() { this.constructor = d; }
  11924. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  11925. };
  11926. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  11927. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  11928. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  11929. 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;
  11930. return c > 3 && r && Object.defineProperty(target, key, r), r;
  11931. };
  11932. var BABYLON;
  11933. (function (BABYLON) {
  11934. var Sprite2DRenderCache = (function (_super) {
  11935. __extends(Sprite2DRenderCache, _super);
  11936. function Sprite2DRenderCache() {
  11937. var _this = _super.apply(this, arguments) || this;
  11938. _this.effectsReady = false;
  11939. _this.vb = null;
  11940. _this.ib = null;
  11941. _this.instancingAttributes = null;
  11942. _this.texture = null;
  11943. _this.effect = null;
  11944. _this.effectInstanced = null;
  11945. return _this;
  11946. }
  11947. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  11948. // Do nothing if the shader is still loading/preparing
  11949. if (!this.effectsReady) {
  11950. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  11951. return false;
  11952. }
  11953. this.effectsReady = true;
  11954. }
  11955. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  11956. var canvas = instanceInfo.owner.owner;
  11957. var engine = canvas.engine;
  11958. var cur = engine.getAlphaMode();
  11959. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  11960. engine.enableEffect(effect);
  11961. effect.setTexture("diffuseSampler", this.texture);
  11962. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  11963. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  11964. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  11965. }
  11966. effect.setBool("alphaTest", context.renderMode === BABYLON.Render2DContext.RenderModeAlphaTest);
  11967. var pid = context.groupInfoPartData[0];
  11968. if (context.useInstancing) {
  11969. if (!this.instancingAttributes) {
  11970. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  11971. }
  11972. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  11973. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  11974. canvas._addDrawCallCount(1, context.renderMode);
  11975. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  11976. engine.draw(true, 0, 6, count);
  11977. engine.unbindInstanceAttributes();
  11978. }
  11979. else {
  11980. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  11981. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  11982. this.setupUniforms(effect, 0, pid._partData, i);
  11983. engine.draw(true, 0, 6);
  11984. }
  11985. }
  11986. engine.setAlphaMode(cur, true);
  11987. return true;
  11988. };
  11989. Sprite2DRenderCache.prototype.dispose = function () {
  11990. if (!_super.prototype.dispose.call(this)) {
  11991. return false;
  11992. }
  11993. if (this.vb) {
  11994. this._engine._releaseBuffer(this.vb);
  11995. this.vb = null;
  11996. }
  11997. if (this.ib) {
  11998. this._engine._releaseBuffer(this.ib);
  11999. this.ib = null;
  12000. }
  12001. //if (this.texture) {
  12002. // this.texture.dispose();
  12003. // this.texture = null;
  12004. //}
  12005. this.effect = null;
  12006. this.effectInstanced = null;
  12007. return true;
  12008. };
  12009. return Sprite2DRenderCache;
  12010. }(BABYLON.ModelRenderCache));
  12011. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  12012. var Sprite2D = Sprite2D_1 = (function (_super) {
  12013. __extends(Sprite2D, _super);
  12014. /**
  12015. * Create an 2D Sprite primitive
  12016. * @param texture the texture that stores the sprite to render
  12017. * @param settings a combination of settings, possible ones are
  12018. * - 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)
  12019. * - children: an array of direct children
  12020. * - id a text identifier, for information purpose
  12021. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  12022. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  12023. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  12024. * - size: the size of the sprite displayed in the canvas, if not specified the spriteSize will be used
  12025. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  12026. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  12027. * - zOrder: override the zOrder with the specified value
  12028. * - origin: define the normalized origin point location, default [0.5;0.5]
  12029. * - 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.
  12030. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  12031. * - spriteScaleFactor: DEPRECATED. Old behavior: say you want to display a sprite twice as big as its bitmap which is 64,64, you set the spriteSize to 128,128 and have to set the spriteScaleFactory to 0.5,0.5 in order to address only the 64,64 pixels of the bitmaps. Default is 1,1.
  12032. * - 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
  12033. * - invertY: if true the texture Y will be inverted, default is false.
  12034. * - 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.
  12035. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  12036. * - 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.
  12037. * - 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.
  12038. * - 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!
  12039. * - 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.
  12040. * - 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).
  12041. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  12042. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12043. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12044. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12045. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12046. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  12047. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  12048. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  12049. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  12050. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12051. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12052. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12053. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12054. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  12055. */
  12056. function Sprite2D(texture, settings) {
  12057. var _this;
  12058. if (!settings) {
  12059. settings = {};
  12060. }
  12061. _this = _super.call(this, settings) || this;
  12062. _this.texture = texture;
  12063. _this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12064. _this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12065. _this._useSize = false;
  12066. _this.spriteSize = (settings.spriteSize != null) ? settings.spriteSize.clone() : null;
  12067. _this.spriteLocation = (settings.spriteLocation != null) ? settings.spriteLocation.clone() : new BABYLON.Vector2(0, 0);
  12068. if (settings.size != null) {
  12069. _this.size = settings.size;
  12070. }
  12071. _this.spriteFrame = 0;
  12072. _this.invertY = (settings.invertY == null) ? false : settings.invertY;
  12073. _this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  12074. _this.useAlphaFromTexture = true;
  12075. _this._scale9 = (settings.scale9 != null) ? settings.scale9.clone() : null;
  12076. // 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.
  12077. // The fucking delayed texture sprite bug is fixed!
  12078. if (settings.spriteSize == null) {
  12079. _this.spriteSize = new BABYLON.Size(10, 10);
  12080. }
  12081. if (settings.spriteSize == null || !texture.isReady()) {
  12082. if (texture.isReady()) {
  12083. var s = texture.getBaseSize();
  12084. _this.spriteSize = new BABYLON.Size(s.width, s.height);
  12085. _this._updateSpriteScaleFactor();
  12086. }
  12087. else {
  12088. texture.onLoadObservable.add(function () {
  12089. if (settings.spriteSize == null) {
  12090. var s = texture.getBaseSize();
  12091. _this.spriteSize = new BABYLON.Size(s.width, s.height);
  12092. }
  12093. _this._updateSpriteScaleFactor();
  12094. _this._positioningDirty();
  12095. _this._setLayoutDirty();
  12096. _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId | Sprite2D_1.textureProperty.flagId; // To make sure the sprite is issued again for render
  12097. });
  12098. }
  12099. }
  12100. return _this;
  12101. }
  12102. Object.defineProperty(Sprite2D.prototype, "texture", {
  12103. get: function () {
  12104. return this._texture;
  12105. },
  12106. set: function (value) {
  12107. this._texture = value;
  12108. this._oldTextureHasAlpha = this._texture && this.texture.hasAlpha;
  12109. },
  12110. enumerable: true,
  12111. configurable: true
  12112. });
  12113. Object.defineProperty(Sprite2D.prototype, "useAlphaFromTexture", {
  12114. get: function () {
  12115. return this._useAlphaFromTexture;
  12116. },
  12117. set: function (value) {
  12118. if (this._useAlphaFromTexture === value) {
  12119. return;
  12120. }
  12121. this._useAlphaFromTexture = value;
  12122. this._updateRenderMode();
  12123. },
  12124. enumerable: true,
  12125. configurable: true
  12126. });
  12127. Object.defineProperty(Sprite2D.prototype, "size", {
  12128. get: function () {
  12129. if (this._size == null) {
  12130. return this.spriteSize;
  12131. }
  12132. return this.internalGetSize();
  12133. },
  12134. set: function (value) {
  12135. this._useSize = value != null;
  12136. this.internalSetSize(value);
  12137. this._updateSpriteScaleFactor();
  12138. },
  12139. enumerable: true,
  12140. configurable: true
  12141. });
  12142. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  12143. get: function () {
  12144. if (this._actualSize) {
  12145. return this._actualSize;
  12146. }
  12147. return this.size;
  12148. },
  12149. set: function (value) {
  12150. this._actualSize = value;
  12151. },
  12152. enumerable: true,
  12153. configurable: true
  12154. });
  12155. Object.defineProperty(Sprite2D.prototype, "spriteSize", {
  12156. get: function () {
  12157. return this._spriteSize;
  12158. },
  12159. set: function (value) {
  12160. this._spriteSize = value;
  12161. this._updateSpriteScaleFactor();
  12162. },
  12163. enumerable: true,
  12164. configurable: true
  12165. });
  12166. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  12167. get: function () {
  12168. return this._spriteLocation;
  12169. },
  12170. set: function (value) {
  12171. this._spriteLocation = value;
  12172. },
  12173. enumerable: true,
  12174. configurable: true
  12175. });
  12176. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  12177. get: function () {
  12178. return this._spriteFrame;
  12179. },
  12180. set: function (value) {
  12181. this._spriteFrame = value;
  12182. },
  12183. enumerable: true,
  12184. configurable: true
  12185. });
  12186. Object.defineProperty(Sprite2D.prototype, "invertY", {
  12187. get: function () {
  12188. return this._invertY;
  12189. },
  12190. set: function (value) {
  12191. this._invertY = value;
  12192. },
  12193. enumerable: true,
  12194. configurable: true
  12195. });
  12196. Object.defineProperty(Sprite2D.prototype, "isScale9", {
  12197. get: function () {
  12198. return this._scale9 !== null;
  12199. },
  12200. enumerable: true,
  12201. configurable: true
  12202. });
  12203. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  12204. //@instanceLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, pi => Sprite2D.spriteScaleFactorProperty = pi)
  12205. ///**
  12206. // * Get/set the sprite location (in pixels) in the texture
  12207. // */
  12208. //public get spriteScaleFactor(): Vector2 {
  12209. // return this._spriteScaleFactor;
  12210. //}
  12211. //public set spriteScaleFactor(value: Vector2) {
  12212. // this._spriteScaleFactor = value;
  12213. //}
  12214. /**
  12215. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  12216. */
  12217. get: function () {
  12218. return this._alignToPixel;
  12219. },
  12220. set: function (value) {
  12221. this._alignToPixel = value;
  12222. },
  12223. enumerable: true,
  12224. configurable: true
  12225. });
  12226. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  12227. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  12228. return true;
  12229. };
  12230. /**
  12231. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  12232. */
  12233. Sprite2D.prototype.getAnimatables = function () {
  12234. var res = new Array();
  12235. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  12236. res.push(this.texture);
  12237. }
  12238. return res;
  12239. };
  12240. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  12241. // 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
  12242. return true;
  12243. };
  12244. Object.defineProperty(Sprite2D.prototype, "isSizeAuto", {
  12245. get: function () {
  12246. return this.size == null;
  12247. },
  12248. enumerable: true,
  12249. configurable: true
  12250. });
  12251. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  12252. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  12253. return renderCache;
  12254. };
  12255. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  12256. var renderCache = modelRenderCache;
  12257. var engine = this.owner.engine;
  12258. var vb = new Float32Array(4);
  12259. for (var i = 0; i < 4; i++) {
  12260. vb[i] = i;
  12261. }
  12262. renderCache.vb = engine.createVertexBuffer(vb);
  12263. var ib = new Float32Array(6);
  12264. ib[0] = 0;
  12265. ib[1] = 2;
  12266. ib[2] = 1;
  12267. ib[3] = 0;
  12268. ib[4] = 3;
  12269. ib[5] = 2;
  12270. renderCache.ib = engine.createIndexBuffer(ib);
  12271. renderCache.texture = this.texture;
  12272. // 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
  12273. var ei = this.getDataPartEffectInfo(Sprite2D_1.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], true);
  12274. if (ei) {
  12275. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  12276. }
  12277. ei = this.getDataPartEffectInfo(Sprite2D_1.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], false);
  12278. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  12279. return renderCache;
  12280. };
  12281. Sprite2D.prototype.getUsedShaderCategories = function (dataPart) {
  12282. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  12283. if (dataPart.id === Sprite2D_1.SPRITE2D_MAINPARTID) {
  12284. var useScale9 = this._scale9 != null;
  12285. if (useScale9) {
  12286. cat.push(Sprite2D_1.SHAPE2D_CATEGORY_SCALE9);
  12287. }
  12288. }
  12289. return cat;
  12290. };
  12291. Sprite2D.prototype.createInstanceDataParts = function () {
  12292. return [new Sprite2DInstanceData(Sprite2D_1.SPRITE2D_MAINPARTID)];
  12293. };
  12294. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  12295. Sprite2D_1.layoutConstructMode = true;
  12296. };
  12297. // if obj contains something, we restore the _text property
  12298. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  12299. Sprite2D_1.layoutConstructMode = false;
  12300. };
  12301. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  12302. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  12303. return false;
  12304. }
  12305. if (!this.texture.isReady() && !Sprite2D_1.layoutConstructMode) {
  12306. return false;
  12307. }
  12308. if (part.id === Sprite2D_1.SPRITE2D_MAINPARTID) {
  12309. var d = this._instanceDataParts[0];
  12310. if (Sprite2D_1.layoutConstructMode) {
  12311. d.topLeftUV = BABYLON.Vector2.Zero();
  12312. d.sizeUV = BABYLON.Vector2.Zero();
  12313. d.properties = BABYLON.Vector3.Zero();
  12314. d.textureSize = BABYLON.Vector2.Zero();
  12315. d.scaleFactor = BABYLON.Vector2.Zero();
  12316. if (this.isScale9) {
  12317. d.scale9 = BABYLON.Vector4.Zero();
  12318. }
  12319. }
  12320. else {
  12321. var ts = this.texture.getBaseSize();
  12322. var ss = this.spriteSize;
  12323. var sl = this.spriteLocation;
  12324. var ssf = this.actualScale;
  12325. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  12326. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  12327. d.sizeUV = suv;
  12328. d.scaleFactor = ssf;
  12329. Sprite2D_1._prop.x = this.spriteFrame;
  12330. Sprite2D_1._prop.y = this.invertY ? 1 : 0;
  12331. Sprite2D_1._prop.z = this.alignToPixel ? 1 : 0;
  12332. d.properties = Sprite2D_1._prop;
  12333. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  12334. var scale9 = this._scale9;
  12335. if (scale9 != null) {
  12336. 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);
  12337. d.scale9 = normalizedScale9;
  12338. }
  12339. }
  12340. }
  12341. return true;
  12342. };
  12343. Sprite2D.prototype._mustUpdateInstance = function () {
  12344. var res = this._oldTextureHasAlpha !== (this.texture != null && this.texture.hasAlpha);
  12345. this._oldTextureHasAlpha = this.texture != null && this.texture.hasAlpha;
  12346. if (res) {
  12347. this._updateRenderMode();
  12348. }
  12349. return res;
  12350. };
  12351. Sprite2D.prototype._useTextureAlpha = function () {
  12352. return this.texture != null && this.texture.hasAlpha;
  12353. };
  12354. Sprite2D.prototype._shouldUseAlphaFromTexture = function () {
  12355. return this.texture != null && this.texture.hasAlpha && this.useAlphaFromTexture;
  12356. };
  12357. Sprite2D.prototype._updateSpriteScaleFactor = function () {
  12358. if (!this._useSize) {
  12359. return;
  12360. }
  12361. var sS = this.spriteSize;
  12362. var s = this.size;
  12363. if (s == null || sS == null) {
  12364. return;
  12365. }
  12366. this.scaleX = s.width / sS.width;
  12367. this.scaleY = s.height / sS.height;
  12368. };
  12369. return Sprite2D;
  12370. }(BABYLON.RenderablePrim2D));
  12371. Sprite2D.SPRITE2D_MAINPARTID = 1;
  12372. Sprite2D.SHAPE2D_CATEGORY_SCALE9 = "Scale9";
  12373. Sprite2D._prop = BABYLON.Vector3.Zero();
  12374. Sprite2D.layoutConstructMode = false;
  12375. __decorate([
  12376. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D_1.textureProperty = pi; })
  12377. ], Sprite2D.prototype, "texture", null);
  12378. __decorate([
  12379. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D_1.useAlphaFromTextureProperty = pi; })
  12380. ], Sprite2D.prototype, "useAlphaFromTexture", null);
  12381. __decorate([
  12382. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D_1.actualSizeProperty = pi; }, false, true)
  12383. ], Sprite2D.prototype, "actualSize", null);
  12384. __decorate([
  12385. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D_1.spriteSizeProperty = pi; })
  12386. ], Sprite2D.prototype, "spriteSize", null);
  12387. __decorate([
  12388. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D_1.spriteLocationProperty = pi; })
  12389. ], Sprite2D.prototype, "spriteLocation", null);
  12390. __decorate([
  12391. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D_1.spriteFrameProperty = pi; })
  12392. ], Sprite2D.prototype, "spriteFrame", null);
  12393. __decorate([
  12394. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Sprite2D_1.invertYProperty = pi; })
  12395. ], Sprite2D.prototype, "invertY", null);
  12396. __decorate([
  12397. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 8, function (pi) { return Sprite2D_1.spriteScale9Property = pi; })
  12398. ], Sprite2D.prototype, "isScale9", null);
  12399. Sprite2D = Sprite2D_1 = __decorate([
  12400. BABYLON.className("Sprite2D", "BABYLON")
  12401. ], Sprite2D);
  12402. BABYLON.Sprite2D = Sprite2D;
  12403. var Sprite2DInstanceData = (function (_super) {
  12404. __extends(Sprite2DInstanceData, _super);
  12405. function Sprite2DInstanceData(partId) {
  12406. return _super.call(this, partId, 1) || this;
  12407. }
  12408. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  12409. get: function () {
  12410. return null;
  12411. },
  12412. set: function (value) {
  12413. },
  12414. enumerable: true,
  12415. configurable: true
  12416. });
  12417. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  12418. get: function () {
  12419. return null;
  12420. },
  12421. set: function (value) {
  12422. },
  12423. enumerable: true,
  12424. configurable: true
  12425. });
  12426. Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
  12427. get: function () {
  12428. return null;
  12429. },
  12430. set: function (value) {
  12431. },
  12432. enumerable: true,
  12433. configurable: true
  12434. });
  12435. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  12436. get: function () {
  12437. return null;
  12438. },
  12439. set: function (value) {
  12440. },
  12441. enumerable: true,
  12442. configurable: true
  12443. });
  12444. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  12445. // 3 floats being:
  12446. // - x: frame number to display
  12447. // - y: invertY setting
  12448. // - z: alignToPixel setting
  12449. get: function () {
  12450. return null;
  12451. },
  12452. set: function (value) {
  12453. },
  12454. enumerable: true,
  12455. configurable: true
  12456. });
  12457. Object.defineProperty(Sprite2DInstanceData.prototype, "scale9", {
  12458. get: function () {
  12459. return null;
  12460. },
  12461. set: function (value) {
  12462. },
  12463. enumerable: true,
  12464. configurable: true
  12465. });
  12466. return Sprite2DInstanceData;
  12467. }(BABYLON.InstanceDataBase));
  12468. __decorate([
  12469. BABYLON.instanceData()
  12470. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  12471. __decorate([
  12472. BABYLON.instanceData()
  12473. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  12474. __decorate([
  12475. BABYLON.instanceData(Sprite2D.SHAPE2D_CATEGORY_SCALE9)
  12476. ], Sprite2DInstanceData.prototype, "scaleFactor", null);
  12477. __decorate([
  12478. BABYLON.instanceData()
  12479. ], Sprite2DInstanceData.prototype, "textureSize", null);
  12480. __decorate([
  12481. BABYLON.instanceData()
  12482. ], Sprite2DInstanceData.prototype, "properties", null);
  12483. __decorate([
  12484. BABYLON.instanceData(Sprite2D.SHAPE2D_CATEGORY_SCALE9)
  12485. ], Sprite2DInstanceData.prototype, "scale9", null);
  12486. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  12487. var Sprite2D_1;
  12488. })(BABYLON || (BABYLON = {}));
  12489. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  12490. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  12491. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  12492. 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;
  12493. return c > 3 && r && Object.defineProperty(target, key, r), r;
  12494. };
  12495. var BABYLON;
  12496. (function (BABYLON) {
  12497. /**
  12498. * This class will contains information about a sub picture present in an Atlas Picture.
  12499. */
  12500. var AtlasSubPictureInfo = (function () {
  12501. function AtlasSubPictureInfo() {
  12502. }
  12503. return AtlasSubPictureInfo;
  12504. }());
  12505. BABYLON.AtlasSubPictureInfo = AtlasSubPictureInfo;
  12506. /**
  12507. * This class represent an Atlas Picture, it contains the information of all the sub pictures and the Texture that stores the bitmap.
  12508. * You get an instance of this class using methods of the AtlasPictureInfoFactory
  12509. */
  12510. var AtlasPictureInfo = (function () {
  12511. function AtlasPictureInfo() {
  12512. }
  12513. /**
  12514. * Creates many sprite from the Atlas Picture
  12515. * @param filterCallback a predicate if true is returned then the corresponding sub picture will be used to create a sprite.
  12516. * The Predicate has many parameters:
  12517. * - index: just an index incremented at each sub picture submitted for Sprite creation
  12518. * - name: the sub picture's name
  12519. * - aspi: the AtlasSubPictureInfo corresponding to the submitted sub picture
  12520. * - settings: the Sprite2D creation settings, you can alter this JSON object but BEWARE, the alterations will be kept for subsequent Sprite2D creations!
  12521. * @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.
  12522. */
  12523. AtlasPictureInfo.prototype.createSprites = function (filterCallback, spriteSettings) {
  12524. var _this = this;
  12525. var res = new Array();
  12526. var index = 0;
  12527. this.subPictures.forEach(function (k, v) {
  12528. if (!filterCallback || filterCallback(index++, k, v, spriteSettings)) {
  12529. var s = _this.createSprite(k, spriteSettings);
  12530. if (s) {
  12531. res.push(s);
  12532. }
  12533. }
  12534. });
  12535. return res;
  12536. };
  12537. /**
  12538. * Create one Sprite from a sub picture
  12539. * @param subPictureName the name of the sub picture to use
  12540. * @param spriteSettings the Sprite2D settings to use for the Sprite instance creation
  12541. */
  12542. AtlasPictureInfo.prototype.createSprite = function (subPictureName, spriteSettings) {
  12543. var spi = this.subPictures.get(subPictureName);
  12544. if (!spi) {
  12545. return null;
  12546. }
  12547. if (!spriteSettings) {
  12548. spriteSettings = {};
  12549. }
  12550. var s = spriteSettings;
  12551. s.id = subPictureName;
  12552. s.spriteLocation = spi.location;
  12553. s.spriteSize = spi.size;
  12554. var sprite = new BABYLON.Sprite2D(this.texture, spriteSettings);
  12555. return sprite;
  12556. };
  12557. return AtlasPictureInfo;
  12558. }());
  12559. BABYLON.AtlasPictureInfo = AtlasPictureInfo;
  12560. /**
  12561. * This if the Factory class containing static method to create Atlas Pictures Info objects or add new loaders
  12562. */
  12563. var AtlasPictureInfoFactory = (function () {
  12564. function AtlasPictureInfoFactory() {
  12565. }
  12566. /**
  12567. * Add a custom loader
  12568. * @param fileExtension must be the file extension (without the dot) of the file that is loaded by this loader (e.g.: json)
  12569. * @param plugin the instance of the loader
  12570. */
  12571. AtlasPictureInfoFactory.addLoader = function (fileExtension, plugin) {
  12572. var a = AtlasPictureInfoFactory.plugins.getOrAddWithFactory(fileExtension.toLocaleLowerCase(), function () { return new Array(); });
  12573. a.push(plugin);
  12574. };
  12575. /**
  12576. * Load an Atlas Picture Info object from a data file at a given url and with a given texture
  12577. * @param texture the texture containing the atlas bitmap
  12578. * @param url the URL of the Atlas Info data file
  12579. * @param onLoad a callback that will be called when the AtlasPictureInfo object will be loaded and ready
  12580. * @param onError a callback that will be called in case of error
  12581. */
  12582. AtlasPictureInfoFactory.loadFromUrl = function (texture, url, onLoad, onError) {
  12583. if (onError === void 0) { onError = null; }
  12584. var xhr = new XMLHttpRequest();
  12585. xhr.onreadystatechange = function () {
  12586. if (xhr.readyState === XMLHttpRequest.DONE) {
  12587. if (xhr.status === 200) {
  12588. var ext = url.split('.').pop().split(/\#|\?/)[0];
  12589. var plugins = AtlasPictureInfoFactory.plugins.get(ext.toLocaleLowerCase());
  12590. if (!plugins) {
  12591. if (onError) {
  12592. onError("couldn't find a plugin for this file extension", -1);
  12593. }
  12594. return;
  12595. }
  12596. for (var _i = 0, plugins_1 = plugins; _i < plugins_1.length; _i++) {
  12597. var p = plugins_1[_i];
  12598. var ret = p.loadFile(xhr.response);
  12599. if (ret) {
  12600. if (ret.api) {
  12601. ret.api.texture = texture;
  12602. if (onLoad) {
  12603. onLoad(ret.api);
  12604. }
  12605. }
  12606. else if (onError) {
  12607. onError(ret.errorMsg, ret.errorCode);
  12608. }
  12609. return;
  12610. }
  12611. }
  12612. if (onError) {
  12613. onError("No plugin to load this Atlas Data file format", -1);
  12614. }
  12615. }
  12616. else {
  12617. if (onError) {
  12618. onError("Couldn't load file through HTTP Request, HTTP Status " + xhr.status, xhr.status);
  12619. }
  12620. }
  12621. }
  12622. };
  12623. xhr.open("GET", url, true);
  12624. xhr.send();
  12625. return null;
  12626. };
  12627. return AtlasPictureInfoFactory;
  12628. }());
  12629. AtlasPictureInfoFactory.plugins = new BABYLON.StringDictionary();
  12630. BABYLON.AtlasPictureInfoFactory = AtlasPictureInfoFactory;
  12631. // Loader class for the TexturePacker's JSON Array data format
  12632. var JSONArrayLoader = JSONArrayLoader_1 = (function () {
  12633. function JSONArrayLoader() {
  12634. }
  12635. JSONArrayLoader.prototype.loadFile = function (content) {
  12636. var errorMsg = null;
  12637. var errorCode = 0;
  12638. var root = null;
  12639. var api = null;
  12640. try {
  12641. var frames_1;
  12642. var meta = void 0;
  12643. try {
  12644. root = JSON.parse(content);
  12645. frames_1 = root.frames;
  12646. meta = root.meta;
  12647. if (!frames_1 || !meta) {
  12648. throw Error("Not a JSON Array file format");
  12649. }
  12650. }
  12651. catch (ex1) {
  12652. return null;
  12653. }
  12654. api = new AtlasPictureInfo();
  12655. api.atlasSize = new BABYLON.Size(meta.size.w, meta.size.h);
  12656. api.subPictures = new BABYLON.StringDictionary();
  12657. for (var _i = 0, frames_2 = frames_1; _i < frames_2.length; _i++) {
  12658. var f = frames_2[_i];
  12659. var aspi = new AtlasSubPictureInfo();
  12660. aspi.name = f.filename;
  12661. aspi.location = new BABYLON.Vector2(f.frame.x, api.atlasSize.height - (f.frame.y + f.frame.h));
  12662. aspi.size = new BABYLON.Size(f.frame.w, f.frame.h);
  12663. api.subPictures.add(aspi.name, aspi);
  12664. }
  12665. }
  12666. catch (ex2) {
  12667. errorMsg = "Unknown Exception: " + ex2;
  12668. errorCode = -2;
  12669. }
  12670. return { api: api, errorMsg: errorMsg, errorCode: errorCode };
  12671. };
  12672. return JSONArrayLoader;
  12673. }());
  12674. JSONArrayLoader = JSONArrayLoader_1 = __decorate([
  12675. AtlasLoaderPlugin("json", new JSONArrayLoader_1())
  12676. ], JSONArrayLoader);
  12677. /**
  12678. * Use this decorator when you declare an Atlas Loader Class for the loader to register itself automatically.
  12679. * @param fileExtension the extension of the file that the plugin is loading (there can be many plugin for the same extension)
  12680. * @param plugin an instance of the plugin class to add to the AtlasPictureInfoFactory
  12681. */
  12682. function AtlasLoaderPlugin(fileExtension, plugin) {
  12683. return function () {
  12684. AtlasPictureInfoFactory.addLoader(fileExtension, plugin);
  12685. };
  12686. }
  12687. BABYLON.AtlasLoaderPlugin = AtlasLoaderPlugin;
  12688. var JSONArrayLoader_1;
  12689. })(BABYLON || (BABYLON = {}));
  12690. var __extends = (this && this.__extends) || function (d, b) {
  12691. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12692. function __() { this.constructor = d; }
  12693. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  12694. };
  12695. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  12696. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  12697. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  12698. 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;
  12699. return c > 3 && r && Object.defineProperty(target, key, r), r;
  12700. };
  12701. var BABYLON;
  12702. (function (BABYLON) {
  12703. var Text2DRenderCache = (function (_super) {
  12704. __extends(Text2DRenderCache, _super);
  12705. function Text2DRenderCache() {
  12706. var _this = _super.apply(this, arguments) || this;
  12707. _this.effectsReady = false;
  12708. _this.vb = null;
  12709. _this.ib = null;
  12710. _this.instancingAttributes = null;
  12711. _this.fontTexture = null;
  12712. _this.effect = null;
  12713. _this.effectInstanced = null;
  12714. return _this;
  12715. }
  12716. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  12717. // Do nothing if the shader is still loading/preparing
  12718. if (!this.effectsReady) {
  12719. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  12720. return false;
  12721. }
  12722. this.effectsReady = true;
  12723. }
  12724. var canvas = instanceInfo.owner.owner;
  12725. var engine = canvas.engine;
  12726. this.fontTexture.update();
  12727. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  12728. engine.enableEffect(effect);
  12729. effect.setTexture("diffuseSampler", this.fontTexture);
  12730. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  12731. var sdf = this.fontTexture.isSignedDistanceField;
  12732. // Enable alpha mode only if the texture is not using SDF, SDF is rendered in AlphaTest mode, which mean no alpha blend
  12733. var curAlphaMode;
  12734. if (!sdf) {
  12735. curAlphaMode = engine.getAlphaMode();
  12736. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  12737. }
  12738. var pid = context.groupInfoPartData[0];
  12739. if (context.useInstancing) {
  12740. if (!this.instancingAttributes) {
  12741. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  12742. }
  12743. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  12744. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  12745. canvas._addDrawCallCount(1, context.renderMode);
  12746. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  12747. engine.draw(true, 0, 6, count);
  12748. engine.unbindInstanceAttributes();
  12749. }
  12750. else {
  12751. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  12752. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  12753. this.setupUniforms(effect, 0, pid._partData, i);
  12754. engine.draw(true, 0, 6);
  12755. }
  12756. }
  12757. if (!sdf) {
  12758. engine.setAlphaMode(curAlphaMode, true);
  12759. }
  12760. return true;
  12761. };
  12762. Text2DRenderCache.prototype.dispose = function () {
  12763. if (!_super.prototype.dispose.call(this)) {
  12764. return false;
  12765. }
  12766. if (this.vb) {
  12767. this._engine._releaseBuffer(this.vb);
  12768. this.vb = null;
  12769. }
  12770. if (this.ib) {
  12771. this._engine._releaseBuffer(this.ib);
  12772. this.ib = null;
  12773. }
  12774. if (this.fontTexture) {
  12775. this.fontTexture.decCachedFontTextureCounter();
  12776. this.fontTexture = null;
  12777. }
  12778. this.effect = null;
  12779. this.effectInstanced = null;
  12780. return true;
  12781. };
  12782. return Text2DRenderCache;
  12783. }(BABYLON.ModelRenderCache));
  12784. BABYLON.Text2DRenderCache = Text2DRenderCache;
  12785. var Text2DInstanceData = (function (_super) {
  12786. __extends(Text2DInstanceData, _super);
  12787. function Text2DInstanceData(partId, dataElementCount) {
  12788. return _super.call(this, partId, dataElementCount) || this;
  12789. }
  12790. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  12791. get: function () {
  12792. return null;
  12793. },
  12794. set: function (value) {
  12795. },
  12796. enumerable: true,
  12797. configurable: true
  12798. });
  12799. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  12800. get: function () {
  12801. return null;
  12802. },
  12803. set: function (value) {
  12804. },
  12805. enumerable: true,
  12806. configurable: true
  12807. });
  12808. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  12809. get: function () {
  12810. return null;
  12811. },
  12812. set: function (value) {
  12813. },
  12814. enumerable: true,
  12815. configurable: true
  12816. });
  12817. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  12818. get: function () {
  12819. return null;
  12820. },
  12821. set: function (value) {
  12822. },
  12823. enumerable: true,
  12824. configurable: true
  12825. });
  12826. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  12827. get: function () {
  12828. return null;
  12829. },
  12830. set: function (value) {
  12831. },
  12832. enumerable: true,
  12833. configurable: true
  12834. });
  12835. return Text2DInstanceData;
  12836. }(BABYLON.InstanceDataBase));
  12837. __decorate([
  12838. BABYLON.instanceData()
  12839. ], Text2DInstanceData.prototype, "topLeftUV", null);
  12840. __decorate([
  12841. BABYLON.instanceData()
  12842. ], Text2DInstanceData.prototype, "sizeUV", null);
  12843. __decorate([
  12844. BABYLON.instanceData()
  12845. ], Text2DInstanceData.prototype, "textureSize", null);
  12846. __decorate([
  12847. BABYLON.instanceData()
  12848. ], Text2DInstanceData.prototype, "color", null);
  12849. __decorate([
  12850. BABYLON.instanceData()
  12851. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  12852. BABYLON.Text2DInstanceData = Text2DInstanceData;
  12853. var Text2D = Text2D_1 = (function (_super) {
  12854. __extends(Text2D, _super);
  12855. /**
  12856. * Create a Text primitive
  12857. * @param text the text to display
  12858. * @param settings a combination of settings, possible ones are
  12859. * - 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)
  12860. * - children: an array of direct children
  12861. * - id a text identifier, for information purpose
  12862. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  12863. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  12864. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  12865. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  12866. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  12867. * - zOrder: override the zOrder with the specified value
  12868. * - origin: define the normalized origin point location, default [0.5;0.5]
  12869. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  12870. * - 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.
  12871. * - 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.
  12872. * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white.
  12873. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  12874. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  12875. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  12876. * - 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.
  12877. * - 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.
  12878. * - 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!
  12879. * - 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.
  12880. * - 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).
  12881. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  12882. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12883. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12884. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12885. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12886. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  12887. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  12888. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  12889. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  12890. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12891. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12892. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12893. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12894. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  12895. * - textAlignmentH: align text horizontally (Text2D.AlignLeft, Text2D.AlignCenter, Text2D.AlignRight)
  12896. * - textAlignmentV: align text vertically (Text2D.AlignTop, Text2D.AlignCenter, Text2D.AlignBottom)
  12897. * - textAlignment: a string defining the text alignment, text can be: [<h:|horizontal:><left|right|center>], [<v:|vertical:><top|bottom|center>]
  12898. * - wordWrap: if true the text will wrap inside content area
  12899. */
  12900. function Text2D(text, settings) {
  12901. var _this;
  12902. if (!settings) {
  12903. settings = {};
  12904. }
  12905. _this = _super.call(this, settings) || this;
  12906. if (settings.bitmapFontTexture != null) {
  12907. _this._fontTexture = settings.bitmapFontTexture;
  12908. _this._fontName = null;
  12909. _this._fontSuperSample = false;
  12910. _this._fontSDF = false;
  12911. }
  12912. else {
  12913. _this._fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  12914. _this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  12915. _this._fontSDF = (settings.fontSignedDistanceField != null && settings.fontSignedDistanceField);
  12916. }
  12917. _this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  12918. _this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  12919. _this._textSize = null;
  12920. _this.text = text;
  12921. _this.size = (settings.size == null) ? null : settings.size;
  12922. _this.textAlignmentH = (settings.textAlignmentH == null) ? Text2D_1.AlignLeft : settings.textAlignmentH;
  12923. _this.textAlignmentV = (settings.textAlignmentV == null) ? Text2D_1.AlignTop : settings.textAlignmentV;
  12924. _this.textAlignment = (settings.textAlignment == null) ? "" : settings.textAlignment;
  12925. _this._wordWrap = (settings.wordWrap == null) ? false : settings.wordWrap;
  12926. _this._updateRenderMode();
  12927. return _this;
  12928. }
  12929. Object.defineProperty(Text2D, "AlignLeft", {
  12930. /**
  12931. * Alignment is made relative to the left edge of the Content Area. Valid for horizontal alignment only.
  12932. */
  12933. get: function () { return Text2D_1._AlignLeft; },
  12934. enumerable: true,
  12935. configurable: true
  12936. });
  12937. Object.defineProperty(Text2D, "AlignTop", {
  12938. /**
  12939. * Alignment is made relative to the top edge of the Content Area. Valid for vertical alignment only.
  12940. */
  12941. get: function () { return Text2D_1._AlignTop; },
  12942. enumerable: true,
  12943. configurable: true
  12944. });
  12945. Object.defineProperty(Text2D, "AlignRight", {
  12946. /**
  12947. * Alignment is made relative to the right edge of the Content Area. Valid for horizontal alignment only.
  12948. */
  12949. get: function () { return Text2D_1._AlignRight; },
  12950. enumerable: true,
  12951. configurable: true
  12952. });
  12953. Object.defineProperty(Text2D, "AlignBottom", {
  12954. /**
  12955. * Alignment is made relative to the bottom edge of the Content Area. Valid for vertical alignment only.
  12956. */
  12957. get: function () { return Text2D_1._AlignBottom; },
  12958. enumerable: true,
  12959. configurable: true
  12960. });
  12961. Object.defineProperty(Text2D, "AlignCenter", {
  12962. /**
  12963. * Alignment is made to center the text from equal distance to the opposite edges of the Content Area
  12964. */
  12965. get: function () { return Text2D_1._AlignCenter; },
  12966. enumerable: true,
  12967. configurable: true
  12968. });
  12969. Object.defineProperty(Text2D.prototype, "fontName", {
  12970. get: function () {
  12971. return this._fontName;
  12972. },
  12973. set: function (value) {
  12974. if (this._fontName) {
  12975. throw new Error("Font Name change is not supported right now.");
  12976. }
  12977. this._fontName = value;
  12978. },
  12979. enumerable: true,
  12980. configurable: true
  12981. });
  12982. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  12983. get: function () {
  12984. return this._defaultFontColor;
  12985. },
  12986. set: function (value) {
  12987. this._defaultFontColor = value;
  12988. },
  12989. enumerable: true,
  12990. configurable: true
  12991. });
  12992. Object.defineProperty(Text2D.prototype, "text", {
  12993. get: function () {
  12994. return this._text;
  12995. },
  12996. set: function (value) {
  12997. if (!value) {
  12998. value = "";
  12999. }
  13000. this._text = value;
  13001. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  13002. this._size = null;
  13003. this._updateCharCount();
  13004. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  13005. var s = this.textSize;
  13006. },
  13007. enumerable: true,
  13008. configurable: true
  13009. });
  13010. Object.defineProperty(Text2D.prototype, "size", {
  13011. get: function () {
  13012. if (this._size != null) {
  13013. return this._size;
  13014. }
  13015. return this.textSize;
  13016. },
  13017. set: function (value) {
  13018. this._size = value;
  13019. },
  13020. enumerable: true,
  13021. configurable: true
  13022. });
  13023. Object.defineProperty(Text2D.prototype, "fontSuperSample", {
  13024. get: function () {
  13025. return this._fontTexture && this._fontTexture.isSuperSampled;
  13026. },
  13027. enumerable: true,
  13028. configurable: true
  13029. });
  13030. Object.defineProperty(Text2D.prototype, "fontSignedDistanceField", {
  13031. get: function () {
  13032. return this._fontTexture && this._fontTexture.isSignedDistanceField;
  13033. },
  13034. enumerable: true,
  13035. configurable: true
  13036. });
  13037. Object.defineProperty(Text2D.prototype, "isSizeAuto", {
  13038. get: function () {
  13039. return false;
  13040. },
  13041. enumerable: true,
  13042. configurable: true
  13043. });
  13044. Object.defineProperty(Text2D.prototype, "actualSize", {
  13045. /**
  13046. * Get the actual size of the Text2D primitive
  13047. */
  13048. get: function () {
  13049. if (this._actualSize) {
  13050. return this._actualSize;
  13051. }
  13052. return this.size;
  13053. },
  13054. enumerable: true,
  13055. configurable: true
  13056. });
  13057. Object.defineProperty(Text2D.prototype, "textSize", {
  13058. /**
  13059. * Get the area that bounds the text associated to the primitive
  13060. */
  13061. get: function () {
  13062. if (!this._textSize) {
  13063. if (this.owner && this._text) {
  13064. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  13065. if (!newSize.equals(this._textSize)) {
  13066. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  13067. this._positioningDirty();
  13068. }
  13069. this._textSize = newSize;
  13070. }
  13071. else {
  13072. return Text2D_1.nullSize;
  13073. }
  13074. }
  13075. return this._textSize;
  13076. },
  13077. enumerable: true,
  13078. configurable: true
  13079. });
  13080. Object.defineProperty(Text2D.prototype, "fontTexture", {
  13081. get: function () {
  13082. if (this._fontTexture) {
  13083. return this._fontTexture;
  13084. }
  13085. if (this.fontName == null || this.owner == null || this.owner.scene == null) {
  13086. return null;
  13087. }
  13088. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample, this._fontSDF);
  13089. return this._fontTexture;
  13090. },
  13091. enumerable: true,
  13092. configurable: true
  13093. });
  13094. /**
  13095. * Dispose the primitive, remove it from its parent
  13096. */
  13097. Text2D.prototype.dispose = function () {
  13098. if (!_super.prototype.dispose.call(this)) {
  13099. return false;
  13100. }
  13101. if (this._fontTexture) {
  13102. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample, this._fontSDF);
  13103. this._fontTexture = null;
  13104. }
  13105. return true;
  13106. };
  13107. Text2D.prototype.updateLevelBoundingInfo = function () {
  13108. if (!this.owner || !this._text) {
  13109. return false;
  13110. }
  13111. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  13112. return true;
  13113. };
  13114. Object.defineProperty(Text2D.prototype, "textAlignment", {
  13115. /**
  13116. * You can get/set the text alignment through this property
  13117. */
  13118. get: function () {
  13119. return this._textAlignment;
  13120. },
  13121. set: function (value) {
  13122. this._textAlignment = value;
  13123. this._setTextAlignmentfromString(value);
  13124. },
  13125. enumerable: true,
  13126. configurable: true
  13127. });
  13128. Text2D.prototype.levelIntersect = function (intersectInfo) {
  13129. // 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...
  13130. return true;
  13131. };
  13132. Text2D.prototype.createModelRenderCache = function (modelKey) {
  13133. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  13134. return renderCache;
  13135. };
  13136. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  13137. var renderCache = modelRenderCache;
  13138. var engine = this.owner.engine;
  13139. renderCache.fontTexture = this.fontTexture;
  13140. renderCache.fontTexture.incCachedFontTextureCounter();
  13141. var vb = new Float32Array(4);
  13142. for (var i = 0; i < 4; i++) {
  13143. vb[i] = i;
  13144. }
  13145. renderCache.vb = engine.createVertexBuffer(vb);
  13146. var ib = new Float32Array(6);
  13147. ib[0] = 0;
  13148. ib[1] = 2;
  13149. ib[2] = 1;
  13150. ib[3] = 0;
  13151. ib[4] = 3;
  13152. ib[5] = 2;
  13153. renderCache.ib = engine.createIndexBuffer(ib);
  13154. // 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
  13155. var ei = this.getDataPartEffectInfo(Text2D_1.TEXT2D_MAINPARTID, ["index"], null, true);
  13156. if (ei) {
  13157. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  13158. }
  13159. ei = this.getDataPartEffectInfo(Text2D_1.TEXT2D_MAINPARTID, ["index"], null, false);
  13160. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  13161. return renderCache;
  13162. };
  13163. Text2D.prototype.createInstanceDataParts = function () {
  13164. return [new Text2DInstanceData(Text2D_1.TEXT2D_MAINPARTID, this._charCount)];
  13165. };
  13166. // Looks like a hack!? Yes! Because that's what it is!
  13167. // 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
  13168. // 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)
  13169. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  13170. if (!this._charCount) {
  13171. var curText = this._text;
  13172. this.text = "A";
  13173. return curText;
  13174. }
  13175. };
  13176. // if obj contains something, we restore the _text property
  13177. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  13178. if (obj !== undefined) {
  13179. this.text = obj;
  13180. }
  13181. };
  13182. Text2D.prototype.getUsedShaderCategories = function (dataPart) {
  13183. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  13184. if (this._fontSDF) {
  13185. cat.push(Text2D_1.TEXT2D_CATEGORY_SDF);
  13186. }
  13187. return cat;
  13188. };
  13189. Text2D.prototype.refreshInstanceDataPart = function (part) {
  13190. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  13191. return false;
  13192. }
  13193. if (part.id === Text2D_1.TEXT2D_MAINPARTID) {
  13194. var d = part;
  13195. var texture = this.fontTexture;
  13196. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  13197. var ts = texture.getSize();
  13198. var offset = BABYLON.Vector2.Zero();
  13199. var lh = this.fontTexture.lineHeight;
  13200. d.dataElementCount = this._charCount;
  13201. d.curElement = 0;
  13202. var lineLengths = [];
  13203. var charWidths = [];
  13204. var charsPerLine = [];
  13205. var numCharsCurrenLine = 0;
  13206. var contentAreaWidth = this.contentArea.width;
  13207. var contentAreaHeight = this.contentArea.height;
  13208. var numCharsCurrentWord = 0;
  13209. var widthCurrentWord = 0;
  13210. var numWordsPerLine = 0;
  13211. var text = this.text;
  13212. var tabWidth = this._tabulationSize * texture.spaceWidth;
  13213. for (var i_1 = 0; i_1 < text.length; i_1++) {
  13214. var char = text[i_1];
  13215. numCharsCurrenLine++;
  13216. charWidths[i_1] = 0;
  13217. // Line feed
  13218. if (this._isWhiteSpaceCharVert(char)) {
  13219. lineLengths.push(offset.x);
  13220. charsPerLine.push(numCharsCurrenLine - 1);
  13221. numCharsCurrenLine = 1;
  13222. offset.x = 0;
  13223. if (widthCurrentWord > 0) {
  13224. numWordsPerLine++;
  13225. }
  13226. numWordsPerLine = 0;
  13227. numCharsCurrentWord = 0;
  13228. widthCurrentWord = 0;
  13229. continue;
  13230. }
  13231. var ci = texture.getChar(char);
  13232. var charWidth = 0;
  13233. if (char === "\t") {
  13234. charWidth = tabWidth;
  13235. }
  13236. else {
  13237. charWidth = ci.charWidth;
  13238. }
  13239. offset.x += charWidth;
  13240. charWidths[i_1] = charWidth;
  13241. if (this._isWhiteSpaceCharHoriz(char)) {
  13242. if (widthCurrentWord > 0) {
  13243. numWordsPerLine++;
  13244. }
  13245. numCharsCurrentWord = 0;
  13246. widthCurrentWord = 0;
  13247. }
  13248. else {
  13249. widthCurrentWord += ci.charWidth;
  13250. numCharsCurrentWord++;
  13251. }
  13252. if (this._wordWrap && numWordsPerLine > 0 && offset.x > contentAreaWidth) {
  13253. lineLengths.push(offset.x - widthCurrentWord);
  13254. numCharsCurrenLine -= numCharsCurrentWord;
  13255. var j = i_1 - numCharsCurrentWord;
  13256. //skip white space at the end of this line
  13257. while (this._isWhiteSpaceCharHoriz(text[j])) {
  13258. lineLengths[lineLengths.length - 1] -= charWidths[j];
  13259. j--;
  13260. }
  13261. charsPerLine.push(numCharsCurrenLine);
  13262. if (this._isWhiteSpaceCharHoriz(text[i_1])) {
  13263. //skip white space at the beginning of next line
  13264. var numSpaces = 0;
  13265. while (this._isWhiteSpaceCharHoriz(text[i_1 + numSpaces])) {
  13266. numSpaces++;
  13267. charWidths[i_1 + numSpaces] = 0;
  13268. }
  13269. i_1 += numSpaces - 1;
  13270. offset.x = 0;
  13271. numCharsCurrenLine = numSpaces - 1;
  13272. }
  13273. else {
  13274. numCharsCurrenLine = numCharsCurrentWord;
  13275. offset.x = widthCurrentWord;
  13276. }
  13277. numWordsPerLine = 0;
  13278. }
  13279. }
  13280. lineLengths.push(offset.x);
  13281. charsPerLine.push(numCharsCurrenLine);
  13282. //skip white space at the end
  13283. var i = text.length - 1;
  13284. while (this._isWhiteSpaceCharHoriz(text[i])) {
  13285. lineLengths[lineLengths.length - 1] -= charWidths[i];
  13286. i--;
  13287. }
  13288. var charNum = 0;
  13289. var maxLineLen = 0;
  13290. var alignH = this.textAlignmentH;
  13291. var alignV = this.textAlignmentV;
  13292. offset.x = 0;
  13293. if (alignH == Text2D_1.AlignRight || alignH == Text2D_1.AlignCenter) {
  13294. for (var i_2 = 0; i_2 < lineLengths.length; i_2++) {
  13295. if (lineLengths[i_2] > maxLineLen) {
  13296. maxLineLen = lineLengths[i_2];
  13297. }
  13298. }
  13299. }
  13300. var textHeight = lineLengths.length * lh;
  13301. var offsetX = this.padding.leftPixels;
  13302. if (alignH == Text2D_1.AlignRight) {
  13303. offsetX += contentAreaWidth - maxLineLen;
  13304. }
  13305. else if (alignH == Text2D_1.AlignCenter) {
  13306. offsetX += (contentAreaWidth - maxLineLen) * .5;
  13307. }
  13308. offset.x += offsetX;
  13309. offset.y += contentAreaHeight + textHeight - lh;
  13310. offset.y += this.padding.bottomPixels;
  13311. if (alignV == Text2D_1.AlignBottom) {
  13312. offset.y -= contentAreaHeight;
  13313. }
  13314. else if (alignV == Text2D_1.AlignCenter) {
  13315. offset.y -= (contentAreaHeight - textHeight) * .5 + lineLengths.length * lh;
  13316. }
  13317. else {
  13318. offset.y -= lineLengths.length * lh;
  13319. }
  13320. for (var i_3 = 0; i_3 < lineLengths.length; i_3++) {
  13321. var numChars = charsPerLine[i_3];
  13322. var lineLength = lineLengths[i_3];
  13323. if (alignH == Text2D_1.AlignRight) {
  13324. offset.x += maxLineLen - lineLength;
  13325. }
  13326. else if (alignH == Text2D_1.AlignCenter) {
  13327. offset.x += (maxLineLen - lineLength) * .5;
  13328. }
  13329. for (var j = 0; j < numChars; j++) {
  13330. var char = text[charNum];
  13331. var charWidth = charWidths[charNum];
  13332. this.updateInstanceDataPart(d, offset);
  13333. offset.x += charWidth;
  13334. if (!this._isWhiteSpaceCharHoriz(char)) {
  13335. var ci = texture.getChar(char);
  13336. d.topLeftUV = ci.topLeftUV;
  13337. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  13338. d.sizeUV = suv;
  13339. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  13340. d.color = this.defaultFontColor;
  13341. d.superSampleFactor = superSampleFactor;
  13342. ++d.curElement;
  13343. }
  13344. charNum++;
  13345. }
  13346. offset.x = offsetX;
  13347. offset.y -= texture.lineHeight;
  13348. }
  13349. }
  13350. return true;
  13351. };
  13352. Text2D.prototype._isWhiteSpaceCharHoriz = function (char) {
  13353. if (char === " " || char === "\t") {
  13354. return true;
  13355. }
  13356. };
  13357. Text2D.prototype._isWhiteSpaceCharVert = function (char) {
  13358. if (char === "\n" || char === "\r") {
  13359. return true;
  13360. }
  13361. };
  13362. Text2D.prototype._updateCharCount = function () {
  13363. var count = 0;
  13364. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  13365. var char = _a[_i];
  13366. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  13367. continue;
  13368. }
  13369. ++count;
  13370. }
  13371. this._charCount = count;
  13372. };
  13373. Text2D.prototype._setTextAlignmentfromString = function (value) {
  13374. var m = value.trim().split(",");
  13375. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  13376. var v = m_1[_i];
  13377. v = v.toLocaleLowerCase().trim();
  13378. // Horizontal
  13379. var i = v.indexOf("h:");
  13380. if (i === -1) {
  13381. i = v.indexOf("horizontal:");
  13382. }
  13383. if (i !== -1) {
  13384. v = v.substr(v.indexOf(":") + 1);
  13385. this._setTextAlignmentHorizontal(v);
  13386. continue;
  13387. }
  13388. // Vertical
  13389. i = v.indexOf("v:");
  13390. if (i === -1) {
  13391. i = v.indexOf("vertical:");
  13392. }
  13393. if (i !== -1) {
  13394. v = v.substr(v.indexOf(":") + 1);
  13395. this._setTextAlignmentVertical(v);
  13396. continue;
  13397. }
  13398. }
  13399. };
  13400. Text2D.prototype._setTextAlignmentHorizontal = function (text) {
  13401. var v = text.trim().toLocaleLowerCase();
  13402. switch (v) {
  13403. case "left":
  13404. this.textAlignmentH = Text2D_1.AlignLeft;
  13405. return;
  13406. case "right":
  13407. this.textAlignmentH = Text2D_1.AlignRight;
  13408. return;
  13409. case "center":
  13410. this.textAlignmentH = Text2D_1.AlignCenter;
  13411. return;
  13412. }
  13413. };
  13414. Text2D.prototype._setTextAlignmentVertical = function (text) {
  13415. var v = text.trim().toLocaleLowerCase();
  13416. switch (v) {
  13417. case "top":
  13418. this.textAlignmentV = Text2D_1.AlignTop;
  13419. return;
  13420. case "bottom":
  13421. this.textAlignmentV = Text2D_1.AlignBottom;
  13422. return;
  13423. case "center":
  13424. this.textAlignmentV = Text2D_1.AlignCenter;
  13425. return;
  13426. }
  13427. };
  13428. Text2D.prototype._useTextureAlpha = function () {
  13429. return this._fontSDF;
  13430. };
  13431. Text2D.prototype._shouldUseAlphaFromTexture = function () {
  13432. return !this._fontSDF;
  13433. };
  13434. return Text2D;
  13435. }(BABYLON.RenderablePrim2D));
  13436. Text2D.TEXT2D_MAINPARTID = 1;
  13437. Text2D.TEXT2D_CATEGORY_SDF = "SignedDistanceField";
  13438. Text2D._AlignLeft = 1;
  13439. Text2D._AlignTop = 1; // Same as left
  13440. Text2D._AlignRight = 2;
  13441. Text2D._AlignBottom = 2; // Same as right
  13442. Text2D._AlignCenter = 3;
  13443. __decorate([
  13444. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D_1.fontProperty = pi; }, false, true)
  13445. ], Text2D.prototype, "fontName", null);
  13446. __decorate([
  13447. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D_1.defaultFontColorProperty = pi; })
  13448. ], Text2D.prototype, "defaultFontColor", null);
  13449. __decorate([
  13450. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D_1.textProperty = pi; }, false, true)
  13451. ], Text2D.prototype, "text", null);
  13452. __decorate([
  13453. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D_1.sizeProperty = pi; })
  13454. ], Text2D.prototype, "size", null);
  13455. __decorate([
  13456. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Text2D_1.fontSuperSampleProperty = pi; }, false, false)
  13457. ], Text2D.prototype, "fontSuperSample", null);
  13458. __decorate([
  13459. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Text2D_1.fontSuperSampleProperty = pi; }, false, false)
  13460. ], Text2D.prototype, "fontSignedDistanceField", null);
  13461. Text2D = Text2D_1 = __decorate([
  13462. BABYLON.className("Text2D", "BABYLON")
  13463. ], Text2D);
  13464. BABYLON.Text2D = Text2D;
  13465. var Text2D_1;
  13466. })(BABYLON || (BABYLON = {}));
  13467. var __extends = (this && this.__extends) || function (d, b) {
  13468. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13469. function __() { this.constructor = d; }
  13470. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  13471. };
  13472. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  13473. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  13474. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  13475. 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;
  13476. return c > 3 && r && Object.defineProperty(target, key, r), r;
  13477. };
  13478. var BABYLON;
  13479. (function (BABYLON) {
  13480. var Lines2DRenderCache = (function (_super) {
  13481. __extends(Lines2DRenderCache, _super);
  13482. function Lines2DRenderCache(engine, modelKey) {
  13483. var _this = _super.call(this, engine, modelKey) || this;
  13484. _this.effectsReady = false;
  13485. _this.fillVB = null;
  13486. _this.fillIB = null;
  13487. _this.fillIndicesCount = 0;
  13488. _this.instancingFillAttributes = null;
  13489. _this.effectFill = null;
  13490. _this.effectFillInstanced = null;
  13491. _this.borderVB = null;
  13492. _this.borderIB = null;
  13493. _this.borderIndicesCount = 0;
  13494. _this.instancingBorderAttributes = null;
  13495. _this.effectBorder = null;
  13496. _this.effectBorderInstanced = null;
  13497. return _this;
  13498. }
  13499. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  13500. // Do nothing if the shader is still loading/preparing
  13501. if (!this.effectsReady) {
  13502. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  13503. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  13504. return false;
  13505. }
  13506. this.effectsReady = true;
  13507. }
  13508. var canvas = instanceInfo.owner.owner;
  13509. var engine = canvas.engine;
  13510. var depthFunction = 0;
  13511. if (this.effectFill && this.effectBorder) {
  13512. depthFunction = engine.getDepthFunction();
  13513. engine.setDepthFunctionToLessOrEqual();
  13514. }
  13515. var curAlphaMode = engine.getAlphaMode();
  13516. if (this.effectFill) {
  13517. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  13518. var pid = context.groupInfoPartData[partIndex];
  13519. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  13520. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  13521. }
  13522. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  13523. engine.enableEffect(effect);
  13524. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  13525. if (context.useInstancing) {
  13526. if (!this.instancingFillAttributes) {
  13527. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  13528. }
  13529. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  13530. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  13531. canvas._addDrawCallCount(1, context.renderMode);
  13532. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  13533. engine.draw(true, 0, this.fillIndicesCount, count);
  13534. engine.unbindInstanceAttributes();
  13535. }
  13536. else {
  13537. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  13538. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  13539. this.setupUniforms(effect, partIndex, pid._partData, i);
  13540. engine.draw(true, 0, this.fillIndicesCount);
  13541. }
  13542. }
  13543. }
  13544. if (this.effectBorder) {
  13545. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  13546. var pid = context.groupInfoPartData[partIndex];
  13547. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  13548. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  13549. }
  13550. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  13551. engine.enableEffect(effect);
  13552. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  13553. if (context.useInstancing) {
  13554. if (!this.instancingBorderAttributes) {
  13555. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  13556. }
  13557. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  13558. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  13559. canvas._addDrawCallCount(1, context.renderMode);
  13560. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  13561. engine.draw(true, 0, this.borderIndicesCount, count);
  13562. engine.unbindInstanceAttributes();
  13563. }
  13564. else {
  13565. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  13566. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  13567. this.setupUniforms(effect, partIndex, pid._partData, i);
  13568. engine.draw(true, 0, this.borderIndicesCount);
  13569. }
  13570. }
  13571. }
  13572. engine.setAlphaMode(curAlphaMode, true);
  13573. if (this.effectFill && this.effectBorder) {
  13574. engine.setDepthFunction(depthFunction);
  13575. }
  13576. return true;
  13577. };
  13578. Lines2DRenderCache.prototype.dispose = function () {
  13579. if (!_super.prototype.dispose.call(this)) {
  13580. return false;
  13581. }
  13582. if (this.fillVB) {
  13583. this._engine._releaseBuffer(this.fillVB);
  13584. this.fillVB = null;
  13585. }
  13586. if (this.fillIB) {
  13587. this._engine._releaseBuffer(this.fillIB);
  13588. this.fillIB = null;
  13589. }
  13590. this.effectFill = null;
  13591. this.effectFillInstanced = null;
  13592. this.effectBorder = null;
  13593. this.effectBorderInstanced = null;
  13594. if (this.borderVB) {
  13595. this._engine._releaseBuffer(this.borderVB);
  13596. this.borderVB = null;
  13597. }
  13598. if (this.borderIB) {
  13599. this._engine._releaseBuffer(this.borderIB);
  13600. this.borderIB = null;
  13601. }
  13602. return true;
  13603. };
  13604. return Lines2DRenderCache;
  13605. }(BABYLON.ModelRenderCache));
  13606. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  13607. var Lines2DInstanceData = (function (_super) {
  13608. __extends(Lines2DInstanceData, _super);
  13609. function Lines2DInstanceData(partId) {
  13610. return _super.call(this, partId, 1) || this;
  13611. }
  13612. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  13613. get: function () {
  13614. return null;
  13615. },
  13616. set: function (value) {
  13617. },
  13618. enumerable: true,
  13619. configurable: true
  13620. });
  13621. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  13622. get: function () {
  13623. return null;
  13624. },
  13625. set: function (value) {
  13626. },
  13627. enumerable: true,
  13628. configurable: true
  13629. });
  13630. return Lines2DInstanceData;
  13631. }(BABYLON.Shape2DInstanceData));
  13632. __decorate([
  13633. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  13634. ], Lines2DInstanceData.prototype, "boundingMin", null);
  13635. __decorate([
  13636. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  13637. ], Lines2DInstanceData.prototype, "boundingMax", null);
  13638. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  13639. var Lines2D = Lines2D_1 = (function (_super) {
  13640. __extends(Lines2D, _super);
  13641. /**
  13642. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  13643. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  13644. * @param settings a combination of settings, possible ones are
  13645. * - 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)
  13646. * - children: an array of direct children
  13647. * - id a text identifier, for information purpose
  13648. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  13649. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  13650. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  13651. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  13652. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  13653. * - zOrder: override the zOrder with the specified value
  13654. * - origin: define the normalized origin point location, default [0.5;0.5]
  13655. * - 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.
  13656. * - 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.
  13657. * - 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.
  13658. * - 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.
  13659. * - 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)
  13660. * - 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)
  13661. * - borderThickness: the thickness of the drawn border, default is 1.
  13662. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  13663. * - 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.
  13664. * - 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.
  13665. * - 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!
  13666. * - 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.
  13667. * - 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).
  13668. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  13669. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13670. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13671. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13672. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13673. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  13674. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  13675. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  13676. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  13677. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13678. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13679. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13680. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13681. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  13682. */
  13683. function Lines2D(points, settings) {
  13684. var _this;
  13685. if (!settings) {
  13686. settings = {};
  13687. }
  13688. _this = _super.call(this, settings) || this;
  13689. _this._fillVB = null;
  13690. _this._fillIB = null;
  13691. _this._borderVB = null;
  13692. _this._borderIB = null;
  13693. _this._size = BABYLON.Size.Zero();
  13694. _this._boundingMin = null;
  13695. _this._boundingMax = null;
  13696. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  13697. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  13698. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  13699. var closed = (settings.closed == null) ? false : settings.closed;
  13700. _this.points = points;
  13701. _this.fillThickness = fillThickness;
  13702. _this.startCap = startCap;
  13703. _this.endCap = endCap;
  13704. _this.closed = closed;
  13705. return _this;
  13706. }
  13707. Object.defineProperty(Lines2D, "NoCap", {
  13708. /**
  13709. * No Cap to apply on the extremity
  13710. */
  13711. get: function () { return Lines2D_1._noCap; },
  13712. enumerable: true,
  13713. configurable: true
  13714. });
  13715. Object.defineProperty(Lines2D, "RoundCap", {
  13716. /**
  13717. * A round cap, will use the line thickness as diameter
  13718. */
  13719. get: function () { return Lines2D_1._roundCap; },
  13720. enumerable: true,
  13721. configurable: true
  13722. });
  13723. Object.defineProperty(Lines2D, "TriangleCap", {
  13724. /**
  13725. * Creates a triangle at the extremity.
  13726. */
  13727. get: function () { return Lines2D_1._triangleCap; },
  13728. enumerable: true,
  13729. configurable: true
  13730. });
  13731. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  13732. /**
  13733. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  13734. */
  13735. get: function () { return Lines2D_1._squareAnchorCap; },
  13736. enumerable: true,
  13737. configurable: true
  13738. });
  13739. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  13740. /**
  13741. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  13742. */
  13743. get: function () { return Lines2D_1._roundAnchorCap; },
  13744. enumerable: true,
  13745. configurable: true
  13746. });
  13747. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  13748. /**
  13749. * Creates a diamond anchor at the extremity.
  13750. */
  13751. get: function () { return Lines2D_1._diamondAnchorCap; },
  13752. enumerable: true,
  13753. configurable: true
  13754. });
  13755. Object.defineProperty(Lines2D, "ArrowCap", {
  13756. /**
  13757. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  13758. */
  13759. get: function () { return Lines2D_1._arrowCap; },
  13760. enumerable: true,
  13761. configurable: true
  13762. });
  13763. Object.defineProperty(Lines2D.prototype, "points", {
  13764. get: function () {
  13765. return this._points;
  13766. },
  13767. set: function (value) {
  13768. this._points = value;
  13769. this._primTriArrayDirty = true;
  13770. this._boundingBoxDirty();
  13771. },
  13772. enumerable: true,
  13773. configurable: true
  13774. });
  13775. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  13776. get: function () {
  13777. return this._fillThickness;
  13778. },
  13779. set: function (value) {
  13780. this._fillThickness = value;
  13781. },
  13782. enumerable: true,
  13783. configurable: true
  13784. });
  13785. Object.defineProperty(Lines2D.prototype, "closed", {
  13786. get: function () {
  13787. return this._closed;
  13788. },
  13789. set: function (value) {
  13790. this._closed = value;
  13791. },
  13792. enumerable: true,
  13793. configurable: true
  13794. });
  13795. Object.defineProperty(Lines2D.prototype, "startCap", {
  13796. get: function () {
  13797. return this._startCap;
  13798. },
  13799. set: function (value) {
  13800. this._startCap = value;
  13801. },
  13802. enumerable: true,
  13803. configurable: true
  13804. });
  13805. Object.defineProperty(Lines2D.prototype, "endCap", {
  13806. get: function () {
  13807. return this._endCap;
  13808. },
  13809. set: function (value) {
  13810. this._endCap = value;
  13811. },
  13812. enumerable: true,
  13813. configurable: true
  13814. });
  13815. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  13816. var p = intersectInfo._localPickPosition;
  13817. this.updateTriArray();
  13818. return this._primTriArray.doesContain(p);
  13819. };
  13820. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  13821. get: function () {
  13822. if (!this._boundingMin) {
  13823. this._computeLines2D();
  13824. }
  13825. return this._boundingMin;
  13826. },
  13827. enumerable: true,
  13828. configurable: true
  13829. });
  13830. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  13831. get: function () {
  13832. if (!this._boundingMax) {
  13833. this._computeLines2D();
  13834. }
  13835. return this._boundingMax;
  13836. },
  13837. enumerable: true,
  13838. configurable: true
  13839. });
  13840. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  13841. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  13842. // Remove the BORDER category, we don't use it in the VertexShader
  13843. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  13844. if (i !== -1) {
  13845. res.splice(i, 1);
  13846. }
  13847. return res;
  13848. };
  13849. Lines2D.prototype.updateLevelBoundingInfo = function () {
  13850. if (!this._size) {
  13851. return false;
  13852. }
  13853. if (!this._boundingMin) {
  13854. this._computeLines2D();
  13855. }
  13856. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  13857. return true;
  13858. };
  13859. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  13860. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  13861. return renderCache;
  13862. };
  13863. ///////////////////////////////////////////////////////////////////////////////////
  13864. // Methods for Lines building
  13865. Lines2D.prototype._perp = function (v, res) {
  13866. res.x = v.y;
  13867. res.y = -v.x;
  13868. };
  13869. ;
  13870. Lines2D.prototype._direction = function (a, b, res) {
  13871. a.subtractToRef(b, res);
  13872. res.normalize();
  13873. };
  13874. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  13875. a.addToRef(b, tangent);
  13876. tangent.normalize();
  13877. miter.x = -tangent.y;
  13878. miter.y = tangent.x;
  13879. Lines2D_1._miterTps.x = -a.y;
  13880. Lines2D_1._miterTps.y = a.x;
  13881. return 1 / BABYLON.Vector2.Dot(miter, Lines2D_1._miterTps);
  13882. };
  13883. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  13884. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  13885. if (d === 0)
  13886. return false;
  13887. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  13888. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  13889. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  13890. return false;
  13891. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  13892. return false;
  13893. return true;
  13894. };
  13895. Lines2D.prototype._updateMinMax = function (array, offset) {
  13896. if (offset >= array.length) {
  13897. return;
  13898. }
  13899. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  13900. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  13901. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  13902. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  13903. };
  13904. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  13905. var borderMode = borderThickness != null && !isNaN(borderThickness);
  13906. var off = index * (borderMode ? 8 : 4);
  13907. // 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)
  13908. if (off >= array.length) {
  13909. return;
  13910. }
  13911. // Store start/end normal, we need it for the cap construction
  13912. if (index === 0) {
  13913. this._perp(n, Lines2D_1._startDir);
  13914. }
  13915. else if (index === max - 1) {
  13916. this._perp(n, Lines2D_1._endDir);
  13917. Lines2D_1._endDir.x *= -1;
  13918. Lines2D_1._endDir.y *= -1;
  13919. }
  13920. var swap = false;
  13921. array[off + 0] = p.x + n.x * halfThickness;
  13922. array[off + 1] = p.y + n.y * halfThickness;
  13923. array[off + 2] = p.x + n.x * -halfThickness;
  13924. array[off + 3] = p.y + n.y * -halfThickness;
  13925. this._updateMinMax(array, off);
  13926. this._updateMinMax(array, off + 2);
  13927. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  13928. // 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
  13929. if (detectFlip != 0) {
  13930. // Flip if intersect
  13931. var flipOff = detectFlip * (borderMode ? 8 : 4);
  13932. 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])) {
  13933. swap = true;
  13934. var tps = array[off + 0];
  13935. array[off + 0] = array[off + 2];
  13936. array[off + 2] = tps;
  13937. tps = array[off + 1];
  13938. array[off + 1] = array[off + 3];
  13939. array[off + 3] = tps;
  13940. }
  13941. }
  13942. if (borderMode) {
  13943. var t = halfThickness + borderThickness;
  13944. array[off + 4] = p.x + n.x * (swap ? -t : t);
  13945. array[off + 5] = p.y + n.y * (swap ? -t : t);
  13946. array[off + 6] = p.x + n.x * (swap ? t : -t);
  13947. array[off + 7] = p.y + n.y * (swap ? t : -t);
  13948. this._updateMinMax(array, off + 4);
  13949. this._updateMinMax(array, off + 6);
  13950. }
  13951. if (contour) {
  13952. off += borderMode ? 4 : 0;
  13953. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  13954. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  13955. }
  13956. };
  13957. Lines2D.prototype._getCapSize = function (type, border) {
  13958. if (border === void 0) { border = false; }
  13959. var sd = Lines2D_1._roundCapSubDiv;
  13960. // If no array given, we call this to get the size
  13961. var vbsize = 0, ibsize = 0;
  13962. switch (type) {
  13963. case Lines2D_1.NoCap:
  13964. {
  13965. // If the line is not close and we're computing border, we add the size to generate the edge border
  13966. if (!this.closed && border) {
  13967. vbsize = 4;
  13968. ibsize = 6;
  13969. }
  13970. else {
  13971. vbsize = ibsize = 0;
  13972. }
  13973. break;
  13974. }
  13975. case Lines2D_1.RoundCap:
  13976. {
  13977. if (border) {
  13978. vbsize = sd;
  13979. ibsize = (sd - 2) * 3;
  13980. }
  13981. else {
  13982. vbsize = (sd / 2) + 1;
  13983. ibsize = (sd / 2) * 3;
  13984. }
  13985. break;
  13986. }
  13987. case Lines2D_1.ArrowCap:
  13988. {
  13989. if (border) {
  13990. vbsize = 12;
  13991. ibsize = 24;
  13992. }
  13993. else {
  13994. vbsize = 3;
  13995. ibsize = 3;
  13996. }
  13997. break;
  13998. }
  13999. case Lines2D_1.TriangleCap:
  14000. {
  14001. if (border) {
  14002. vbsize = 6;
  14003. ibsize = 12;
  14004. }
  14005. else {
  14006. vbsize = 3;
  14007. ibsize = 3;
  14008. }
  14009. break;
  14010. }
  14011. case Lines2D_1.DiamondAnchorCap:
  14012. {
  14013. if (border) {
  14014. vbsize = 10;
  14015. ibsize = 24;
  14016. }
  14017. else {
  14018. vbsize = 5;
  14019. ibsize = 9;
  14020. }
  14021. break;
  14022. }
  14023. case Lines2D_1.SquareAnchorCap:
  14024. {
  14025. if (border) {
  14026. vbsize = 12;
  14027. ibsize = 30;
  14028. }
  14029. else {
  14030. vbsize = 4;
  14031. ibsize = 6;
  14032. }
  14033. break;
  14034. }
  14035. case Lines2D_1.RoundAnchorCap:
  14036. {
  14037. if (border) {
  14038. vbsize = sd * 2;
  14039. ibsize = (sd - 1) * 6;
  14040. }
  14041. else {
  14042. vbsize = sd + 1;
  14043. ibsize = (sd + 1) * 3;
  14044. }
  14045. break;
  14046. }
  14047. }
  14048. return { vbsize: vbsize * 2, ibsize: ibsize };
  14049. };
  14050. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  14051. var c = Math.cos(rotation);
  14052. var s = Math.sin(rotation);
  14053. Lines2D_1._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  14054. Lines2D_1._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  14055. var offset = baseOffset + (index * 2);
  14056. vb[offset + 0] = Lines2D_1._tpsV.x;
  14057. vb[offset + 1] = Lines2D_1._tpsV.y;
  14058. if (contour) {
  14059. contour.push(Lines2D_1._tpsV.x);
  14060. contour.push(Lines2D_1._tpsV.y);
  14061. }
  14062. this._updateMinMax(vb, offset);
  14063. return (baseOffset + index * 2) / 2;
  14064. };
  14065. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  14066. ib[baseOffset + index] = vertexIndex;
  14067. };
  14068. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  14069. // 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
  14070. var sd = Lines2D_1._roundCapSubDiv;
  14071. var dir = new BABYLON.Vector2(1, 0);
  14072. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  14073. var ht = thickness / 2;
  14074. var t = thickness;
  14075. var borderMode = borderThickness != null;
  14076. var bt = borderThickness;
  14077. switch (type) {
  14078. case Lines2D_1.NoCap:
  14079. if (borderMode && !this.closed) {
  14080. var vi = 0;
  14081. var ii = 0;
  14082. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  14083. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  14084. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  14085. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  14086. this._storeIndex(ib, ibi, ii++, v1);
  14087. this._storeIndex(ib, ibi, ii++, v2);
  14088. this._storeIndex(ib, ibi, ii++, v3);
  14089. this._storeIndex(ib, ibi, ii++, v1);
  14090. this._storeIndex(ib, ibi, ii++, v3);
  14091. this._storeIndex(ib, ibi, ii++, v4);
  14092. }
  14093. break;
  14094. case Lines2D_1.ArrowCap:
  14095. ht *= 2;
  14096. case Lines2D_1.TriangleCap:
  14097. {
  14098. if (borderMode) {
  14099. var f = type === Lines2D_1.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  14100. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  14101. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  14102. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  14103. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  14104. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  14105. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  14106. var ii = 0;
  14107. this._storeIndex(ib, ibi, ii++, v1);
  14108. this._storeIndex(ib, ibi, ii++, v4);
  14109. this._storeIndex(ib, ibi, ii++, v5);
  14110. this._storeIndex(ib, ibi, ii++, v1);
  14111. this._storeIndex(ib, ibi, ii++, v5);
  14112. this._storeIndex(ib, ibi, ii++, v2);
  14113. this._storeIndex(ib, ibi, ii++, v6);
  14114. this._storeIndex(ib, ibi, ii++, v3);
  14115. this._storeIndex(ib, ibi, ii++, v2);
  14116. this._storeIndex(ib, ibi, ii++, v6);
  14117. this._storeIndex(ib, ibi, ii++, v2);
  14118. this._storeIndex(ib, ibi, ii++, v5);
  14119. if (type === Lines2D_1.ArrowCap) {
  14120. var rht = thickness / 2;
  14121. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  14122. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  14123. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  14124. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  14125. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  14126. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  14127. this._storeIndex(ib, ibi, ii++, v7);
  14128. this._storeIndex(ib, ibi, ii++, v8);
  14129. this._storeIndex(ib, ibi, ii++, v9);
  14130. this._storeIndex(ib, ibi, ii++, v7);
  14131. this._storeIndex(ib, ibi, ii++, v9);
  14132. this._storeIndex(ib, ibi, ii++, v4);
  14133. this._storeIndex(ib, ibi, ii++, v10);
  14134. this._storeIndex(ib, ibi, ii++, v12);
  14135. this._storeIndex(ib, ibi, ii++, v11);
  14136. this._storeIndex(ib, ibi, ii++, v10);
  14137. this._storeIndex(ib, ibi, ii++, v6);
  14138. this._storeIndex(ib, ibi, ii++, v12);
  14139. }
  14140. }
  14141. else {
  14142. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  14143. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  14144. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  14145. this._storeIndex(ib, ibi, 0, v1);
  14146. this._storeIndex(ib, ibi, 1, v2);
  14147. this._storeIndex(ib, ibi, 2, v3);
  14148. }
  14149. break;
  14150. }
  14151. case Lines2D_1.RoundCap:
  14152. {
  14153. if (borderMode) {
  14154. var curA = -Math.PI / 2;
  14155. var incA = Math.PI / (sd / 2 - 1);
  14156. var ii = 0;
  14157. for (var i = 0; i < (sd / 2); i++) {
  14158. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  14159. 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);
  14160. if (i > 0) {
  14161. this._storeIndex(ib, ibi, ii++, v1 - 2);
  14162. this._storeIndex(ib, ibi, ii++, v2 - 2);
  14163. this._storeIndex(ib, ibi, ii++, v2);
  14164. this._storeIndex(ib, ibi, ii++, v1 - 2);
  14165. this._storeIndex(ib, ibi, ii++, v2);
  14166. this._storeIndex(ib, ibi, ii++, v1);
  14167. }
  14168. curA += incA;
  14169. }
  14170. }
  14171. else {
  14172. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  14173. var curA = -Math.PI / 2;
  14174. var incA = Math.PI / (sd / 2 - 1);
  14175. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  14176. curA += incA;
  14177. for (var i = 1; i < (sd / 2); i++) {
  14178. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  14179. this._storeIndex(ib, ibi, i * 3 + 0, c);
  14180. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  14181. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  14182. curA += incA;
  14183. }
  14184. }
  14185. break;
  14186. }
  14187. case Lines2D_1.SquareAnchorCap:
  14188. {
  14189. var vi = 0;
  14190. var c = borderMode ? null : contour;
  14191. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  14192. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  14193. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  14194. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  14195. if (borderMode) {
  14196. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  14197. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  14198. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  14199. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  14200. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  14201. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  14202. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  14203. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  14204. var ii = 0;
  14205. this._storeIndex(ib, ibi, ii++, v6);
  14206. this._storeIndex(ib, ibi, ii++, v1);
  14207. this._storeIndex(ib, ibi, ii++, v5);
  14208. this._storeIndex(ib, ibi, ii++, v6);
  14209. this._storeIndex(ib, ibi, ii++, v7);
  14210. this._storeIndex(ib, ibi, ii++, v1);
  14211. this._storeIndex(ib, ibi, ii++, v1);
  14212. this._storeIndex(ib, ibi, ii++, v7);
  14213. this._storeIndex(ib, ibi, ii++, v8);
  14214. this._storeIndex(ib, ibi, ii++, v1);
  14215. this._storeIndex(ib, ibi, ii++, v8);
  14216. this._storeIndex(ib, ibi, ii++, v2);
  14217. this._storeIndex(ib, ibi, ii++, v2);
  14218. this._storeIndex(ib, ibi, ii++, v8);
  14219. this._storeIndex(ib, ibi, ii++, v9);
  14220. this._storeIndex(ib, ibi, ii++, v2);
  14221. this._storeIndex(ib, ibi, ii++, v9);
  14222. this._storeIndex(ib, ibi, ii++, v3);
  14223. this._storeIndex(ib, ibi, ii++, v3);
  14224. this._storeIndex(ib, ibi, ii++, v9);
  14225. this._storeIndex(ib, ibi, ii++, v10);
  14226. this._storeIndex(ib, ibi, ii++, v3);
  14227. this._storeIndex(ib, ibi, ii++, v10);
  14228. this._storeIndex(ib, ibi, ii++, v4);
  14229. this._storeIndex(ib, ibi, ii++, v10);
  14230. this._storeIndex(ib, ibi, ii++, v11);
  14231. this._storeIndex(ib, ibi, ii++, v4);
  14232. this._storeIndex(ib, ibi, ii++, v11);
  14233. this._storeIndex(ib, ibi, ii++, v12);
  14234. this._storeIndex(ib, ibi, ii++, v4);
  14235. }
  14236. else {
  14237. this._storeIndex(ib, ibi, 0, v1);
  14238. this._storeIndex(ib, ibi, 1, v2);
  14239. this._storeIndex(ib, ibi, 2, v3);
  14240. this._storeIndex(ib, ibi, 3, v1);
  14241. this._storeIndex(ib, ibi, 4, v3);
  14242. this._storeIndex(ib, ibi, 5, v4);
  14243. }
  14244. break;
  14245. }
  14246. case Lines2D_1.RoundAnchorCap:
  14247. {
  14248. var cpos = Math.sqrt(t * t - ht * ht);
  14249. var center = new BABYLON.Vector2(cpos, 0);
  14250. var curA = BABYLON.Tools.ToRadians(-150);
  14251. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  14252. if (borderMode) {
  14253. var ii = 0;
  14254. for (var i = 0; i < sd; i++) {
  14255. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  14256. 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);
  14257. if (i > 0) {
  14258. this._storeIndex(ib, ibi, ii++, v1 - 2);
  14259. this._storeIndex(ib, ibi, ii++, v2 - 2);
  14260. this._storeIndex(ib, ibi, ii++, v2);
  14261. this._storeIndex(ib, ibi, ii++, v1 - 2);
  14262. this._storeIndex(ib, ibi, ii++, v2);
  14263. this._storeIndex(ib, ibi, ii++, v1);
  14264. }
  14265. curA += incA;
  14266. }
  14267. }
  14268. else {
  14269. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  14270. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  14271. curA += incA;
  14272. for (var i = 1; i < sd; i++) {
  14273. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  14274. this._storeIndex(ib, ibi, i * 3 + 0, c);
  14275. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  14276. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  14277. curA += incA;
  14278. }
  14279. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  14280. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  14281. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  14282. }
  14283. break;
  14284. }
  14285. case Lines2D_1.DiamondAnchorCap:
  14286. {
  14287. var vi = 0;
  14288. var c = borderMode ? null : contour;
  14289. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  14290. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  14291. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  14292. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  14293. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  14294. if (borderMode) {
  14295. var f = Math.sqrt(bt * bt * 2);
  14296. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  14297. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  14298. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  14299. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  14300. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  14301. var ii = 0;
  14302. this._storeIndex(ib, ibi, ii++, v6);
  14303. this._storeIndex(ib, ibi, ii++, v7);
  14304. this._storeIndex(ib, ibi, ii++, v1);
  14305. this._storeIndex(ib, ibi, ii++, v1);
  14306. this._storeIndex(ib, ibi, ii++, v7);
  14307. this._storeIndex(ib, ibi, ii++, v2);
  14308. this._storeIndex(ib, ibi, ii++, v2);
  14309. this._storeIndex(ib, ibi, ii++, v7);
  14310. this._storeIndex(ib, ibi, ii++, v8);
  14311. this._storeIndex(ib, ibi, ii++, v2);
  14312. this._storeIndex(ib, ibi, ii++, v8);
  14313. this._storeIndex(ib, ibi, ii++, v3);
  14314. this._storeIndex(ib, ibi, ii++, v3);
  14315. this._storeIndex(ib, ibi, ii++, v8);
  14316. this._storeIndex(ib, ibi, ii++, v9);
  14317. this._storeIndex(ib, ibi, ii++, v3);
  14318. this._storeIndex(ib, ibi, ii++, v9);
  14319. this._storeIndex(ib, ibi, ii++, v4);
  14320. this._storeIndex(ib, ibi, ii++, v4);
  14321. this._storeIndex(ib, ibi, ii++, v9);
  14322. this._storeIndex(ib, ibi, ii++, v10);
  14323. this._storeIndex(ib, ibi, ii++, v4);
  14324. this._storeIndex(ib, ibi, ii++, v10);
  14325. this._storeIndex(ib, ibi, ii++, v5);
  14326. }
  14327. else {
  14328. this._storeIndex(ib, ibi, 0, v1);
  14329. this._storeIndex(ib, ibi, 1, v2);
  14330. this._storeIndex(ib, ibi, 2, v3);
  14331. this._storeIndex(ib, ibi, 3, v1);
  14332. this._storeIndex(ib, ibi, 4, v3);
  14333. this._storeIndex(ib, ibi, 5, v5);
  14334. this._storeIndex(ib, ibi, 6, v5);
  14335. this._storeIndex(ib, ibi, 7, v3);
  14336. this._storeIndex(ib, ibi, 8, v4);
  14337. }
  14338. break;
  14339. }
  14340. }
  14341. return null;
  14342. };
  14343. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  14344. var lineA = BABYLON.Vector2.Zero();
  14345. var lineB = BABYLON.Vector2.Zero();
  14346. var tangent = BABYLON.Vector2.Zero();
  14347. var miter = BABYLON.Vector2.Zero();
  14348. var curNormal = null;
  14349. if (this.closed) {
  14350. this.points.push(this.points[0]);
  14351. }
  14352. var total = this.points.length;
  14353. for (var i = 1; i < total; i++) {
  14354. var last = this.points[i - 1];
  14355. var cur = this.points[i];
  14356. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  14357. this._direction(cur, last, lineA);
  14358. if (!curNormal) {
  14359. curNormal = BABYLON.Vector2.Zero();
  14360. this._perp(lineA, curNormal);
  14361. }
  14362. if (i === 1) {
  14363. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  14364. }
  14365. if (!next) {
  14366. this._perp(lineA, curNormal);
  14367. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  14368. }
  14369. else {
  14370. this._direction(next, cur, lineB);
  14371. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  14372. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  14373. }
  14374. }
  14375. if (this.points.length > 2 && this.closed) {
  14376. var last2 = this.points[total - 2];
  14377. var cur2 = this.points[0];
  14378. var next2 = this.points[1];
  14379. this._direction(cur2, last2, lineA);
  14380. this._direction(next2, cur2, lineB);
  14381. this._perp(lineA, curNormal);
  14382. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  14383. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  14384. // Patch contour
  14385. if (contour) {
  14386. var off = (bt == null) ? 0 : 4;
  14387. contour[0].x = vb[off + 0];
  14388. contour[0].y = vb[off + 1];
  14389. contour[1].x = vb[off + 2];
  14390. contour[1].y = vb[off + 3];
  14391. }
  14392. }
  14393. // Remove the point we added at the beginning
  14394. if (this.closed) {
  14395. this.points.splice(total - 1);
  14396. }
  14397. };
  14398. // Methods for Lines building
  14399. ///////////////////////////////////////////////////////////////////////////////////
  14400. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  14401. var renderCache = modelRenderCache;
  14402. var engine = this.owner.engine;
  14403. if (this._fillVB === null) {
  14404. this._computeLines2D();
  14405. }
  14406. // Need to create WebGL resources for fill part?
  14407. if (this.fill) {
  14408. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  14409. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  14410. renderCache.fillIndicesCount = this._fillIB.length;
  14411. // 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
  14412. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, true);
  14413. if (ei) {
  14414. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  14415. }
  14416. // Get the non instanced version
  14417. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, false);
  14418. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  14419. }
  14420. // Need to create WebGL resources for border part?
  14421. if (this.border) {
  14422. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  14423. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  14424. renderCache.borderIndicesCount = this._borderIB.length;
  14425. // 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
  14426. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, true);
  14427. if (ei) {
  14428. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  14429. }
  14430. // Get the non instanced version
  14431. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, false);
  14432. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  14433. }
  14434. this._fillVB = null;
  14435. this._fillIB = null;
  14436. this._borderVB = null;
  14437. this._borderIB = null;
  14438. return renderCache;
  14439. };
  14440. Lines2D.prototype.updateTriArray = function () {
  14441. if (this._primTriArrayDirty) {
  14442. this._computeLines2D();
  14443. }
  14444. };
  14445. Lines2D.prototype._computeLines2D = function () {
  14446. var _this = this;
  14447. // Init min/max because their being computed here
  14448. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  14449. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  14450. var contour = new Array();
  14451. var startCapContour = new Array();
  14452. var endCapContour = new Array();
  14453. // Need to create WebGL resources for fill part?
  14454. if (this.fill) {
  14455. var startCapInfo = this._getCapSize(this.startCap);
  14456. var endCapInfo = this._getCapSize(this.endCap);
  14457. var count = this.points.length;
  14458. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  14459. this._fillVB = new Float32Array(vbSize);
  14460. var vb = this._fillVB;
  14461. var ht = this.fillThickness / 2;
  14462. var total = this.points.length;
  14463. this._buildLine(vb, this.border ? null : contour, ht);
  14464. var max = total * 2;
  14465. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  14466. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  14467. var ib = this._fillIB;
  14468. for (var i = 0; i < triCount; i += 2) {
  14469. ib[i * 3 + 0] = i + 0;
  14470. ib[i * 3 + 1] = i + 1;
  14471. ib[i * 3 + 2] = (i + 2) % max;
  14472. ib[i * 3 + 3] = i + 1;
  14473. ib[i * 3 + 4] = (i + 3) % max;
  14474. ib[i * 3 + 5] = (i + 2) % max;
  14475. }
  14476. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D_1._startDir, this.border ? null : startCapContour);
  14477. 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);
  14478. }
  14479. // Need to create WebGL resources for border part?
  14480. if (this.border) {
  14481. var startCapInfo = this._getCapSize(this.startCap, true);
  14482. var endCapInfo = this._getCapSize(this.endCap, true);
  14483. var count = this.points.length;
  14484. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  14485. this._borderVB = new Float32Array(vbSize);
  14486. var vb = this._borderVB;
  14487. var ht = this.fillThickness / 2;
  14488. var bt = this.borderThickness;
  14489. var total = this.points.length;
  14490. this._buildLine(vb, contour, ht, bt);
  14491. var max = total * 2 * 2;
  14492. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  14493. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  14494. var ib = this._borderIB;
  14495. for (var i = 0; i < triCount; i += 4) {
  14496. ib[i * 3 + 0] = i + 0;
  14497. ib[i * 3 + 1] = i + 2;
  14498. ib[i * 3 + 2] = (i + 6) % max;
  14499. ib[i * 3 + 3] = i + 0;
  14500. ib[i * 3 + 4] = (i + 6) % max;
  14501. ib[i * 3 + 5] = (i + 4) % max;
  14502. ib[i * 3 + 6] = i + 3;
  14503. ib[i * 3 + 7] = i + 1;
  14504. ib[i * 3 + 8] = (i + 5) % max;
  14505. ib[i * 3 + 9] = i + 3;
  14506. ib[i * 3 + 10] = (i + 5) % max;
  14507. ib[i * 3 + 11] = (i + 7) % max;
  14508. }
  14509. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D_1._startDir, startCapContour);
  14510. 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);
  14511. }
  14512. var startCapTri;
  14513. if (startCapContour.length > 0) {
  14514. startCapTri = Earcut.earcut(startCapContour, null, 2);
  14515. }
  14516. var endCapTri;
  14517. if (endCapContour.length > 0) {
  14518. endCapTri = Earcut.earcut(endCapContour, null, 2);
  14519. }
  14520. // Build the Tri2DArray using the contour info from the shape and the caps (if any)
  14521. {
  14522. var pl = this.points.length;
  14523. // Count the number of needed triangles
  14524. var count = ((this.closed ? pl : (pl - 1)) * 2) + (startCapTri != null ? ((startCapTri.length + endCapTri.length) / 3) : 0);
  14525. // Init/Clear the TriArray
  14526. if (!this._primTriArray) {
  14527. this._primTriArray = new BABYLON.Tri2DArray(count);
  14528. }
  14529. else {
  14530. this._primTriArray.clear(count);
  14531. }
  14532. var pta_1 = this._primTriArray;
  14533. var l = this.closed ? pl + 1 : pl;
  14534. this.transformPointWithOriginToRef(contour[0], null, Lines2D_1._prevA);
  14535. this.transformPointWithOriginToRef(contour[1], null, Lines2D_1._prevB);
  14536. var si_1 = 0;
  14537. for (var i = 1; i < l; i++) {
  14538. this.transformPointWithOriginToRef(contour[(i % pl) * 2 + 0], null, Lines2D_1._curA);
  14539. this.transformPointWithOriginToRef(contour[(i % pl) * 2 + 1], null, Lines2D_1._curB);
  14540. pta_1.storeTriangle(si_1++, Lines2D_1._prevA, Lines2D_1._prevB, Lines2D_1._curA);
  14541. pta_1.storeTriangle(si_1++, Lines2D_1._curA, Lines2D_1._prevB, Lines2D_1._curB);
  14542. Lines2D_1._prevA.x = Lines2D_1._curA.x;
  14543. Lines2D_1._prevA.y = Lines2D_1._curA.y;
  14544. Lines2D_1._prevB.x = Lines2D_1._curB.x;
  14545. Lines2D_1._prevB.y = Lines2D_1._curB.y;
  14546. }
  14547. var capIntersect = function (tri, points) {
  14548. var l = tri.length;
  14549. for (var i = 0; i < l; i += 3) {
  14550. Lines2D_1._curA.x = points[tri[i + 0] * 2 + 0];
  14551. Lines2D_1._curA.y = points[tri[i + 0] * 2 + 1];
  14552. _this.transformPointWithOriginToRef(Lines2D_1._curA, null, Lines2D_1._curB);
  14553. Lines2D_1._curA.x = points[tri[i + 1] * 2 + 0];
  14554. Lines2D_1._curA.y = points[tri[i + 1] * 2 + 1];
  14555. _this.transformPointWithOriginToRef(Lines2D_1._curA, null, Lines2D_1._prevA);
  14556. Lines2D_1._curA.x = points[tri[i + 2] * 2 + 0];
  14557. Lines2D_1._curA.y = points[tri[i + 2] * 2 + 1];
  14558. _this.transformPointWithOriginToRef(Lines2D_1._curA, null, Lines2D_1._prevB);
  14559. pta_1.storeTriangle(si_1++, Lines2D_1._prevA, Lines2D_1._prevB, Lines2D_1._curB);
  14560. }
  14561. return false;
  14562. };
  14563. if (startCapTri) {
  14564. if (startCapTri) {
  14565. capIntersect(startCapTri, startCapContour);
  14566. }
  14567. if (endCapTri) {
  14568. capIntersect(endCapTri, endCapContour);
  14569. }
  14570. }
  14571. this._primTriArrayDirty = false;
  14572. }
  14573. var bs = this._boundingMax.subtract(this._boundingMin);
  14574. this._size.width = bs.x;
  14575. this._size.height = bs.y;
  14576. };
  14577. Object.defineProperty(Lines2D.prototype, "size", {
  14578. get: function () {
  14579. if (this._size == null) {
  14580. this._computeLines2D();
  14581. }
  14582. return this._size;
  14583. },
  14584. enumerable: true,
  14585. configurable: true
  14586. });
  14587. Lines2D.prototype.createInstanceDataParts = function () {
  14588. var res = new Array();
  14589. if (this.border) {
  14590. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  14591. }
  14592. if (this.fill) {
  14593. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  14594. }
  14595. return res;
  14596. };
  14597. Lines2D.prototype.applyActualScaleOnTransform = function () {
  14598. return true;
  14599. };
  14600. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  14601. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  14602. return false;
  14603. }
  14604. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  14605. var d = part;
  14606. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  14607. d.boundingMin = this.boundingMin;
  14608. d.boundingMax = this.boundingMax;
  14609. }
  14610. }
  14611. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  14612. var d = part;
  14613. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  14614. d.boundingMin = this.boundingMin;
  14615. d.boundingMax = this.boundingMax;
  14616. }
  14617. }
  14618. return true;
  14619. };
  14620. return Lines2D;
  14621. }(BABYLON.Shape2D));
  14622. Lines2D._prevA = BABYLON.Vector2.Zero();
  14623. Lines2D._prevB = BABYLON.Vector2.Zero();
  14624. Lines2D._curA = BABYLON.Vector2.Zero();
  14625. Lines2D._curB = BABYLON.Vector2.Zero();
  14626. Lines2D._miterTps = BABYLON.Vector2.Zero();
  14627. Lines2D._startDir = BABYLON.Vector2.Zero();
  14628. Lines2D._endDir = BABYLON.Vector2.Zero();
  14629. Lines2D._tpsV = BABYLON.Vector2.Zero();
  14630. Lines2D._noCap = 0;
  14631. Lines2D._roundCap = 1;
  14632. Lines2D._triangleCap = 2;
  14633. Lines2D._squareAnchorCap = 3;
  14634. Lines2D._roundAnchorCap = 4;
  14635. Lines2D._diamondAnchorCap = 5;
  14636. Lines2D._arrowCap = 6;
  14637. Lines2D._roundCapSubDiv = 36;
  14638. __decorate([
  14639. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D_1.pointsProperty = pi; })
  14640. ], Lines2D.prototype, "points", null);
  14641. __decorate([
  14642. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D_1.fillThicknessProperty = pi; })
  14643. ], Lines2D.prototype, "fillThickness", null);
  14644. __decorate([
  14645. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D_1.closedProperty = pi; })
  14646. ], Lines2D.prototype, "closed", null);
  14647. __decorate([
  14648. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D_1.startCapProperty = pi; })
  14649. ], Lines2D.prototype, "startCap", null);
  14650. __decorate([
  14651. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D_1.endCapProperty = pi; })
  14652. ], Lines2D.prototype, "endCap", null);
  14653. Lines2D = Lines2D_1 = __decorate([
  14654. BABYLON.className("Lines2D", "BABYLON")
  14655. ], Lines2D);
  14656. BABYLON.Lines2D = Lines2D;
  14657. var Lines2D_1;
  14658. })(BABYLON || (BABYLON = {}));
  14659. var __extends = (this && this.__extends) || function (d, b) {
  14660. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14661. function __() { this.constructor = d; }
  14662. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  14663. };
  14664. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  14665. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  14666. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  14667. 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;
  14668. return c > 3 && r && Object.defineProperty(target, key, r), r;
  14669. };
  14670. var BABYLON;
  14671. (function (BABYLON) {
  14672. // This class contains data that lifetime is bounding to the Babylon Engine object
  14673. var Canvas2DEngineBoundData = (function () {
  14674. function Canvas2DEngineBoundData() {
  14675. this._modelCache = new BABYLON.StringDictionary();
  14676. }
  14677. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  14678. return this._modelCache.getOrAddWithFactory(key, factory);
  14679. };
  14680. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  14681. if (!modelRenderCache.isDisposed) {
  14682. return false;
  14683. }
  14684. this._modelCache.remove(modelRenderCache.modelKey);
  14685. return true;
  14686. };
  14687. return Canvas2DEngineBoundData;
  14688. }());
  14689. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  14690. var Canvas2D = Canvas2D_1 = (function (_super) {
  14691. __extends(Canvas2D, _super);
  14692. function Canvas2D(scene, settings) {
  14693. var _this = _super.call(this, settings) || this;
  14694. /**
  14695. * 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.
  14696. * Beware that you have to take under consideration the origin and unitScaleFactor in your calculations! Good luck!
  14697. */
  14698. _this.worldSpaceToNodeLocal = function (worldPos) {
  14699. var node = _this._worldSpaceNode;
  14700. if (!node) {
  14701. return;
  14702. }
  14703. var mtx = node.getWorldMatrix().clone();
  14704. mtx.invert();
  14705. var usf = _this.unitScaleFactor;
  14706. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  14707. var res = new BABYLON.Vector2(v.x, v.y);
  14708. var size = _this.actualSize;
  14709. res.x += (size.width / usf) * 0.5; // res is centered, make it relative to bottom/left
  14710. res.y += (size.height / usf) * 0.5;
  14711. res.x *= usf; // multiply by the unitScaleFactor, which defines if the canvas is nth time bigger than the original world plane
  14712. res.y *= usf;
  14713. return res;
  14714. };
  14715. /**
  14716. * 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
  14717. */
  14718. _this.worldSpaceCacheChanged = function () {
  14719. var plane = _this.worldSpaceCanvasNode;
  14720. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  14721. vd.uvs = new Float32Array(8);
  14722. var material = plane.material;
  14723. var tex = _this._renderableData._cacheTexture;
  14724. if (material.diffuseTexture !== tex) {
  14725. material.diffuseTexture = tex;
  14726. tex.hasAlpha = true;
  14727. }
  14728. var nodeuv = _this._renderableData._cacheNodeUVs;
  14729. for (var i = 0; i < 4; i++) {
  14730. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  14731. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  14732. }
  14733. vd.applyToMesh(plane);
  14734. };
  14735. _this._notifDebugMode = false;
  14736. /**
  14737. * Instanced Array will be create if there's at least this number of parts/prim that can fit into it
  14738. */
  14739. _this.minPartCountToUseInstancedArray = 5;
  14740. _this._mapCounter = 0;
  14741. _this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  14742. _this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  14743. _this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  14744. _this._groupRenderCounter = new BABYLON.PerfCounter();
  14745. _this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  14746. _this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  14747. _this._updateCachedStateCounter = new BABYLON.PerfCounter();
  14748. _this._updateLayoutCounter = new BABYLON.PerfCounter();
  14749. _this._updatePositioningCounter = new BABYLON.PerfCounter();
  14750. _this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  14751. _this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  14752. _this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  14753. _this._cachedCanvasGroup = null;
  14754. _this._renderingGroupObserver = null;
  14755. _this._beforeRenderObserver = null;
  14756. _this._afterRenderObserver = null;
  14757. _this._profileInfoText = null;
  14758. BABYLON.Prim2DBase._isCanvasInit = false;
  14759. if (!settings) {
  14760. settings = {};
  14761. }
  14762. if (_this._cachingStrategy !== Canvas2D_1.CACHESTRATEGY_TOPLEVELGROUPS) {
  14763. _this._background = new BABYLON.Rectangle2D({ parent: _this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  14764. _this._background.zOrder = 1.0;
  14765. _this._background.isPickable = false;
  14766. _this._background.origin = BABYLON.Vector2.Zero();
  14767. _this._background.levelVisible = false;
  14768. if (settings.backgroundRoundRadius != null) {
  14769. _this.backgroundRoundRadius = settings.backgroundRoundRadius;
  14770. }
  14771. if (settings.backgroundBorder != null) {
  14772. if (typeof (settings.backgroundBorder) === "string") {
  14773. _this.backgroundBorder = Canvas2D_1.GetBrushFromString(settings.backgroundBorder);
  14774. }
  14775. else {
  14776. _this.backgroundBorder = settings.backgroundBorder;
  14777. }
  14778. }
  14779. if (settings.backgroundBorderThickNess != null) {
  14780. _this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  14781. }
  14782. if (settings.backgroundFill != null) {
  14783. if (typeof (settings.backgroundFill) === "string") {
  14784. _this.backgroundFill = Canvas2D_1.GetBrushFromString(settings.backgroundFill);
  14785. }
  14786. else {
  14787. _this.backgroundFill = settings.backgroundFill;
  14788. }
  14789. }
  14790. // Put a handler to resize the background whenever the canvas is resizing
  14791. _this.propertyChanged.add(function (e, s) {
  14792. if (e.propertyName === "size") {
  14793. _this._background.size = _this.size;
  14794. }
  14795. }, BABYLON.Group2D.sizeProperty.flagId);
  14796. _this._background._patchHierarchy(_this);
  14797. }
  14798. var engine = scene.getEngine();
  14799. _this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  14800. _this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  14801. _this._capturedPointers = new BABYLON.StringDictionary();
  14802. _this._pickStartingPosition = BABYLON.Vector2.Zero();
  14803. _this._hierarchyLevelMaxSiblingCount = 50;
  14804. _this._hierarchyDepth = 0;
  14805. _this._zOrder = 0;
  14806. _this._zMax = 1;
  14807. _this._scene = scene;
  14808. _this._engine = engine;
  14809. _this._renderingSize = new BABYLON.Size(0, 0);
  14810. _this._designSize = settings.designSize || null;
  14811. _this._designUseHorizAxis = settings.designUseHorizAxis === true;
  14812. if (!_this._trackedGroups) {
  14813. _this._trackedGroups = new Array();
  14814. }
  14815. _this._maxAdaptiveWorldSpaceCanvasSize = null;
  14816. _this._groupCacheMaps = new BABYLON.StringDictionary();
  14817. _this._patchHierarchy(_this);
  14818. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  14819. _this._fitRenderingDevice = !settings.size;
  14820. if (!settings.size) {
  14821. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  14822. }
  14823. // Register scene dispose to also dispose the canvas when it'll happens
  14824. scene.onDisposeObservable.add(function (d, s) {
  14825. _this.dispose();
  14826. });
  14827. if (_this._isScreenSpace) {
  14828. if (settings.renderingPhase) {
  14829. if (!settings.renderingPhase.camera || settings.renderingPhase.renderingGroupID == null) {
  14830. throw Error("You have to specify a valid camera and renderingGroup");
  14831. }
  14832. _this._renderingGroupObserver = _this._scene.onRenderingGroupObservable.add(function (e, s) {
  14833. if ((_this._scene.activeCamera === settings.renderingPhase.camera) && (e.renderStage === BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT)) {
  14834. _this._engine.clear(null, false, true, true);
  14835. _this._render();
  14836. }
  14837. }, Math.pow(2, settings.renderingPhase.renderingGroupID));
  14838. }
  14839. else {
  14840. _this._afterRenderObserver = _this._scene.onAfterRenderObservable.add(function (d, s) {
  14841. _this._engine.clear(null, false, true, true);
  14842. _this._render();
  14843. });
  14844. }
  14845. }
  14846. else {
  14847. _this._beforeRenderObserver = _this._scene.onBeforeRenderObservable.add(function (d, s) {
  14848. _this._render();
  14849. });
  14850. }
  14851. _this._supprtInstancedArray = _this._engine.getCaps().instancedArrays !== null;
  14852. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  14853. // Setup the canvas for interaction (or not)
  14854. _this._setupInteraction(enableInteraction);
  14855. // Initialize the Primitive Collision Manager
  14856. if (settings.enableCollisionManager) {
  14857. var enableBorders = settings.collisionManagerUseBorders;
  14858. _this._primitiveCollisionManager = (settings.customCollisionManager == null) ? new BABYLON.BasicPrimitiviceCollisionManager(_this, enableBorders) : settings.customCollisionManager(_this, enableBorders);
  14859. }
  14860. // Register this instance
  14861. Canvas2D_1._INSTANCES.push(_this);
  14862. return _this;
  14863. }
  14864. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  14865. get: function () {
  14866. return this._drawCallsOpaqueCounter;
  14867. },
  14868. enumerable: true,
  14869. configurable: true
  14870. });
  14871. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  14872. get: function () {
  14873. return this._drawCallsAlphaTestCounter;
  14874. },
  14875. enumerable: true,
  14876. configurable: true
  14877. });
  14878. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  14879. get: function () {
  14880. return this._drawCallsTransparentCounter;
  14881. },
  14882. enumerable: true,
  14883. configurable: true
  14884. });
  14885. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  14886. get: function () {
  14887. return this._groupRenderCounter;
  14888. },
  14889. enumerable: true,
  14890. configurable: true
  14891. });
  14892. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  14893. get: function () {
  14894. return this._updateTransparentDataCounter;
  14895. },
  14896. enumerable: true,
  14897. configurable: true
  14898. });
  14899. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  14900. get: function () {
  14901. return this._cachedGroupRenderCounter;
  14902. },
  14903. enumerable: true,
  14904. configurable: true
  14905. });
  14906. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  14907. get: function () {
  14908. return this._updateCachedStateCounter;
  14909. },
  14910. enumerable: true,
  14911. configurable: true
  14912. });
  14913. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  14914. get: function () {
  14915. return this._updateLayoutCounter;
  14916. },
  14917. enumerable: true,
  14918. configurable: true
  14919. });
  14920. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  14921. get: function () {
  14922. return this._updatePositioningCounter;
  14923. },
  14924. enumerable: true,
  14925. configurable: true
  14926. });
  14927. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  14928. get: function () {
  14929. return this._updateLocalTransformCounter;
  14930. },
  14931. enumerable: true,
  14932. configurable: true
  14933. });
  14934. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  14935. get: function () {
  14936. return this._updateGlobalTransformCounter;
  14937. },
  14938. enumerable: true,
  14939. configurable: true
  14940. });
  14941. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  14942. get: function () {
  14943. return this._boundingInfoRecomputeCounter;
  14944. },
  14945. enumerable: true,
  14946. configurable: true
  14947. });
  14948. Object.defineProperty(Canvas2D, "instances", {
  14949. get: function () {
  14950. return Canvas2D_1._INSTANCES;
  14951. },
  14952. enumerable: true,
  14953. configurable: true
  14954. });
  14955. Object.defineProperty(Canvas2D.prototype, "primitiveCollisionManager", {
  14956. get: function () {
  14957. return this._primitiveCollisionManager;
  14958. },
  14959. enumerable: true,
  14960. configurable: true
  14961. });
  14962. Canvas2D.prototype._canvasPreInit = function (settings) {
  14963. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D_1.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  14964. this._cachingStrategy = cachingStrategy;
  14965. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  14966. };
  14967. Canvas2D.prototype._setupInteraction = function (enable) {
  14968. var _this = this;
  14969. // No change detection
  14970. if (enable === this._interactionEnabled) {
  14971. return;
  14972. }
  14973. // Set the new state
  14974. this._interactionEnabled = enable;
  14975. // ScreenSpace mode
  14976. if (this._isScreenSpace) {
  14977. // Disable interaction
  14978. if (!enable) {
  14979. if (this._scenePrePointerObserver) {
  14980. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  14981. this._scenePrePointerObserver = null;
  14982. }
  14983. return;
  14984. }
  14985. // Enable Interaction
  14986. // Register the observable
  14987. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  14988. if (_this.isVisible === false) {
  14989. return;
  14990. }
  14991. var hs = 1 / _this.engine.getHardwareScalingLevel();
  14992. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  14993. _this._handlePointerEventForInteraction(e, localPos, s);
  14994. });
  14995. }
  14996. else {
  14997. var scene = this.scene;
  14998. if (enable) {
  14999. scene.constantlyUpdateMeshUnderPointer = true;
  15000. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  15001. if (_this.isVisible === false) {
  15002. return;
  15003. }
  15004. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  15005. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  15006. _this._handlePointerEventForInteraction(e, localPos, s);
  15007. }
  15008. });
  15009. }
  15010. else {
  15011. if (this._scenePointerObserver) {
  15012. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  15013. this._scenePointerObserver = null;
  15014. }
  15015. }
  15016. }
  15017. };
  15018. /**
  15019. * Internal method, you should use the Prim2DBase version instead
  15020. */
  15021. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  15022. if (this.isPointerCaptured(pointerId)) {
  15023. return false;
  15024. }
  15025. // Try to capture the pointer on the HTML side
  15026. try {
  15027. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  15028. }
  15029. catch (e) {
  15030. }
  15031. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  15032. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  15033. this._capturedPointers.add(pointerId.toString(), primitive);
  15034. return true;
  15035. };
  15036. /**
  15037. * Internal method, you should use the Prim2DBase version instead
  15038. */
  15039. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  15040. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  15041. return false;
  15042. }
  15043. // Try to release the pointer on the HTML side
  15044. try {
  15045. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  15046. }
  15047. catch (e) {
  15048. }
  15049. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  15050. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  15051. this._capturedPointers.remove(pointerId.toString());
  15052. return true;
  15053. };
  15054. /**
  15055. * Determine if the given pointer is captured or not
  15056. * @param pointerId the Id of the pointer
  15057. * @return true if it's captured, false otherwise
  15058. */
  15059. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  15060. return this._capturedPointers.contains(pointerId.toString());
  15061. };
  15062. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  15063. // Avoid unnecessary lookup
  15064. if (this._capturedPointers.count === 0) {
  15065. return null;
  15066. }
  15067. return this._capturedPointers.get(pointerId.toString());
  15068. };
  15069. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  15070. // Dispose check
  15071. if (this.isDisposed) {
  15072. return;
  15073. }
  15074. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  15075. if (!this._updatePointerInfo(eventData, localPosition)) {
  15076. return;
  15077. }
  15078. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  15079. // 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.
  15080. // 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.
  15081. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null, true);
  15082. // 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
  15083. this._updateOverStatus(true);
  15084. // Check if we have nothing to raise
  15085. if (!this._actualOverPrimitive && !capturedPrim) {
  15086. return;
  15087. }
  15088. // Update the relatedTarget info with the over primitive or the captured one (if any)
  15089. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  15090. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  15091. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  15092. // Analyze the pointer event type and fire proper events on the primitive
  15093. var skip = false;
  15094. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  15095. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData);
  15096. }
  15097. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  15098. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData);
  15099. }
  15100. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  15101. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData);
  15102. }
  15103. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  15104. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData);
  15105. }
  15106. eventState.skipNextObservers = skip;
  15107. };
  15108. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  15109. var s = this.scale;
  15110. var pii = this._primPointerInfo;
  15111. pii.cancelBubble = false;
  15112. if (!pii.canvasPointerPos) {
  15113. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  15114. }
  15115. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  15116. if (!camera || !camera.viewport) {
  15117. return false;
  15118. }
  15119. var engine = this._scene.getEngine();
  15120. if (this._isScreenSpace) {
  15121. var cameraViewport = camera.viewport;
  15122. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  15123. // Moving coordinates to local viewport world
  15124. var x = localPosition.x - viewport.x;
  15125. var y = localPosition.y - viewport.y;
  15126. pii.canvasPointerPos.x = (x - this.actualPosition.x) / s;
  15127. pii.canvasPointerPos.y = (engine.getRenderHeight() - y - this.actualPosition.y) / s;
  15128. }
  15129. else {
  15130. pii.canvasPointerPos.x = localPosition.x / s;
  15131. pii.canvasPointerPos.y = localPosition.y / s;
  15132. }
  15133. //console.log(`UpdatePointerInfo for ${this.id}, X:${pii.canvasPointerPos.x}, Y:${pii.canvasPointerPos.y}`);
  15134. pii.mouseWheelDelta = 0;
  15135. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  15136. var event = eventData.event;
  15137. if (event.wheelDelta) {
  15138. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  15139. }
  15140. else if (event.detail) {
  15141. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  15142. }
  15143. }
  15144. else {
  15145. var pe = eventData.event;
  15146. pii.ctrlKey = pe.ctrlKey;
  15147. pii.altKey = pe.altKey;
  15148. pii.shiftKey = pe.shiftKey;
  15149. pii.metaKey = pe.metaKey;
  15150. pii.button = pe.button;
  15151. pii.buttons = pe.buttons;
  15152. pii.pointerId = pe.pointerId;
  15153. pii.width = pe.width;
  15154. pii.height = pe.height;
  15155. pii.presssure = pe.pressure;
  15156. pii.tilt.x = pe.tiltX;
  15157. pii.tilt.y = pe.tiltY;
  15158. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  15159. }
  15160. return true;
  15161. };
  15162. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture, force) {
  15163. if (!force && (this.scene.getRenderId() === this._intersectionRenderId)) {
  15164. return;
  15165. }
  15166. // 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
  15167. if (!this._globalTransform) {
  15168. this.updateCachedStates(true);
  15169. }
  15170. var ii = Canvas2D_1._interInfo;
  15171. ii.pickPosition.x = mouseLocalPos.x;
  15172. ii.pickPosition.y = mouseLocalPos.y;
  15173. ii.findFirstOnly = false;
  15174. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  15175. if (!isCapture && !this.levelBoundingInfo.doesIntersect(ii.pickPosition)) {
  15176. // Reset intersection info as we don't hit anything
  15177. ii.intersectedPrimitives = new Array();
  15178. ii.topMostIntersectedPrimitive = null;
  15179. }
  15180. else {
  15181. // The pointer is inside the Canvas, do an intersection test
  15182. this.intersect(ii);
  15183. // Sort primitives to get them from top to bottom
  15184. ii.intersectedPrimitives = ii.intersectedPrimitives.sort(function (a, b) { return a.prim.actualZOffset - b.prim.actualZOffset; });
  15185. }
  15186. {
  15187. // Update prev/actual intersection info, fire "overPrim" property change if needed
  15188. this._previousIntersectionList = this._actualIntersectionList;
  15189. this._actualIntersectionList = ii.intersectedPrimitives;
  15190. this._previousOverPrimitive = this._actualOverPrimitive;
  15191. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  15192. var prev = (this._previousOverPrimitive != null) ? this._previousOverPrimitive.prim : null;
  15193. var actual = (this._actualOverPrimitive != null) ? this._actualOverPrimitive.prim : null;
  15194. if (prev !== actual) {
  15195. this.onPropertyChanged("overPrim", this._previousOverPrimitive ? this._previousOverPrimitive.prim : null, this._actualOverPrimitive ? this._actualOverPrimitive.prim : null);
  15196. }
  15197. }
  15198. this._intersectionRenderId = this.scene.getRenderId();
  15199. };
  15200. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  15201. Canvas2D.prototype._updateOverStatus = function (force) {
  15202. if ((!force && (this.scene.getRenderId() === this._hoverStatusRenderId)) || !this._actualIntersectionList) {
  15203. return;
  15204. }
  15205. if (this._previousIntersectionList == null) {
  15206. this._previousIntersectionList = [];
  15207. }
  15208. // Detect a change of over
  15209. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  15210. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  15211. if (prevPrim !== actualPrim) {
  15212. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  15213. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  15214. // See the NOTE section of: https://www.w3.org/TR/pointerevents/#setting-pointer-capture
  15215. if (capturedPrim) {
  15216. if (capturedPrim === prevPrim) {
  15217. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  15218. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  15219. }
  15220. else if (capturedPrim === actualPrim) {
  15221. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  15222. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  15223. }
  15224. }
  15225. else {
  15226. var _loop_1 = function (prev) {
  15227. if (!BABYLON.Tools.first(this_1._actualIntersectionList, function (pii) { return pii.prim === prev.prim; })) {
  15228. this_1._primPointerInfo.updateRelatedTarget(prev.prim, prev.intersectionLocation);
  15229. this_1._bubbleNotifyPrimPointerObserver(prev.prim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  15230. }
  15231. };
  15232. var this_1 = this;
  15233. // Check for Out & Leave
  15234. for (var _i = 0, _a = this._previousIntersectionList; _i < _a.length; _i++) {
  15235. var prev = _a[_i];
  15236. _loop_1(prev);
  15237. }
  15238. var _loop_2 = function (actual) {
  15239. if (!BABYLON.Tools.first(this_2._previousIntersectionList, function (pii) { return pii.prim === actual.prim; })) {
  15240. this_2._primPointerInfo.updateRelatedTarget(actual.prim, actual.intersectionLocation);
  15241. this_2._bubbleNotifyPrimPointerObserver(actual.prim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  15242. }
  15243. };
  15244. var this_2 = this;
  15245. // Check for Over & Enter
  15246. for (var _b = 0, _c = this._actualIntersectionList; _b < _c.length; _b++) {
  15247. var actual = _c[_b];
  15248. _loop_2(actual);
  15249. }
  15250. }
  15251. }
  15252. this._hoverStatusRenderId = this.scene.getRenderId();
  15253. };
  15254. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  15255. if (this._primPointerInfo.isCaptured) {
  15256. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  15257. }
  15258. else {
  15259. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  15260. var pii = _a[_i];
  15261. if (pii.prim === prim) {
  15262. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  15263. return;
  15264. }
  15265. }
  15266. }
  15267. };
  15268. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  15269. if (!this._notifDebugMode) {
  15270. return;
  15271. }
  15272. var debug = "";
  15273. for (var i = 0; i < prim.hierarchyDepth; i++) {
  15274. debug += " ";
  15275. }
  15276. var pii = this._primPointerInfo;
  15277. 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;
  15278. console.log(debug);
  15279. };
  15280. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  15281. var ppi = this._primPointerInfo;
  15282. var event = eventData ? eventData.event : null;
  15283. var cur = prim;
  15284. while (cur && !cur.isDisposed) {
  15285. this._updatePrimPointerPos(cur);
  15286. // For the first level we have to fire Enter or Leave for corresponding Over or Out
  15287. if (cur === prim) {
  15288. // Fire the proper notification
  15289. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  15290. this._debugExecObserver(prim, BABYLON.PrimitivePointerInfo.PointerEnter);
  15291. prim._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  15292. }
  15293. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  15294. this._debugExecObserver(prim, BABYLON.PrimitivePointerInfo.PointerLeave);
  15295. prim._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  15296. }
  15297. }
  15298. // Exec the observers
  15299. this._debugExecObserver(cur, mask);
  15300. if (!cur._pointerEventObservable.notifyObservers(ppi, mask) && eventData instanceof BABYLON.PointerInfoPre) {
  15301. eventData.skipOnPointerObservable = true;
  15302. return false;
  15303. }
  15304. this._triggerActionManager(cur, ppi, mask, event);
  15305. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  15306. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  15307. if (ppi.cancelBubble) {
  15308. return false;
  15309. }
  15310. // Loop to the parent
  15311. cur = cur.parent;
  15312. }
  15313. return true;
  15314. };
  15315. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  15316. var _this = this;
  15317. // 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
  15318. if (!this._globalTransform) {
  15319. this.updateCachedStates(true);
  15320. }
  15321. // Process Trigger related to PointerDown
  15322. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  15323. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  15324. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  15325. this._pickStartingTime = new Date().getTime();
  15326. this._pickedDownPrim = null;
  15327. if (prim.actionManager) {
  15328. this._pickedDownPrim = prim;
  15329. if (prim.actionManager.hasPickTriggers) {
  15330. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  15331. switch (eventData.button) {
  15332. case 0:
  15333. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  15334. break;
  15335. case 1:
  15336. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  15337. break;
  15338. case 2:
  15339. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  15340. break;
  15341. }
  15342. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  15343. }
  15344. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15345. window.setTimeout(function () {
  15346. var ppi = _this._primPointerInfo;
  15347. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  15348. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null, true);
  15349. _this._updateOverStatus(false);
  15350. var ii = new BABYLON.IntersectInfo2D();
  15351. ii.pickPosition = ppi.canvasPointerPos.clone();
  15352. ii.findFirstOnly = false;
  15353. _this.intersect(ii);
  15354. if (ii.isPrimIntersected(prim) !== null) {
  15355. if (prim.actionManager) {
  15356. 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)) {
  15357. _this._pickStartingTime = 0;
  15358. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  15359. }
  15360. }
  15361. }
  15362. }, BABYLON.ActionManager.LongPressDelay);
  15363. }
  15364. }
  15365. }
  15366. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  15367. this._pickStartingTime = 0;
  15368. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  15369. if (prim.actionManager) {
  15370. // OnPickUpTrigger
  15371. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  15372. // OnPickTrigger
  15373. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  15374. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  15375. }
  15376. }
  15377. // OnPickOutTrigger
  15378. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  15379. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  15380. }
  15381. }
  15382. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  15383. if (prim.actionManager) {
  15384. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  15385. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  15386. }
  15387. }
  15388. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  15389. if (prim.actionManager) {
  15390. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  15391. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  15392. }
  15393. }
  15394. };
  15395. /**
  15396. * Don't forget to call the dispose method when you're done with the Canvas instance.
  15397. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  15398. */
  15399. Canvas2D.prototype.dispose = function () {
  15400. if (!_super.prototype.dispose.call(this)) {
  15401. return false;
  15402. }
  15403. if (this._profilingCanvas) {
  15404. this._profilingCanvas.dispose();
  15405. this._profilingCanvas = null;
  15406. }
  15407. if (this.interactionEnabled) {
  15408. this._setupInteraction(false);
  15409. }
  15410. if (this._renderingGroupObserver) {
  15411. this._scene.onRenderingGroupObservable.remove(this._renderingGroupObserver);
  15412. this._renderingGroupObserver = null;
  15413. }
  15414. if (this._beforeRenderObserver) {
  15415. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  15416. this._beforeRenderObserver = null;
  15417. }
  15418. if (this._afterRenderObserver) {
  15419. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  15420. this._afterRenderObserver = null;
  15421. }
  15422. if (this._groupCacheMaps) {
  15423. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  15424. this._groupCacheMaps = null;
  15425. }
  15426. // Unregister this instance
  15427. var index = Canvas2D_1._INSTANCES.indexOf(this);
  15428. if (index > -1) {
  15429. Canvas2D_1._INSTANCES.splice(index, 1);
  15430. }
  15431. return true;
  15432. };
  15433. Object.defineProperty(Canvas2D.prototype, "scene", {
  15434. /**
  15435. * Accessor to the Scene that owns the Canvas
  15436. * @returns The instance of the Scene object
  15437. */
  15438. get: function () {
  15439. return this._scene;
  15440. },
  15441. enumerable: true,
  15442. configurable: true
  15443. });
  15444. Object.defineProperty(Canvas2D.prototype, "engine", {
  15445. /**
  15446. * Accessor to the Engine that drives the Scene used by this Canvas
  15447. * @returns The instance of the Engine object
  15448. */
  15449. get: function () {
  15450. return this._engine;
  15451. },
  15452. enumerable: true,
  15453. configurable: true
  15454. });
  15455. Object.defineProperty(Canvas2D.prototype, "renderObservable", {
  15456. /**
  15457. * And observable called during the Canvas rendering process.
  15458. * This observable is called twice per render, each time with a different mask:
  15459. * - 1: before render is executed
  15460. * - 2: after render is executed
  15461. */
  15462. get: function () {
  15463. if (!this._renderObservable) {
  15464. this._renderObservable = new BABYLON.Observable();
  15465. }
  15466. return this._renderObservable;
  15467. },
  15468. enumerable: true,
  15469. configurable: true
  15470. });
  15471. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  15472. /**
  15473. * Accessor of the Caching Strategy used by this Canvas.
  15474. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  15475. * @returns the value corresponding to the used strategy.
  15476. */
  15477. get: function () {
  15478. return this._cachingStrategy;
  15479. },
  15480. enumerable: true,
  15481. configurable: true
  15482. });
  15483. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  15484. /**
  15485. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  15486. * @returns {}
  15487. */
  15488. get: function () {
  15489. return this._isScreenSpace;
  15490. },
  15491. enumerable: true,
  15492. configurable: true
  15493. });
  15494. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  15495. /**
  15496. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  15497. */
  15498. get: function () {
  15499. return this._worldSpaceNode;
  15500. },
  15501. set: function (val) {
  15502. this._worldSpaceNode = val;
  15503. },
  15504. enumerable: true,
  15505. configurable: true
  15506. });
  15507. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  15508. /**
  15509. * Check if the WebGL Instanced Array extension is supported or not
  15510. */
  15511. get: function () {
  15512. return this._supprtInstancedArray;
  15513. },
  15514. enumerable: true,
  15515. configurable: true
  15516. });
  15517. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  15518. /**
  15519. * Property that defines the fill object used to draw the background of the Canvas.
  15520. * Note that Canvas with a Caching Strategy of
  15521. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  15522. */
  15523. get: function () {
  15524. if (!this._background || !this._background.isVisible) {
  15525. return null;
  15526. }
  15527. return this._background.fill;
  15528. },
  15529. set: function (value) {
  15530. this.checkBackgroundAvailability();
  15531. if (value === this._background.fill) {
  15532. return;
  15533. }
  15534. this._background.fill = value;
  15535. this._background.levelVisible = true;
  15536. },
  15537. enumerable: true,
  15538. configurable: true
  15539. });
  15540. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  15541. /**
  15542. * Property that defines the border object used to draw the background of the Canvas.
  15543. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  15544. */
  15545. get: function () {
  15546. if (!this._background || !this._background.isVisible) {
  15547. return null;
  15548. }
  15549. return this._background.border;
  15550. },
  15551. set: function (value) {
  15552. this.checkBackgroundAvailability();
  15553. if (value === this._background.border) {
  15554. return;
  15555. }
  15556. this._background.border = value;
  15557. this._background.levelVisible = true;
  15558. },
  15559. enumerable: true,
  15560. configurable: true
  15561. });
  15562. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  15563. /**
  15564. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  15565. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  15566. */
  15567. get: function () {
  15568. if (!this._background || !this._background.isVisible) {
  15569. return null;
  15570. }
  15571. return this._background.borderThickness;
  15572. },
  15573. set: function (value) {
  15574. this.checkBackgroundAvailability();
  15575. if (value === this._background.borderThickness) {
  15576. return;
  15577. }
  15578. this._background.borderThickness = value;
  15579. },
  15580. enumerable: true,
  15581. configurable: true
  15582. });
  15583. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  15584. /**
  15585. * You can set the roundRadius of the background
  15586. * @returns The current roundRadius
  15587. */
  15588. get: function () {
  15589. if (!this._background || !this._background.isVisible) {
  15590. return null;
  15591. }
  15592. return this._background.roundRadius;
  15593. },
  15594. set: function (value) {
  15595. this.checkBackgroundAvailability();
  15596. if (value === this._background.roundRadius) {
  15597. return;
  15598. }
  15599. this._background.roundRadius = value;
  15600. this._background.levelVisible = true;
  15601. },
  15602. enumerable: true,
  15603. configurable: true
  15604. });
  15605. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  15606. /**
  15607. * Enable/Disable interaction for this Canvas
  15608. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  15609. */
  15610. get: function () {
  15611. return this._interactionEnabled;
  15612. },
  15613. set: function (enable) {
  15614. this._setupInteraction(enable);
  15615. },
  15616. enumerable: true,
  15617. configurable: true
  15618. });
  15619. Object.defineProperty(Canvas2D.prototype, "fitRenderingDevice", {
  15620. get: function () {
  15621. return this._fitRenderingDevice;
  15622. },
  15623. enumerable: true,
  15624. configurable: true
  15625. });
  15626. Object.defineProperty(Canvas2D.prototype, "designSize", {
  15627. get: function () {
  15628. return this._designSize;
  15629. },
  15630. enumerable: true,
  15631. configurable: true
  15632. });
  15633. Object.defineProperty(Canvas2D.prototype, "designSizeUseHorizAxis", {
  15634. get: function () {
  15635. return this._designUseHorizAxis;
  15636. },
  15637. enumerable: true,
  15638. configurable: true
  15639. });
  15640. Object.defineProperty(Canvas2D.prototype, "overPrim", {
  15641. /**
  15642. * Return
  15643. */
  15644. get: function () {
  15645. if (this._actualIntersectionList && this._actualIntersectionList.length > 0) {
  15646. return this._actualIntersectionList[0].prim;
  15647. }
  15648. return null;
  15649. },
  15650. enumerable: true,
  15651. configurable: true
  15652. });
  15653. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  15654. /**
  15655. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  15656. * @returns {}
  15657. */
  15658. get: function () {
  15659. return this.__engineData;
  15660. },
  15661. enumerable: true,
  15662. configurable: true
  15663. });
  15664. Object.defineProperty(Canvas2D.prototype, "unitScaleFactor", {
  15665. get: function () {
  15666. return this._unitScaleFactor;
  15667. },
  15668. enumerable: true,
  15669. configurable: true
  15670. });
  15671. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  15672. if (this._profilingCanvas) {
  15673. return this._profilingCanvas;
  15674. }
  15675. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  15676. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D_1.CACHESTRATEGY_DONTCACHE, children: [
  15677. new BABYLON.Rectangle2D({
  15678. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  15679. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "12pt Lucida Console", fontSignedDistanceField: true })
  15680. ]
  15681. })
  15682. ]
  15683. });
  15684. this._profileInfoText = canvas.findById("ProfileInfoText");
  15685. this._profilingCanvas = canvas;
  15686. return canvas;
  15687. };
  15688. Canvas2D.prototype.checkBackgroundAvailability = function () {
  15689. if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_TOPLEVELGROUPS) {
  15690. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  15691. }
  15692. };
  15693. Canvas2D.prototype._initPerfMetrics = function () {
  15694. this._drawCallsOpaqueCounter.fetchNewFrame();
  15695. this._drawCallsAlphaTestCounter.fetchNewFrame();
  15696. this._drawCallsTransparentCounter.fetchNewFrame();
  15697. this._groupRenderCounter.fetchNewFrame();
  15698. this._updateTransparentDataCounter.fetchNewFrame();
  15699. this._cachedGroupRenderCounter.fetchNewFrame();
  15700. this._updateCachedStateCounter.fetchNewFrame();
  15701. this._updateLayoutCounter.fetchNewFrame();
  15702. this._updatePositioningCounter.fetchNewFrame();
  15703. this._updateLocalTransformCounter.fetchNewFrame();
  15704. this._updateGlobalTransformCounter.fetchNewFrame();
  15705. this._boundingInfoRecomputeCounter.fetchNewFrame();
  15706. };
  15707. Canvas2D.prototype._fetchPerfMetrics = function () {
  15708. this._drawCallsOpaqueCounter.addCount(0, true);
  15709. this._drawCallsAlphaTestCounter.addCount(0, true);
  15710. this._drawCallsTransparentCounter.addCount(0, true);
  15711. this._groupRenderCounter.addCount(0, true);
  15712. this._updateTransparentDataCounter.addCount(0, true);
  15713. this._cachedGroupRenderCounter.addCount(0, true);
  15714. this._updateCachedStateCounter.addCount(0, true);
  15715. this._updateLayoutCounter.addCount(0, true);
  15716. this._updatePositioningCounter.addCount(0, true);
  15717. this._updateLocalTransformCounter.addCount(0, true);
  15718. this._updateGlobalTransformCounter.addCount(0, true);
  15719. this._boundingInfoRecomputeCounter.addCount(0, true);
  15720. };
  15721. Canvas2D.prototype._updateProfileCanvas = function () {
  15722. if (this._profileInfoText == null) {
  15723. return;
  15724. }
  15725. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  15726. var p = "Draw Calls:\n" +
  15727. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  15728. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  15729. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  15730. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  15731. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  15732. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  15733. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  15734. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  15735. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  15736. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  15737. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  15738. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")");
  15739. this._profileInfoText.text = p;
  15740. };
  15741. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  15742. switch (renderMode) {
  15743. case BABYLON.Render2DContext.RenderModeOpaque:
  15744. this._drawCallsOpaqueCounter.addCount(count, false);
  15745. return;
  15746. case BABYLON.Render2DContext.RenderModeAlphaTest:
  15747. this._drawCallsAlphaTestCounter.addCount(count, false);
  15748. return;
  15749. case BABYLON.Render2DContext.RenderModeTransparent:
  15750. this._drawCallsTransparentCounter.addCount(count, false);
  15751. return;
  15752. }
  15753. };
  15754. Canvas2D.prototype._addGroupRenderCount = function (count) {
  15755. this._groupRenderCounter.addCount(count, false);
  15756. };
  15757. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  15758. this._updateTransparentDataCounter.addCount(count, false);
  15759. };
  15760. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  15761. this._cachedGroupRenderCounter.addCount(count, false);
  15762. };
  15763. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  15764. this._updateCachedStateCounter.addCount(count, false);
  15765. };
  15766. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  15767. this._updateLayoutCounter.addCount(count, false);
  15768. };
  15769. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  15770. this._updatePositioningCounter.addCount(count, false);
  15771. };
  15772. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  15773. this._updateLocalTransformCounter.addCount(count, false);
  15774. };
  15775. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  15776. this._updateGlobalTransformCounter.addCount(count, false);
  15777. };
  15778. Canvas2D.prototype._updateTrackedNodes = function () {
  15779. // Get the used camera
  15780. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  15781. // Compute some matrix stuff
  15782. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D_1._m);
  15783. var rh = this.engine.getRenderHeight();
  15784. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  15785. // Compute the screen position of each group that track a given scene node
  15786. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  15787. var group = _a[_i];
  15788. if (group.isDisposed) {
  15789. continue;
  15790. }
  15791. var node = group.trackedNode;
  15792. var worldMtx = node.getWorldMatrix();
  15793. var proj = BABYLON.Vector3.Project(Canvas2D_1._v, worldMtx, Canvas2D_1._m, v);
  15794. // Set the visibility state accordingly, if the position is outside the frustum (well on the Z planes only...) set the group to hidden
  15795. group.levelVisible = proj.z >= 0 && proj.z < 1.0;
  15796. var s = this.scale;
  15797. group.x = Math.round(proj.x / s);
  15798. group.y = Math.round((rh - proj.y) / s);
  15799. }
  15800. // If it's a WorldSpaceCanvas and it's tracking a node, let's update the WSC transformation data
  15801. if (this._trackNode) {
  15802. var rot = null;
  15803. var scale = null;
  15804. var worldmtx = this._trackNode.getWorldMatrix();
  15805. var pos = worldmtx.getTranslation().add(this._trackNodeOffset);
  15806. var wsc = this;
  15807. var wsn = wsc.worldSpaceCanvasNode;
  15808. if (this._trackNodeBillboard) {
  15809. var viewMtx = cam.getViewMatrix().clone().invert();
  15810. viewMtx.decompose(Canvas2D_1.tS, Canvas2D_1.tR, Canvas2D_1.tT);
  15811. rot = Canvas2D_1.tR.clone();
  15812. }
  15813. worldmtx.decompose(Canvas2D_1.tS, Canvas2D_1.tR, Canvas2D_1.tT);
  15814. var mtx = BABYLON.Matrix.Compose(Canvas2D_1.tS, Canvas2D_1.tR, BABYLON.Vector3.Zero());
  15815. pos = worldmtx.getTranslation().add(BABYLON.Vector3.TransformCoordinates(this._trackNodeOffset, mtx));
  15816. if (Canvas2D_1.tS.lengthSquared() !== 1) {
  15817. scale = Canvas2D_1.tS.clone();
  15818. }
  15819. if (!this._trackNodeBillboard) {
  15820. rot = Canvas2D_1.tR.clone();
  15821. }
  15822. if (wsn instanceof BABYLON.AbstractMesh) {
  15823. wsn.position = pos;
  15824. wsn.rotationQuaternion = rot;
  15825. if (scale) {
  15826. wsn.scaling = scale;
  15827. }
  15828. }
  15829. }
  15830. };
  15831. /**
  15832. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  15833. */
  15834. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  15835. this._updateCanvasState(forceRecompute);
  15836. };
  15837. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  15838. if (this._globalTransformStep < 2) {
  15839. return;
  15840. }
  15841. var n = this.worldSpaceCanvasNode;
  15842. var bi = n.getBoundingInfo().boundingBox;
  15843. var v = bi.vectorsWorld;
  15844. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  15845. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D_1._m);
  15846. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  15847. var projPoints = new Array(4);
  15848. for (var i = 0; i < 4; i++) {
  15849. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D_1._mI, Canvas2D_1._m, vp);
  15850. }
  15851. var left = projPoints[3].subtract(projPoints[0]).length();
  15852. var top = projPoints[3].subtract(projPoints[1]).length();
  15853. var right = projPoints[1].subtract(projPoints[2]).length();
  15854. var bottom = projPoints[2].subtract(projPoints[0]).length();
  15855. var w = Math.round(Math.max(top, bottom));
  15856. var h = Math.round(Math.max(right, left));
  15857. var isW = w > h;
  15858. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  15859. var edge = Math.max(w, h);
  15860. if (edge < 256) {
  15861. edge = 256;
  15862. }
  15863. else {
  15864. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  15865. }
  15866. // Clip values if needed
  15867. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  15868. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  15869. if (newScale !== this.scale) {
  15870. var scale = newScale;
  15871. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  15872. this._setRenderingScale(scale);
  15873. }
  15874. };
  15875. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  15876. // Check if the update has already been made for this render Frame
  15877. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  15878. return;
  15879. }
  15880. // Detect a change of rendering size
  15881. var renderingSizeChanged = false;
  15882. var newWidth = this.engine.getRenderWidth();
  15883. if (newWidth !== this._renderingSize.width) {
  15884. renderingSizeChanged = true;
  15885. }
  15886. this._renderingSize.width = newWidth;
  15887. var newHeight = this.engine.getRenderHeight();
  15888. if (newHeight !== this._renderingSize.height) {
  15889. renderingSizeChanged = true;
  15890. }
  15891. this._renderingSize.height = newHeight;
  15892. // If the canvas fit the rendering size and it changed, update
  15893. if (renderingSizeChanged && this._fitRenderingDevice) {
  15894. this.actualSize = this._renderingSize.clone();
  15895. this.size = this._renderingSize.clone();
  15896. if (this._background) {
  15897. this._background.size = this.size;
  15898. }
  15899. // Dirty the Layout at the Canvas level to recompute as the size changed
  15900. this._setLayoutDirty();
  15901. }
  15902. // If there's a design size, update the scale according to the renderingSize
  15903. if (this._designSize) {
  15904. var scale = void 0;
  15905. if (this._designUseHorizAxis) {
  15906. scale = this._renderingSize.width / this._designSize.width;
  15907. }
  15908. else {
  15909. scale = this._renderingSize.height / this._designSize.height;
  15910. }
  15911. this.size = this._designSize.clone();
  15912. this.actualSize = this._designSize.clone();
  15913. this.scale = scale;
  15914. }
  15915. var context = new BABYLON.PrepareRender2DContext();
  15916. ++this._globalTransformProcessStep;
  15917. this.updateCachedStates(false);
  15918. this._prepareGroupRender(context);
  15919. this._updateRenderId = this.scene.getRenderId();
  15920. };
  15921. /**
  15922. * Method that renders the Canvas, you should not invoke
  15923. */
  15924. Canvas2D.prototype._render = function () {
  15925. this._initPerfMetrics();
  15926. if (this._renderObservable && this._renderObservable.hasObservers()) {
  15927. this._renderObservable.notifyObservers(this, Canvas2D_1.RENDEROBSERVABLE_PRE);
  15928. }
  15929. this._updateCanvasState(false);
  15930. this._updateTrackedNodes();
  15931. // Nothing to do is the Canvas is not visible
  15932. if (this.isVisible === false) {
  15933. return;
  15934. }
  15935. if (!this._isScreenSpace) {
  15936. this._updateAdaptiveSizeWorldCanvas();
  15937. }
  15938. this._updateCanvasState(false);
  15939. if (this._primitiveCollisionManager) {
  15940. this._primitiveCollisionManager.update();
  15941. }
  15942. if (this._primPointerInfo.canvasPointerPos) {
  15943. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false, false);
  15944. this._updateOverStatus(false);
  15945. }
  15946. this.engine.setState(false);
  15947. this._groupRender();
  15948. if (!this._isScreenSpace) {
  15949. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  15950. this.worldSpaceCacheChanged();
  15951. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  15952. }
  15953. }
  15954. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  15955. if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  15956. this._cachedCanvasGroup._renderCachedCanvas();
  15957. }
  15958. this._fetchPerfMetrics();
  15959. this._updateProfileCanvas();
  15960. if (this._renderObservable && this._renderObservable.hasObservers()) {
  15961. this._renderObservable.notifyObservers(this, Canvas2D_1.RENDEROBSERVABLE_POST);
  15962. }
  15963. };
  15964. /**
  15965. * Internal method that allocate a cache for the given group.
  15966. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  15967. * @param group The group to allocate the cache of.
  15968. * @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.
  15969. */
  15970. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  15971. if (useMipMap === void 0) { useMipMap = false; }
  15972. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  15973. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  15974. var rd = group._renderableData;
  15975. var noResizeScale = rd._noResizeOnScale;
  15976. var isCanvas = parent == null;
  15977. var scale;
  15978. if (noResizeScale) {
  15979. scale = isCanvas ? Canvas2D_1._unS : group.parent.actualScale;
  15980. }
  15981. else {
  15982. scale = group.actualScale;
  15983. }
  15984. // Determine size
  15985. var size = group.actualSize;
  15986. size = new BABYLON.Size(Math.ceil(size.width * scale.x), Math.ceil(size.height * scale.y));
  15987. var originalSize = size.clone();
  15988. if (minSize) {
  15989. size.width = Math.max(minSize.width, size.width);
  15990. size.height = Math.max(minSize.height, size.height);
  15991. }
  15992. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  15993. // Try to find a spot in one of the cached texture
  15994. var res = null;
  15995. var map;
  15996. for (var _i = 0, mapArray_1 = mapArray; _i < mapArray_1.length; _i++) {
  15997. var _map = mapArray_1[_i];
  15998. map = _map;
  15999. var node = map.allocateRect(size);
  16000. if (node) {
  16001. res = { node: node, texture: map };
  16002. break;
  16003. }
  16004. }
  16005. // Couldn't find a map that could fit the rect, create a new map for it
  16006. if (!res) {
  16007. var mapSize = new BABYLON.Size(Canvas2D_1._groupTextureCacheSize, Canvas2D_1._groupTextureCacheSize);
  16008. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  16009. if (size.width > mapSize.width || size.height > mapSize.height) {
  16010. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  16011. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  16012. }
  16013. var id = "groupsMapChache" + this._mapCounter++ + "forCanvas" + this.id;
  16014. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  16015. map.hasAlpha = true;
  16016. map.anisotropicFilteringLevel = 4;
  16017. mapArray.splice(0, 0, map);
  16018. var node = map.allocateRect(size);
  16019. res = { node: node, texture: map };
  16020. }
  16021. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  16022. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  16023. if (group !== this || this._isScreenSpace) {
  16024. var node = res.node;
  16025. // 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
  16026. var sprite = void 0;
  16027. if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_CANVAS) {
  16028. if (this._cachedCanvasGroup) {
  16029. this._cachedCanvasGroup.dispose();
  16030. }
  16031. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  16032. sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: originalSize, spriteLocation: node.pos });
  16033. sprite.zOrder = 1;
  16034. sprite.origin = BABYLON.Vector2.Zero();
  16035. }
  16036. else {
  16037. 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 });
  16038. sprite.origin = group.origin.clone();
  16039. sprite.addExternalData("__cachedGroup__", group);
  16040. sprite.pointerEventObservable.add(function (e, s) {
  16041. if (group.pointerEventObservable !== null) {
  16042. group.pointerEventObservable.notifyObservers(e, s.mask);
  16043. }
  16044. });
  16045. res.sprite = sprite;
  16046. }
  16047. if (sprite && noResizeScale) {
  16048. var relScale = isCanvas ? group.actualScale : group.actualScale.divide(group.parent.actualScale);
  16049. sprite.scaleX = relScale.x;
  16050. sprite.scaleY = relScale.y;
  16051. }
  16052. }
  16053. return res;
  16054. };
  16055. /**
  16056. * Internal method used to register a Scene Node to track position for the given group
  16057. * Do not invoke this method, for internal purpose only.
  16058. * @param group the group to track its associated Scene Node
  16059. */
  16060. Canvas2D.prototype._registerTrackedNode = function (group) {
  16061. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  16062. return;
  16063. }
  16064. if (!this._trackedGroups) {
  16065. this._trackedGroups = new Array();
  16066. }
  16067. this._trackedGroups.push(group);
  16068. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  16069. };
  16070. /**
  16071. * Internal method used to unregister a tracked Scene Node
  16072. * Do not invoke this method, it's for internal purpose only.
  16073. * @param group the group to unregister its tracked Scene Node from.
  16074. */
  16075. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  16076. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  16077. return;
  16078. }
  16079. var i = this._trackedGroups.indexOf(group);
  16080. if (i !== -1) {
  16081. this._trackedGroups.splice(i, 1);
  16082. }
  16083. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  16084. };
  16085. /**
  16086. * Get a Solid Color Brush instance matching the given color.
  16087. * @param color The color to retrieve
  16088. * @return A shared instance of the SolidColorBrush2D class that use the given color
  16089. */
  16090. Canvas2D.GetSolidColorBrush = function (color) {
  16091. return Canvas2D_1._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  16092. };
  16093. /**
  16094. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  16095. * @param color The color to retrieve
  16096. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  16097. */
  16098. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  16099. return Canvas2D_1._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  16100. };
  16101. /**
  16102. * Get a Gradient Color Brush
  16103. * @param color1 starting color
  16104. * @param color2 engine color
  16105. * @param translation translation vector to apply. default is [0;0]
  16106. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  16107. * @param scale scaling factor to apply. default is 1.
  16108. */
  16109. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  16110. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  16111. if (rotation === void 0) { rotation = 0; }
  16112. if (scale === void 0) { scale = 1; }
  16113. return Canvas2D_1._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  16114. };
  16115. /**
  16116. * Create a solid or gradient brush from a string value.
  16117. * @param brushString should be either
  16118. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  16119. * - "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.
  16120. */
  16121. Canvas2D.GetBrushFromString = function (brushString) {
  16122. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  16123. brushString = brushString.trim();
  16124. var split = brushString.split(",");
  16125. // Solid, formatted as: "[solid:]#FF808080"
  16126. if (split.length === 1) {
  16127. var value = null;
  16128. if (brushString.indexOf("solid:") === 0) {
  16129. value = brushString.substr(6).trim();
  16130. }
  16131. else if (brushString.indexOf("#") === 0) {
  16132. value = brushString;
  16133. }
  16134. else {
  16135. return null;
  16136. }
  16137. return Canvas2D_1.GetSolidColorBrushFromHex(value);
  16138. }
  16139. else {
  16140. if (split[0].indexOf("gradient:") === 0) {
  16141. split[0] = split[0].substr(9).trim();
  16142. }
  16143. try {
  16144. var start = BABYLON.Color4.FromHexString(split[0].trim());
  16145. var end = BABYLON.Color4.FromHexString(split[1].trim());
  16146. var t = BABYLON.Vector2.Zero();
  16147. if (split.length > 2) {
  16148. var v = split[2].trim();
  16149. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  16150. return null;
  16151. }
  16152. var sep = v.indexOf(":");
  16153. var x = parseFloat(v.substr(1, sep));
  16154. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  16155. t = new BABYLON.Vector2(x, y);
  16156. }
  16157. var r = 0;
  16158. if (split.length > 3) {
  16159. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  16160. }
  16161. var s = 1;
  16162. if (split.length > 4) {
  16163. s = parseFloat(split[4].trim());
  16164. }
  16165. return Canvas2D_1.GetGradientColorBrush(start, end, t, r, s);
  16166. }
  16167. catch (e) {
  16168. return null;
  16169. }
  16170. }
  16171. };
  16172. return Canvas2D;
  16173. }(BABYLON.Group2D));
  16174. /**
  16175. * 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.
  16176. * This strategy doesn't allow primitives added directly as children of the Canvas.
  16177. * 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.
  16178. */
  16179. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  16180. /**
  16181. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  16182. * 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.
  16183. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  16184. * 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.
  16185. */
  16186. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  16187. /**
  16188. * 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).
  16189. */
  16190. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  16191. /**
  16192. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  16193. * 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).
  16194. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  16195. */
  16196. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  16197. /**
  16198. * Observable Mask to be notified before rendering is made
  16199. */
  16200. Canvas2D.RENDEROBSERVABLE_PRE = 1;
  16201. /**
  16202. * Observable Mask to be notified after rendering is made
  16203. */
  16204. Canvas2D.RENDEROBSERVABLE_POST = 2;
  16205. Canvas2D._INSTANCES = [];
  16206. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  16207. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  16208. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  16209. Canvas2D._m = BABYLON.Matrix.Identity();
  16210. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  16211. Canvas2D.tS = BABYLON.Vector3.Zero();
  16212. Canvas2D.tT = BABYLON.Vector3.Zero();
  16213. Canvas2D.tR = BABYLON.Quaternion.Identity();
  16214. /**
  16215. * Define the default size used for both the width and height of a MapTexture to allocate.
  16216. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  16217. */
  16218. Canvas2D._groupTextureCacheSize = 1024;
  16219. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  16220. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  16221. Canvas2D = Canvas2D_1 = __decorate([
  16222. BABYLON.className("Canvas2D", "BABYLON")
  16223. ], Canvas2D);
  16224. BABYLON.Canvas2D = Canvas2D;
  16225. var WorldSpaceCanvas2D = (function (_super) {
  16226. __extends(WorldSpaceCanvas2D, _super);
  16227. /**
  16228. * 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.
  16229. * 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.
  16230. * @param scene the Scene that owns the Canvas
  16231. * @param size the dimension of the Canvas in World Space
  16232. * @param settings a combination of settings, possible ones are
  16233. * - children: an array of direct children primitives
  16234. * - id: a text identifier, for information purpose only, default is null.
  16235. * - 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).
  16236. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  16237. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  16238. * - 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
  16239. * - trackNodeOffset: if you use trackNode you may want to specify a 3D Offset to apply to shift the Canvas
  16240. * - trackNodeBillboard: if true the WorldSpaceCanvas will always face the screen
  16241. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  16242. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  16243. * - 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).
  16244. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  16245. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  16246. * - 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.
  16247. * - 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.
  16248. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  16249. * - 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.
  16250. * - 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.
  16251. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  16252. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  16253. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  16254. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  16255. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  16256. */
  16257. function WorldSpaceCanvas2D(scene, size, settings) {
  16258. var _this;
  16259. BABYLON.Prim2DBase._isCanvasInit = true;
  16260. var s = settings;
  16261. s.isScreenSpace = false;
  16262. if (settings.unitScaleFactor != null) {
  16263. s.size = size.multiplyByFloats(settings.unitScaleFactor, settings.unitScaleFactor);
  16264. }
  16265. else {
  16266. s.size = size.clone();
  16267. }
  16268. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  16269. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  16270. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  16271. }
  16272. _this = _super.call(this, scene, settings) || this;
  16273. BABYLON.Prim2DBase._isCanvasInit = false;
  16274. _this._unitScaleFactor = (settings.unitScaleFactor != null) ? settings.unitScaleFactor : 1;
  16275. _this._renderableData._useMipMap = true;
  16276. _this._renderableData._anisotropicLevel = 8;
  16277. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  16278. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  16279. //}
  16280. if (settings.trackNode != null) {
  16281. _this._trackNode = settings.trackNode;
  16282. _this._trackNodeOffset = (settings.trackNodeOffset != null) ? settings.trackNodeOffset : BABYLON.Vector3.Zero();
  16283. _this._trackNodeBillboard = (settings.trackNodeBillboard != null) ? settings.trackNodeBillboard : false;
  16284. }
  16285. else {
  16286. _this._trackNode = null;
  16287. _this._trackNodeOffset = null;
  16288. _this._trackNodeBillboard = false;
  16289. }
  16290. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  16291. _this._customWorldSpaceNode = !createWorldSpaceNode;
  16292. var id = settings ? settings.id || null : null;
  16293. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  16294. var capMaxTextSize = _this.engine.getCaps().maxRenderTextureSize;
  16295. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 1K if allowed otherwise the max allowed
  16296. if (settings.maxAdaptiveCanvasSize == null) {
  16297. _this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  16298. }
  16299. else {
  16300. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  16301. _this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  16302. }
  16303. if (createWorldSpaceNode) {
  16304. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, _this);
  16305. var vertexData = BABYLON.VertexData.CreatePlane({
  16306. width: size.width,
  16307. height: size.height,
  16308. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  16309. });
  16310. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  16311. _this.applyCachedTexture(vertexData, mtl);
  16312. vertexData.applyToMesh(plane, true);
  16313. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  16314. mtl.disableLighting = true;
  16315. mtl.useAlphaFromDiffuseTexture = true;
  16316. if (settings && settings.sideOrientation) {
  16317. mtl.backFaceCulling = (settings.sideOrientation === BABYLON.Mesh.DEFAULTSIDE || settings.sideOrientation === BABYLON.Mesh.FRONTSIDE);
  16318. }
  16319. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  16320. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  16321. plane.material = mtl;
  16322. _this._worldSpaceNode = plane;
  16323. }
  16324. else {
  16325. _this._worldSpaceNode = settings.customWorldSpaceNode;
  16326. _this.applyCachedTexture(null, null);
  16327. }
  16328. _this.propertyChanged.add(function (e, st) {
  16329. var mesh = _this._worldSpaceNode;
  16330. if (mesh) {
  16331. mesh.isVisible = e.newValue;
  16332. }
  16333. }, BABYLON.Prim2DBase.isVisibleProperty.flagId);
  16334. return _this;
  16335. }
  16336. WorldSpaceCanvas2D.prototype.dispose = function () {
  16337. if (!_super.prototype.dispose.call(this)) {
  16338. return false;
  16339. }
  16340. if (!this._customWorldSpaceNode && this._worldSpaceNode) {
  16341. this._worldSpaceNode.dispose();
  16342. this._worldSpaceNode = null;
  16343. }
  16344. };
  16345. return WorldSpaceCanvas2D;
  16346. }(Canvas2D));
  16347. WorldSpaceCanvas2D = __decorate([
  16348. BABYLON.className("WorldSpaceCanvas2D", "BABYLON")
  16349. ], WorldSpaceCanvas2D);
  16350. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  16351. var ScreenSpaceCanvas2D = (function (_super) {
  16352. __extends(ScreenSpaceCanvas2D, _super);
  16353. /**
  16354. * 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.
  16355. * 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.
  16356. * All caching strategies will be available.
  16357. * 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]
  16358. * @param scene the Scene that owns the Canvas
  16359. * @param settings a combination of settings, possible ones are
  16360. * - children: an array of direct children primitives
  16361. * - id: a text identifier, for information purpose only
  16362. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  16363. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  16364. * - 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]
  16365. * - width: the width of the Canvas. you can alternatively use the size setting.
  16366. * - height: the height of the Canvas. you can alternatively use the size setting.
  16367. * - 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
  16368. * - 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.
  16369. * - 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.
  16370. * - 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.
  16371. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  16372. * - 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.
  16373. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  16374. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  16375. * - 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.
  16376. * - 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.
  16377. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  16378. * - 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.
  16379. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  16380. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  16381. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  16382. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  16383. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  16384. */
  16385. function ScreenSpaceCanvas2D(scene, settings) {
  16386. var _this;
  16387. BABYLON.Prim2DBase._isCanvasInit = true;
  16388. _this = _super.call(this, scene, settings) || this;
  16389. return _this;
  16390. }
  16391. return ScreenSpaceCanvas2D;
  16392. }(Canvas2D));
  16393. ScreenSpaceCanvas2D = __decorate([
  16394. BABYLON.className("ScreenSpaceCanvas2D", "BABYLON")
  16395. ], ScreenSpaceCanvas2D);
  16396. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  16397. var Canvas2D_1;
  16398. })(BABYLON || (BABYLON = {}));
  16399. var __extends = (this && this.__extends) || function (d, b) {
  16400. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16401. function __() { this.constructor = d; }
  16402. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  16403. };
  16404. var BABYLON;
  16405. (function (BABYLON) {
  16406. /**
  16407. * This is the class that is used to display a World Space Canvas into a 3D scene
  16408. */
  16409. var WorldSpaceCanvas2DNode = (function (_super) {
  16410. __extends(WorldSpaceCanvas2DNode, _super);
  16411. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  16412. var _this = _super.call(this, name, scene) || this;
  16413. _this._canvas = canvas;
  16414. return _this;
  16415. }
  16416. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  16417. _super.prototype.dispose.call(this);
  16418. if (this._canvas) {
  16419. this._canvas.dispose();
  16420. this._canvas = null;
  16421. }
  16422. };
  16423. return WorldSpaceCanvas2DNode;
  16424. }(BABYLON.Mesh));
  16425. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  16426. })(BABYLON || (BABYLON = {}));
  16427. var __extends = (this && this.__extends) || function (d, b) {
  16428. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16429. function __() { this.constructor = d; }
  16430. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  16431. };
  16432. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  16433. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  16434. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  16435. 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;
  16436. return c > 3 && r && Object.defineProperty(target, key, r), r;
  16437. };
  16438. var BABYLON;
  16439. (function (BABYLON) {
  16440. var Command = (function () {
  16441. function Command(execute, canExecute) {
  16442. if (!execute) {
  16443. throw Error("At least an execute lambda must be given at Command creation time");
  16444. }
  16445. this._canExecuteChanged = null;
  16446. this._lastCanExecuteResult = null;
  16447. this.execute = execute;
  16448. this.canExecute = canExecute;
  16449. }
  16450. Command.prototype.canExecute = function (parameter) {
  16451. var res = true;
  16452. if (this._canExecute) {
  16453. res = this._canExecute(parameter);
  16454. }
  16455. if (res !== this._lastCanExecuteResult) {
  16456. if (this._canExecuteChanged && this._canExecuteChanged.hasObservers()) {
  16457. this._canExecuteChanged.notifyObservers(null);
  16458. }
  16459. this._lastCanExecuteResult = res;
  16460. }
  16461. return res;
  16462. };
  16463. Command.prototype.execute = function (parameter) {
  16464. this._execute(parameter);
  16465. };
  16466. Object.defineProperty(Command.prototype, "canExecuteChanged", {
  16467. get: function () {
  16468. if (!this._canExecuteChanged) {
  16469. this._canExecuteChanged = new BABYLON.Observable();
  16470. }
  16471. return this._canExecuteChanged;
  16472. },
  16473. enumerable: true,
  16474. configurable: true
  16475. });
  16476. return Command;
  16477. }());
  16478. BABYLON.Command = Command;
  16479. var UIElement = (function (_super) {
  16480. __extends(UIElement, _super);
  16481. function UIElement(settings) {
  16482. var _this = _super.call(this) || this;
  16483. if (!settings) {
  16484. throw Error("A settings object must be passed with at least either a parent or owner parameter");
  16485. }
  16486. var type = BABYLON.Tools.getFullClassName(_this);
  16487. _this._ownerWindow = null;
  16488. _this._parent = null;
  16489. _this._visualPlaceholder = null;
  16490. _this._visualTemplateRoot = null;
  16491. _this._visualChildrenPlaceholder = null;
  16492. _this._hierarchyDepth = 0;
  16493. _this._renderingTemplateName = (settings.templateName != null) ? settings.templateName : GUIManager.DefaultTemplateName;
  16494. _this._style = (settings.styleName != null) ? GUIManager.getStyle(type, settings.styleName) : null;
  16495. _this._flags = 0;
  16496. _this._id = (settings.id != null) ? settings.id : null;
  16497. _this._uid = null;
  16498. _this._width = (settings.width != null) ? settings.width : null;
  16499. _this._height = (settings.height != null) ? settings.height : null;
  16500. _this._minWidth = (settings.minWidth != null) ? settings.minWidth : 0;
  16501. _this._minHeight = (settings.minHeight != null) ? settings.minHeight : 0;
  16502. _this._maxWidth = (settings.maxWidth != null) ? settings.maxWidth : Number.MAX_VALUE;
  16503. _this._maxHeight = (settings.maxHeight != null) ? settings.maxHeight : Number.MAX_VALUE;
  16504. _this._margin = null;
  16505. _this._padding = null;
  16506. _this._marginAlignment = null;
  16507. _this._setFlags(UIElement.flagIsVisible | UIElement.flagIsEnabled);
  16508. // Default Margin Alignment for UIElement is stretch for horizontal/vertical and not left/bottom (which is the default for Canvas2D Primitives)
  16509. //this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  16510. //this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  16511. // Set the layout/margin stuffs
  16512. if (settings.marginTop) {
  16513. _this.margin.setTop(settings.marginTop);
  16514. }
  16515. if (settings.marginLeft) {
  16516. _this.margin.setLeft(settings.marginLeft);
  16517. }
  16518. if (settings.marginRight) {
  16519. _this.margin.setRight(settings.marginRight);
  16520. }
  16521. if (settings.marginBottom) {
  16522. _this.margin.setBottom(settings.marginBottom);
  16523. }
  16524. if (settings.margin) {
  16525. if (typeof settings.margin === "string") {
  16526. _this.margin.fromString(settings.margin);
  16527. }
  16528. else {
  16529. _this.margin.fromUniformPixels(settings.margin);
  16530. }
  16531. }
  16532. if (settings.marginHAlignment) {
  16533. _this.marginAlignment.horizontal = settings.marginHAlignment;
  16534. }
  16535. if (settings.marginVAlignment) {
  16536. _this.marginAlignment.vertical = settings.marginVAlignment;
  16537. }
  16538. if (settings.marginAlignment) {
  16539. _this.marginAlignment.fromString(settings.marginAlignment);
  16540. }
  16541. if (settings.paddingTop) {
  16542. _this.padding.setTop(settings.paddingTop);
  16543. }
  16544. if (settings.paddingLeft) {
  16545. _this.padding.setLeft(settings.paddingLeft);
  16546. }
  16547. if (settings.paddingRight) {
  16548. _this.padding.setRight(settings.paddingRight);
  16549. }
  16550. if (settings.paddingBottom) {
  16551. _this.padding.setBottom(settings.paddingBottom);
  16552. }
  16553. if (settings.padding) {
  16554. _this.padding.fromString(settings.padding);
  16555. }
  16556. if (settings.paddingHAlignment) {
  16557. _this.paddingAlignment.horizontal = settings.paddingHAlignment;
  16558. }
  16559. if (settings.paddingVAlignment) {
  16560. _this.paddingAlignment.vertical = settings.paddingVAlignment;
  16561. }
  16562. if (settings.paddingAlignment) {
  16563. _this.paddingAlignment.fromString(settings.paddingAlignment);
  16564. }
  16565. if (settings.parent != null) {
  16566. _this._parent = settings.parent;
  16567. _this._hierarchyDepth = _this._parent._hierarchyDepth + 1;
  16568. }
  16569. return _this;
  16570. }
  16571. Object.defineProperty(UIElement, "enabledState", {
  16572. get: function () {
  16573. return UIElement._enableState;
  16574. },
  16575. enumerable: true,
  16576. configurable: true
  16577. });
  16578. Object.defineProperty(UIElement, "disabledState", {
  16579. get: function () {
  16580. return UIElement._disabledState;
  16581. },
  16582. enumerable: true,
  16583. configurable: true
  16584. });
  16585. Object.defineProperty(UIElement, "mouseOverState", {
  16586. get: function () {
  16587. return UIElement._mouseOverState;
  16588. },
  16589. enumerable: true,
  16590. configurable: true
  16591. });
  16592. UIElement.prototype.dispose = function () {
  16593. if (this.isDisposed) {
  16594. return false;
  16595. }
  16596. if (this._renderingTemplate) {
  16597. this._renderingTemplate.detach();
  16598. this._renderingTemplate = null;
  16599. }
  16600. _super.prototype.dispose.call(this);
  16601. // Don't set to null, it may upset somebody...
  16602. this.animations.splice(0);
  16603. return true;
  16604. };
  16605. /**
  16606. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  16607. * Look at Sprite2D for more information
  16608. */
  16609. UIElement.prototype.getAnimatables = function () {
  16610. return new Array();
  16611. };
  16612. // TODO
  16613. // PROPERTIES
  16614. // Style
  16615. // Id
  16616. // Parent/Children
  16617. // ActualWidth/Height, MinWidth/Height, MaxWidth/Height,
  16618. // Alignment/Margin
  16619. // Visibility, IsVisible
  16620. // IsEnabled (is false, control is disabled, no interaction and a specific render state)
  16621. // CacheMode of Visual Elements
  16622. // Focusable/IsFocused
  16623. // IsPointerCaptured, CapturePointer, IsPointerDirectlyOver, IsPointerOver. De-correlate mouse, stylus, touch?
  16624. // ContextMenu
  16625. // Cursor
  16626. // DesiredSize
  16627. // IsInputEnable ?
  16628. // Opacity, OpacityMask ?
  16629. // SnapToDevicePixels
  16630. // Tag
  16631. // ToolTip
  16632. // METHODS
  16633. // BringIntoView (for scrollable content, to move the scroll to bring the given element visible in the parent's area)
  16634. // Capture/ReleaseCapture (mouse, touch, stylus)
  16635. // Focus
  16636. // PointFrom/ToScreen to translate coordinates
  16637. // EVENTS
  16638. // ContextMenuOpening/Closing/Changed
  16639. // DragEnter/LeaveOver, Drop
  16640. // Got/LostFocus
  16641. // IsEnabledChanged
  16642. // IsPointerOver/DirectlyOverChanged
  16643. // IsVisibleChanged
  16644. // KeyDown/Up
  16645. // LayoutUpdated ?
  16646. // Pointer related events
  16647. // SizeChanged
  16648. // ToolTipOpening/Closing
  16649. UIElement.prototype.findById = function (id) {
  16650. if (this._id === id) {
  16651. return this;
  16652. }
  16653. var children = this._getChildren();
  16654. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  16655. var child = children_1[_i];
  16656. var r = child.findById(id);
  16657. if (r != null) {
  16658. return r;
  16659. }
  16660. }
  16661. };
  16662. Object.defineProperty(UIElement.prototype, "ownerWindow", {
  16663. get: function () {
  16664. return this._ownerWindow;
  16665. },
  16666. enumerable: true,
  16667. configurable: true
  16668. });
  16669. Object.defineProperty(UIElement.prototype, "style", {
  16670. get: function () {
  16671. if (!this.style) {
  16672. return GUIManager.DefaultStyleName;
  16673. }
  16674. return this._style.name;
  16675. },
  16676. set: function (value) {
  16677. if (this._style && (this._style.name === value)) {
  16678. return;
  16679. }
  16680. var newStyle = null;
  16681. if (value) {
  16682. newStyle = GUIManager.getStyle(BABYLON.Tools.getFullClassName(this), value);
  16683. if (!newStyle) {
  16684. throw Error("Couldn't find Style " + value + " for UIElement " + BABYLON.Tools.getFullClassName(this));
  16685. }
  16686. }
  16687. if (this._style) {
  16688. this._style.removeStyle(this);
  16689. }
  16690. if (newStyle) {
  16691. newStyle.applyStyle(this);
  16692. }
  16693. this._style = newStyle;
  16694. },
  16695. enumerable: true,
  16696. configurable: true
  16697. });
  16698. Object.defineProperty(UIElement.prototype, "id", {
  16699. /**
  16700. * A string that identifies the UIElement.
  16701. * The id is optional and there's possible collision with other UIElement's id as the uniqueness is not supported.
  16702. */
  16703. get: function () {
  16704. return this._id;
  16705. },
  16706. set: function (value) {
  16707. if (this._id === value) {
  16708. return;
  16709. }
  16710. this._id = value;
  16711. },
  16712. enumerable: true,
  16713. configurable: true
  16714. });
  16715. Object.defineProperty(UIElement.prototype, "uid", {
  16716. /**
  16717. * Return a unique id automatically generated.
  16718. * This property is mainly used for serialization to ensure a perfect way of identifying a UIElement
  16719. */
  16720. get: function () {
  16721. if (!this._uid) {
  16722. this._uid = BABYLON.Tools.RandomId();
  16723. }
  16724. return this._uid;
  16725. },
  16726. enumerable: true,
  16727. configurable: true
  16728. });
  16729. Object.defineProperty(UIElement.prototype, "hierarchyDepth", {
  16730. get: function () {
  16731. return this._hierarchyDepth;
  16732. },
  16733. enumerable: true,
  16734. configurable: true
  16735. });
  16736. Object.defineProperty(UIElement.prototype, "parent", {
  16737. get: function () {
  16738. return this._parent;
  16739. },
  16740. set: function (value) {
  16741. this._parent = value;
  16742. },
  16743. enumerable: true,
  16744. configurable: true
  16745. });
  16746. Object.defineProperty(UIElement.prototype, "width", {
  16747. get: function () {
  16748. return this._width;
  16749. },
  16750. set: function (value) {
  16751. this._width = value;
  16752. },
  16753. enumerable: true,
  16754. configurable: true
  16755. });
  16756. Object.defineProperty(UIElement.prototype, "height", {
  16757. get: function () {
  16758. return this._height;
  16759. },
  16760. set: function (value) {
  16761. this._height = value;
  16762. },
  16763. enumerable: true,
  16764. configurable: true
  16765. });
  16766. Object.defineProperty(UIElement.prototype, "minWidth", {
  16767. get: function () {
  16768. return this._minWidth;
  16769. },
  16770. set: function (value) {
  16771. this._minWidth = value;
  16772. },
  16773. enumerable: true,
  16774. configurable: true
  16775. });
  16776. Object.defineProperty(UIElement.prototype, "minHheight", {
  16777. get: function () {
  16778. return this._minHeight;
  16779. },
  16780. enumerable: true,
  16781. configurable: true
  16782. });
  16783. Object.defineProperty(UIElement.prototype, "minHeight", {
  16784. set: function (value) {
  16785. this._minHeight = value;
  16786. },
  16787. enumerable: true,
  16788. configurable: true
  16789. });
  16790. Object.defineProperty(UIElement.prototype, "maxWidth", {
  16791. get: function () {
  16792. return this._maxWidth;
  16793. },
  16794. set: function (value) {
  16795. this._maxWidth = value;
  16796. },
  16797. enumerable: true,
  16798. configurable: true
  16799. });
  16800. Object.defineProperty(UIElement.prototype, "maxHeight", {
  16801. get: function () {
  16802. return this._maxHeight;
  16803. },
  16804. set: function (value) {
  16805. this._maxHeight = value;
  16806. },
  16807. enumerable: true,
  16808. configurable: true
  16809. });
  16810. Object.defineProperty(UIElement.prototype, "actualWidth", {
  16811. get: function () {
  16812. return this._actualWidth;
  16813. },
  16814. set: function (value) {
  16815. this._actualWidth = value;
  16816. },
  16817. enumerable: true,
  16818. configurable: true
  16819. });
  16820. Object.defineProperty(UIElement.prototype, "actualHeight", {
  16821. get: function () {
  16822. return this._actualHeight;
  16823. },
  16824. set: function (value) {
  16825. this._actualHeight = value;
  16826. },
  16827. enumerable: true,
  16828. configurable: true
  16829. });
  16830. Object.defineProperty(UIElement.prototype, "margin", {
  16831. get: function () {
  16832. var _this = this;
  16833. if (!this._margin) {
  16834. this._margin = new BABYLON.PrimitiveThickness(function () {
  16835. if (!_this.parent) {
  16836. return null;
  16837. }
  16838. return _this.parent.margin;
  16839. });
  16840. }
  16841. return this._margin;
  16842. },
  16843. set: function (value) {
  16844. this.margin.copyFrom(value);
  16845. },
  16846. enumerable: true,
  16847. configurable: true
  16848. });
  16849. Object.defineProperty(UIElement.prototype, "_hasMargin", {
  16850. get: function () {
  16851. return (this._margin !== null && !this._margin.isDefault) || (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  16852. },
  16853. enumerable: true,
  16854. configurable: true
  16855. });
  16856. Object.defineProperty(UIElement.prototype, "padding", {
  16857. get: function () {
  16858. var _this = this;
  16859. if (!this._padding) {
  16860. this._padding = new BABYLON.PrimitiveThickness(function () {
  16861. if (!_this.parent) {
  16862. return null;
  16863. }
  16864. return _this.parent.padding;
  16865. });
  16866. }
  16867. return this._padding;
  16868. },
  16869. set: function (value) {
  16870. this.padding.copyFrom(value);
  16871. },
  16872. enumerable: true,
  16873. configurable: true
  16874. });
  16875. Object.defineProperty(UIElement.prototype, "_hasPadding", {
  16876. get: function () {
  16877. return this._padding !== null && !this._padding.isDefault;
  16878. },
  16879. enumerable: true,
  16880. configurable: true
  16881. });
  16882. Object.defineProperty(UIElement.prototype, "marginAlignment", {
  16883. get: function () {
  16884. if (!this._marginAlignment) {
  16885. this._marginAlignment = new BABYLON.PrimitiveAlignment();
  16886. }
  16887. return this._marginAlignment;
  16888. },
  16889. set: function (value) {
  16890. this.marginAlignment.copyFrom(value);
  16891. },
  16892. enumerable: true,
  16893. configurable: true
  16894. });
  16895. Object.defineProperty(UIElement.prototype, "_hasMarginAlignment", {
  16896. /**
  16897. * Check if there a marginAlignment specified (non null and not default)
  16898. */
  16899. get: function () {
  16900. return (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  16901. },
  16902. enumerable: true,
  16903. configurable: true
  16904. });
  16905. Object.defineProperty(UIElement.prototype, "paddingAlignment", {
  16906. get: function () {
  16907. if (!this._paddingAlignment) {
  16908. this._paddingAlignment = new BABYLON.PrimitiveAlignment();
  16909. }
  16910. return this._paddingAlignment;
  16911. },
  16912. set: function (value) {
  16913. this.paddingAlignment.copyFrom(value);
  16914. },
  16915. enumerable: true,
  16916. configurable: true
  16917. });
  16918. Object.defineProperty(UIElement.prototype, "_hasPaddingAlignment", {
  16919. /**
  16920. * Check if there a marginAlignment specified (non null and not default)
  16921. */
  16922. get: function () {
  16923. return (this._paddingAlignment !== null && !this._paddingAlignment.isDefault);
  16924. },
  16925. enumerable: true,
  16926. configurable: true
  16927. });
  16928. Object.defineProperty(UIElement.prototype, "isVisible", {
  16929. get: function () {
  16930. return this._isFlagSet(UIElement.flagIsVisible);
  16931. },
  16932. set: function (value) {
  16933. if (this.isVisible === value) {
  16934. return;
  16935. }
  16936. this._visualPlaceholder.levelVisible = value;
  16937. this._changeFlags(UIElement.flagIsVisible, value);
  16938. },
  16939. enumerable: true,
  16940. configurable: true
  16941. });
  16942. Object.defineProperty(UIElement.prototype, "isEnabled", {
  16943. get: function () {
  16944. return this._isFlagSet(UIElement.flagIsEnabled);
  16945. },
  16946. set: function (value) {
  16947. this._changeFlags(UIElement.flagIsEnabled, value);
  16948. },
  16949. enumerable: true,
  16950. configurable: true
  16951. });
  16952. Object.defineProperty(UIElement.prototype, "isFocused", {
  16953. get: function () {
  16954. return this._isFlagSet(UIElement.flagIsFocus);
  16955. },
  16956. set: function (value) {
  16957. // If the UIElement doesn't accept focus, set it on its parent
  16958. if (!this.isFocusable) {
  16959. var p = this.parent;
  16960. if (!p) {
  16961. return;
  16962. }
  16963. p.isFocused = value;
  16964. }
  16965. // If the focus is being set, notify the Focus Manager
  16966. if (value) {
  16967. this.ownerWindow.focusManager.setFocusOn(this, this.getFocusScope());
  16968. }
  16969. this._changeFlags(UIElement.flagIsFocus, value);
  16970. },
  16971. enumerable: true,
  16972. configurable: true
  16973. });
  16974. Object.defineProperty(UIElement.prototype, "isMouseOver", {
  16975. get: function () {
  16976. return this._isFlagSet(UIElement.flagIsMouseOver);
  16977. },
  16978. set: function (value) {
  16979. this._changeFlags(UIElement.flagIsMouseOver, value);
  16980. },
  16981. enumerable: true,
  16982. configurable: true
  16983. });
  16984. Object.defineProperty(UIElement.prototype, "isFocusScope", {
  16985. get: function () {
  16986. return this._isFlagSet(UIElement.flagIsFocusScope);
  16987. },
  16988. set: function (value) {
  16989. this._changeFlags(UIElement.flagIsFocusScope, value);
  16990. },
  16991. enumerable: true,
  16992. configurable: true
  16993. });
  16994. Object.defineProperty(UIElement.prototype, "isFocusable", {
  16995. get: function () {
  16996. return this._isFlagSet(UIElement.flagIsFocusable);
  16997. },
  16998. set: function (value) {
  16999. this._changeFlags(UIElement.flagIsFocusable, value);
  17000. },
  17001. enumerable: true,
  17002. configurable: true
  17003. });
  17004. // 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)
  17005. UIElement.prototype.getFocusScope = function () {
  17006. if (this.isFocusScope) {
  17007. return this;
  17008. }
  17009. var p = this.parent;
  17010. if (!p) {
  17011. return null;
  17012. }
  17013. return p.getFocusScope();
  17014. };
  17015. /**
  17016. * Check if a given flag is set
  17017. * @param flag the flag value
  17018. * @return true if set, false otherwise
  17019. */
  17020. UIElement.prototype._isFlagSet = function (flag) {
  17021. return (this._flags & flag) !== 0;
  17022. };
  17023. /**
  17024. * Check if all given flags are set
  17025. * @param flags the flags ORed
  17026. * @return true if all the flags are set, false otherwise
  17027. */
  17028. UIElement.prototype._areAllFlagsSet = function (flags) {
  17029. return (this._flags & flags) === flags;
  17030. };
  17031. /**
  17032. * Check if at least one flag of the given flags is set
  17033. * @param flags the flags ORed
  17034. * @return true if at least one flag is set, false otherwise
  17035. */
  17036. UIElement.prototype._areSomeFlagsSet = function (flags) {
  17037. return (this._flags & flags) !== 0;
  17038. };
  17039. /**
  17040. * Clear the given flags
  17041. * @param flags the flags to clear
  17042. */
  17043. UIElement.prototype._clearFlags = function (flags) {
  17044. this._flags &= ~flags;
  17045. };
  17046. /**
  17047. * Set the given flags to true state
  17048. * @param flags the flags ORed to set
  17049. * @return the flags state before this call
  17050. */
  17051. UIElement.prototype._setFlags = function (flags) {
  17052. var cur = this._flags;
  17053. this._flags |= flags;
  17054. return cur;
  17055. };
  17056. /**
  17057. * Change the state of the given flags
  17058. * @param flags the flags ORed to change
  17059. * @param state true to set them, false to clear them
  17060. */
  17061. UIElement.prototype._changeFlags = function (flags, state) {
  17062. if (state) {
  17063. this._flags |= flags;
  17064. }
  17065. else {
  17066. this._flags &= ~flags;
  17067. }
  17068. };
  17069. UIElement.prototype._assignTemplate = function (templateName) {
  17070. if (!templateName) {
  17071. templateName = GUIManager.DefaultTemplateName;
  17072. }
  17073. var className = BABYLON.Tools.getFullClassName(this);
  17074. if (!className) {
  17075. throw Error("Couldn't access class name of this UIElement, you have to decorate the type with the className decorator");
  17076. }
  17077. var factory = GUIManager.getRenderingTemplate(className, templateName);
  17078. if (!factory) {
  17079. throw Error("Couldn't get the renderingTemplate " + templateName + " of class " + className);
  17080. }
  17081. this._renderingTemplateName = templateName;
  17082. this._renderingTemplate = factory();
  17083. this._renderingTemplate.attach(this);
  17084. };
  17085. UIElement.prototype._createVisualTree = function () {
  17086. var parentPrim = this.ownerWindow.canvas;
  17087. if (this.parent) {
  17088. parentPrim = this.parent.visualChildrenPlaceholder;
  17089. }
  17090. if (!this._renderingTemplate) {
  17091. this._assignTemplate(this._renderingTemplateName);
  17092. }
  17093. this._visualPlaceholder = new BABYLON.Group2D({ parent: parentPrim, id: "GUI " + BABYLON.Tools.getClassName(this) + " RootGroup of " + this.id });
  17094. var p = this._visualPlaceholder;
  17095. p.addExternalData("_GUIOwnerElement_", this);
  17096. p.dataSource = this;
  17097. p.createSimpleDataBinding(BABYLON.Prim2DBase.widthProperty, "width", BABYLON.DataBinding.MODE_ONEWAY);
  17098. p.createSimpleDataBinding(BABYLON.Prim2DBase.heightProperty, "height", BABYLON.DataBinding.MODE_ONEWAY);
  17099. p.createSimpleDataBinding(BABYLON.Prim2DBase.actualWidthProperty, "actualWidth", BABYLON.DataBinding.MODE_ONEWAYTOSOURCE);
  17100. p.createSimpleDataBinding(BABYLON.Prim2DBase.actualHeightProperty, "actualHeight", BABYLON.DataBinding.MODE_ONEWAYTOSOURCE);
  17101. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "margin", BABYLON.DataBinding.MODE_ONEWAY);
  17102. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "marginAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  17103. this.createVisualTree();
  17104. };
  17105. UIElement.prototype._patchUIElement = function (ownerWindow, parent) {
  17106. if (ownerWindow) {
  17107. if (!this._ownerWindow) {
  17108. ownerWindow._registerVisualToBuild(this);
  17109. }
  17110. this._ownerWindow = ownerWindow;
  17111. }
  17112. this._parent = parent;
  17113. if (parent) {
  17114. this._hierarchyDepth = parent.hierarchyDepth + 1;
  17115. }
  17116. var children = this._getChildren();
  17117. if (children) {
  17118. for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
  17119. var curChild = children_2[_i];
  17120. curChild._patchUIElement(ownerWindow, this);
  17121. }
  17122. }
  17123. };
  17124. // 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.
  17125. UIElement.prototype._getDataSource = function () {
  17126. var levelDS = _super.prototype._getDataSource.call(this);
  17127. if (levelDS != null) {
  17128. return levelDS;
  17129. }
  17130. var p = this.parent;
  17131. if (p != null) {
  17132. return p.dataSource;
  17133. }
  17134. return null;
  17135. };
  17136. UIElement.prototype.createVisualTree = function () {
  17137. var res = this._renderingTemplate.createVisualTree(this, this._visualPlaceholder);
  17138. this._visualTemplateRoot = res.root;
  17139. this._visualChildrenPlaceholder = res.contentPlaceholder;
  17140. };
  17141. Object.defineProperty(UIElement.prototype, "visualPlaceholder", {
  17142. get: function () {
  17143. return this._visualPlaceholder;
  17144. },
  17145. enumerable: true,
  17146. configurable: true
  17147. });
  17148. Object.defineProperty(UIElement.prototype, "visualTemplateRoot", {
  17149. get: function () {
  17150. return this._visualTemplateRoot;
  17151. },
  17152. enumerable: true,
  17153. configurable: true
  17154. });
  17155. Object.defineProperty(UIElement.prototype, "visualChildrenPlaceholder", {
  17156. get: function () {
  17157. return this._visualChildrenPlaceholder;
  17158. },
  17159. enumerable: true,
  17160. configurable: true
  17161. });
  17162. Object.defineProperty(UIElement.prototype, "_position", {
  17163. get: function () { return null; } // TODO use abstract keyword when TS 2.0 will be approved
  17164. ,
  17165. enumerable: true,
  17166. configurable: true
  17167. });
  17168. return UIElement;
  17169. }(BABYLON.SmartPropertyBase));
  17170. UIElement.UIELEMENT_PROPCOUNT = 16;
  17171. UIElement.flagVisualToBuild = 0x0000001;
  17172. UIElement.flagIsVisible = 0x0000002;
  17173. UIElement.flagIsFocus = 0x0000004;
  17174. UIElement.flagIsFocusScope = 0x0000008;
  17175. UIElement.flagIsFocusable = 0x0000010;
  17176. UIElement.flagIsEnabled = 0x0000020;
  17177. UIElement.flagIsMouseOver = 0x0000040;
  17178. UIElement._enableState = "Enabled";
  17179. UIElement._disabledState = "Disabled";
  17180. UIElement._mouseOverState = "MouseOver";
  17181. __decorate([
  17182. BABYLON.dependencyProperty(0, function (pi) { return UIElement.parentProperty = pi; })
  17183. ], UIElement.prototype, "parent", null);
  17184. __decorate([
  17185. BABYLON.dependencyProperty(1, function (pi) { return UIElement.widthProperty = pi; })
  17186. ], UIElement.prototype, "width", null);
  17187. __decorate([
  17188. BABYLON.dependencyProperty(2, function (pi) { return UIElement.heightProperty = pi; })
  17189. ], UIElement.prototype, "height", null);
  17190. __decorate([
  17191. BABYLON.dependencyProperty(3, function (pi) { return UIElement.minWidthProperty = pi; })
  17192. ], UIElement.prototype, "minWidth", null);
  17193. __decorate([
  17194. BABYLON.dependencyProperty(4, function (pi) { return UIElement.minHeightProperty = pi; })
  17195. ], UIElement.prototype, "minHheight", null);
  17196. __decorate([
  17197. BABYLON.dependencyProperty(5, function (pi) { return UIElement.maxWidthProperty = pi; })
  17198. ], UIElement.prototype, "maxWidth", null);
  17199. __decorate([
  17200. BABYLON.dependencyProperty(6, function (pi) { return UIElement.maxHeightProperty = pi; })
  17201. ], UIElement.prototype, "maxHeight", null);
  17202. __decorate([
  17203. BABYLON.dependencyProperty(7, function (pi) { return UIElement.actualWidthProperty = pi; })
  17204. ], UIElement.prototype, "actualWidth", null);
  17205. __decorate([
  17206. BABYLON.dependencyProperty(8, function (pi) { return UIElement.actualHeightProperty = pi; })
  17207. ], UIElement.prototype, "actualHeight", null);
  17208. __decorate([
  17209. BABYLON.dynamicLevelProperty(9, function (pi) { return UIElement.marginProperty = pi; })
  17210. ], UIElement.prototype, "margin", null);
  17211. __decorate([
  17212. BABYLON.dynamicLevelProperty(10, function (pi) { return UIElement.paddingProperty = pi; })
  17213. ], UIElement.prototype, "padding", null);
  17214. __decorate([
  17215. BABYLON.dynamicLevelProperty(11, function (pi) { return UIElement.marginAlignmentProperty = pi; })
  17216. ], UIElement.prototype, "marginAlignment", null);
  17217. __decorate([
  17218. BABYLON.dynamicLevelProperty(12, function (pi) { return UIElement.paddingAlignmentProperty = pi; })
  17219. ], UIElement.prototype, "paddingAlignment", null);
  17220. __decorate([
  17221. BABYLON.dynamicLevelProperty(13, function (pi) { return UIElement.isEnabledProperty = pi; })
  17222. ], UIElement.prototype, "isEnabled", null);
  17223. __decorate([
  17224. BABYLON.dynamicLevelProperty(14, function (pi) { return UIElement.isFocusedProperty = pi; })
  17225. ], UIElement.prototype, "isFocused", null);
  17226. __decorate([
  17227. BABYLON.dynamicLevelProperty(15, function (pi) { return UIElement.isMouseOverProperty = pi; })
  17228. ], UIElement.prototype, "isMouseOver", null);
  17229. BABYLON.UIElement = UIElement;
  17230. var UIElementStyle = (function () {
  17231. function UIElementStyle() {
  17232. }
  17233. Object.defineProperty(UIElementStyle.prototype, "name", {
  17234. get: function () { return null; } // TODO use abstract keyword when TS 2.0 will be approved
  17235. ,
  17236. enumerable: true,
  17237. configurable: true
  17238. });
  17239. return UIElementStyle;
  17240. }());
  17241. BABYLON.UIElementStyle = UIElementStyle;
  17242. var GUIManager = (function () {
  17243. function GUIManager() {
  17244. }
  17245. /////////////////////////////////////////////////////////////////////////////////////////////////////
  17246. // DATA TEMPLATE MANAGER
  17247. GUIManager.registerDataTemplate = function (className, factory) {
  17248. };
  17249. // DATA TEMPLATE MANAGER
  17250. /////////////////////////////////////////////////////////////////////////////////////////////////////
  17251. /////////////////////////////////////////////////////////////////////////////////////////////////////
  17252. // STYLE MANAGER
  17253. GUIManager.getStyle = function (uiElType, styleName) {
  17254. var styles = GUIManager.stylesByUIElement.get(uiElType);
  17255. if (!styles) {
  17256. throw Error("The type " + uiElType + " is unknown, no style were registered for it.");
  17257. }
  17258. var style = styles.get(styleName);
  17259. if (!style) {
  17260. throw Error("Couldn't find Template " + styleName + " of UIElement type " + uiElType);
  17261. }
  17262. return style;
  17263. };
  17264. GUIManager.registerStyle = function (uiElType, templateName, style) {
  17265. var templates = GUIManager.stylesByUIElement.getOrAddWithFactory(uiElType, function () { return new BABYLON.StringDictionary(); });
  17266. if (templates.contains(templateName)) {
  17267. templates[templateName] = style;
  17268. }
  17269. else {
  17270. templates.add(templateName, style);
  17271. }
  17272. };
  17273. Object.defineProperty(GUIManager, "DefaultStyleName", {
  17274. get: function () {
  17275. return GUIManager._defaultStyleName;
  17276. },
  17277. set: function (value) {
  17278. GUIManager._defaultStyleName = value;
  17279. },
  17280. enumerable: true,
  17281. configurable: true
  17282. });
  17283. // STYLE MANAGER
  17284. /////////////////////////////////////////////////////////////////////////////////////////////////////
  17285. /////////////////////////////////////////////////////////////////////////////////////////////////////
  17286. // RENDERING TEMPLATE MANAGER
  17287. GUIManager.getRenderingTemplate = function (uiElType, templateName) {
  17288. var templates = GUIManager.renderingTemplatesByUIElement.get(uiElType);
  17289. if (!templates) {
  17290. throw Error("The type " + uiElType + " is unknown, no Rendering Template were registered for it.");
  17291. }
  17292. var templateFactory = templates.get(templateName);
  17293. if (!templateFactory) {
  17294. throw Error("Couldn't find Template " + templateName + " of UI Element type " + uiElType);
  17295. }
  17296. return templateFactory;
  17297. };
  17298. GUIManager.registerRenderingTemplate = function (uiElType, templateName, factory) {
  17299. var templates = GUIManager.renderingTemplatesByUIElement.getOrAddWithFactory(uiElType, function () { return new BABYLON.StringDictionary(); });
  17300. if (templates.contains(templateName)) {
  17301. templates[templateName] = factory;
  17302. }
  17303. else {
  17304. templates.add(templateName, factory);
  17305. }
  17306. };
  17307. Object.defineProperty(GUIManager, "DefaultTemplateName", {
  17308. get: function () {
  17309. return GUIManager._defaultTemplateName;
  17310. },
  17311. set: function (value) {
  17312. GUIManager._defaultTemplateName = value;
  17313. },
  17314. enumerable: true,
  17315. configurable: true
  17316. });
  17317. return GUIManager;
  17318. }());
  17319. GUIManager.stylesByUIElement = new BABYLON.StringDictionary();
  17320. GUIManager.renderingTemplatesByUIElement = new BABYLON.StringDictionary();
  17321. // RENDERING TEMPLATE MANAGER
  17322. /////////////////////////////////////////////////////////////////////////////////////////////////////
  17323. GUIManager._defaultTemplateName = "Default";
  17324. GUIManager._defaultStyleName = "Default";
  17325. BABYLON.GUIManager = GUIManager;
  17326. var UIElementRenderingTemplateBase = (function () {
  17327. function UIElementRenderingTemplateBase() {
  17328. }
  17329. UIElementRenderingTemplateBase.prototype.attach = function (owner) {
  17330. this._owner = owner;
  17331. };
  17332. UIElementRenderingTemplateBase.prototype.detach = function () {
  17333. };
  17334. Object.defineProperty(UIElementRenderingTemplateBase.prototype, "owner", {
  17335. get: function () {
  17336. return this._owner;
  17337. },
  17338. enumerable: true,
  17339. configurable: true
  17340. });
  17341. return UIElementRenderingTemplateBase;
  17342. }());
  17343. BABYLON.UIElementRenderingTemplateBase = UIElementRenderingTemplateBase;
  17344. function registerWindowRenderingTemplate(uiElType, templateName, factory) {
  17345. return function () {
  17346. GUIManager.registerRenderingTemplate(uiElType, templateName, factory);
  17347. };
  17348. }
  17349. BABYLON.registerWindowRenderingTemplate = registerWindowRenderingTemplate;
  17350. })(BABYLON || (BABYLON = {}));
  17351. var __extends = (this && this.__extends) || function (d, b) {
  17352. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17353. function __() { this.constructor = d; }
  17354. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17355. };
  17356. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  17357. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17358. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  17359. 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;
  17360. return c > 3 && r && Object.defineProperty(target, key, r), r;
  17361. };
  17362. var BABYLON;
  17363. (function (BABYLON) {
  17364. var StackPanel = StackPanel_1 = (function (_super) {
  17365. __extends(StackPanel, _super);
  17366. function StackPanel(settings) {
  17367. var _this;
  17368. if (!settings) {
  17369. settings = {};
  17370. }
  17371. _this = _super.call(this, settings) || this;
  17372. _this.isOrientationHorizontal = (settings.isOrientationHorizontal == null) ? true : settings.isOrientationHorizontal;
  17373. _this._children = new Array();
  17374. if (settings.children != null) {
  17375. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  17376. var child = _a[_i];
  17377. _this._children.push(child);
  17378. }
  17379. }
  17380. return _this;
  17381. }
  17382. Object.defineProperty(StackPanel.prototype, "isOrientationHorizontal", {
  17383. get: function () {
  17384. return this._isOrientationHorizontal;
  17385. },
  17386. set: function (value) {
  17387. this._isOrientationHorizontal = value;
  17388. },
  17389. enumerable: true,
  17390. configurable: true
  17391. });
  17392. StackPanel.prototype.createVisualTree = function () {
  17393. _super.prototype.createVisualTree.call(this);
  17394. // A StackPanel Control has a Group2D, child of the visualPlaceHolder, which is the Children placeholder.
  17395. // The Children UIElement Tree will be create inside this placeholder.
  17396. this._childrenPlaceholder = new BABYLON.Group2D({ parent: this._visualPlaceholder, id: "StackPanel Children Placeholder of " + this.id });
  17397. var p = this._childrenPlaceholder;
  17398. p.layoutEngine = this.isOrientationHorizontal ? BABYLON.StackPanelLayoutEngine.Horizontal : BABYLON.StackPanelLayoutEngine.Vertical;
  17399. // 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.
  17400. p.dataSource = this;
  17401. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "padding", BABYLON.DataBinding.MODE_ONEWAY);
  17402. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "paddingAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  17403. // The UIElement set the childrenPlaceholder with the visual returned by the renderingTemplate.
  17404. // But it's not the case for a StackPanel, the placeholder of UIElement Children (the content)
  17405. this._visualChildrenPlaceholder = this._childrenPlaceholder;
  17406. };
  17407. Object.defineProperty(StackPanel.prototype, "children", {
  17408. get: function () {
  17409. return this._children;
  17410. },
  17411. enumerable: true,
  17412. configurable: true
  17413. });
  17414. StackPanel.prototype._getChildren = function () {
  17415. return this.children;
  17416. };
  17417. return StackPanel;
  17418. }(BABYLON.UIElement));
  17419. StackPanel.STACKPANEL_PROPCOUNT = BABYLON.UIElement.UIELEMENT_PROPCOUNT + 3;
  17420. __decorate([
  17421. BABYLON.dependencyProperty(StackPanel_1.STACKPANEL_PROPCOUNT + 0, function (pi) { return StackPanel_1.orientationHorizontalProperty = pi; })
  17422. ], StackPanel.prototype, "isOrientationHorizontal", null);
  17423. StackPanel = StackPanel_1 = __decorate([
  17424. BABYLON.className("StackPanel", "BABYLON")
  17425. ], StackPanel);
  17426. BABYLON.StackPanel = StackPanel;
  17427. var DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate_1 = (function (_super) {
  17428. __extends(DefaultStackPanelRenderingTemplate, _super);
  17429. function DefaultStackPanelRenderingTemplate() {
  17430. return _super.apply(this, arguments) || this;
  17431. }
  17432. DefaultStackPanelRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  17433. return { root: visualPlaceholder, contentPlaceholder: visualPlaceholder };
  17434. };
  17435. DefaultStackPanelRenderingTemplate.prototype.attach = function (owner) {
  17436. _super.prototype.attach.call(this, owner);
  17437. };
  17438. return DefaultStackPanelRenderingTemplate;
  17439. }(BABYLON.UIElementRenderingTemplateBase));
  17440. DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate_1 = __decorate([
  17441. BABYLON.registerWindowRenderingTemplate("BABYLON.StackPanel", "Default", function () { return new DefaultStackPanelRenderingTemplate_1(); })
  17442. ], DefaultStackPanelRenderingTemplate);
  17443. BABYLON.DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate;
  17444. var StackPanel_1, DefaultStackPanelRenderingTemplate_1;
  17445. })(BABYLON || (BABYLON = {}));
  17446. var __extends = (this && this.__extends) || function (d, b) {
  17447. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17448. function __() { this.constructor = d; }
  17449. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17450. };
  17451. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  17452. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17453. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  17454. 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;
  17455. return c > 3 && r && Object.defineProperty(target, key, r), r;
  17456. };
  17457. var BABYLON;
  17458. (function (BABYLON) {
  17459. var Control = Control_1 = (function (_super) {
  17460. __extends(Control, _super);
  17461. function Control(settings) {
  17462. return _super.call(this, settings) || this;
  17463. }
  17464. Object.defineProperty(Control.prototype, "background", {
  17465. get: function () {
  17466. if (!this._background) {
  17467. this._background = new BABYLON.ObservableStringDictionary(false);
  17468. }
  17469. return this._background;
  17470. },
  17471. set: function (value) {
  17472. this.background.copyFrom(value);
  17473. },
  17474. enumerable: true,
  17475. configurable: true
  17476. });
  17477. Object.defineProperty(Control.prototype, "border", {
  17478. get: function () {
  17479. return this._border;
  17480. },
  17481. set: function (value) {
  17482. this._border = value;
  17483. },
  17484. enumerable: true,
  17485. configurable: true
  17486. });
  17487. Object.defineProperty(Control.prototype, "borderThickness", {
  17488. get: function () {
  17489. return this._borderThickness;
  17490. },
  17491. set: function (value) {
  17492. this._borderThickness = value;
  17493. },
  17494. enumerable: true,
  17495. configurable: true
  17496. });
  17497. Object.defineProperty(Control.prototype, "fontName", {
  17498. get: function () {
  17499. return this._fontName;
  17500. },
  17501. set: function (value) {
  17502. this._fontName = value;
  17503. },
  17504. enumerable: true,
  17505. configurable: true
  17506. });
  17507. Object.defineProperty(Control.prototype, "foreground", {
  17508. get: function () {
  17509. return this._foreground;
  17510. },
  17511. set: function (value) {
  17512. this._foreground = value;
  17513. },
  17514. enumerable: true,
  17515. configurable: true
  17516. });
  17517. return Control;
  17518. }(BABYLON.UIElement));
  17519. Control.CONTROL_PROPCOUNT = BABYLON.UIElement.UIELEMENT_PROPCOUNT + 5;
  17520. __decorate([
  17521. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 0, function (pi) { return Control_1.backgroundProperty = pi; })
  17522. ], Control.prototype, "background", null);
  17523. __decorate([
  17524. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 1, function (pi) { return Control_1.borderProperty = pi; })
  17525. ], Control.prototype, "border", null);
  17526. __decorate([
  17527. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 2, function (pi) { return Control_1.borderThicknessProperty = pi; })
  17528. ], Control.prototype, "borderThickness", null);
  17529. __decorate([
  17530. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 3, function (pi) { return Control_1.fontNameProperty = pi; })
  17531. ], Control.prototype, "fontName", null);
  17532. __decorate([
  17533. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 4, function (pi) { return Control_1.foregroundProperty = pi; })
  17534. ], Control.prototype, "foreground", null);
  17535. Control = Control_1 = __decorate([
  17536. BABYLON.className("Control", "BABYLON")
  17537. ], Control);
  17538. BABYLON.Control = Control;
  17539. var Control_1;
  17540. })(BABYLON || (BABYLON = {}));
  17541. var __extends = (this && this.__extends) || function (d, b) {
  17542. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17543. function __() { this.constructor = d; }
  17544. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17545. };
  17546. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  17547. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17548. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  17549. 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;
  17550. return c > 3 && r && Object.defineProperty(target, key, r), r;
  17551. };
  17552. var BABYLON;
  17553. (function (BABYLON) {
  17554. var ContentControl = ContentControl_1 = (function (_super) {
  17555. __extends(ContentControl, _super);
  17556. function ContentControl(settings) {
  17557. var _this;
  17558. if (!settings) {
  17559. settings = {};
  17560. }
  17561. _this = _super.call(this, settings) || this;
  17562. if (settings.content != null) {
  17563. _this._content = settings.content;
  17564. }
  17565. return _this;
  17566. }
  17567. ContentControl.prototype.dispose = function () {
  17568. if (this.isDisposed) {
  17569. return false;
  17570. }
  17571. if (this.content && this.content.dispose) {
  17572. this.content.dispose();
  17573. this.content = null;
  17574. }
  17575. if (this.__contentUIElement) {
  17576. this.__contentUIElement.dispose();
  17577. this.__contentUIElement = null;
  17578. }
  17579. _super.prototype.dispose.call(this);
  17580. return true;
  17581. };
  17582. Object.defineProperty(ContentControl.prototype, "content", {
  17583. get: function () {
  17584. return this._content;
  17585. },
  17586. set: function (value) {
  17587. this._content = value;
  17588. },
  17589. enumerable: true,
  17590. configurable: true
  17591. });
  17592. Object.defineProperty(ContentControl.prototype, "_contentUIElement", {
  17593. get: function () {
  17594. if (!this.__contentUIElement) {
  17595. this._buildContentUIElement();
  17596. }
  17597. return this.__contentUIElement;
  17598. },
  17599. enumerable: true,
  17600. configurable: true
  17601. });
  17602. ContentControl.prototype._createVisualTree = function () {
  17603. // Base implementation will create the Group2D for the Visual Placeholder and its Visual Tree
  17604. _super.prototype._createVisualTree.call(this);
  17605. // A Content Control has a Group2D, child of the visualPlaceHolder, which is the Content placeholder.
  17606. // The Content UIElement Tree will be create inside this placeholder.
  17607. this._contentPlaceholder = new BABYLON.Group2D({ parent: this._visualPlaceholder, id: "ContentControl Content Placeholder of " + this.id });
  17608. var p = this._contentPlaceholder;
  17609. // 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.
  17610. p.dataSource = this;
  17611. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "padding", BABYLON.DataBinding.MODE_ONEWAY);
  17612. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "paddingAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  17613. // The UIElement set the childrenPlaceholder with the visual returned by the renderingTemplate.
  17614. // But it's not the case for a ContentControl, the placeholder of UIElement Children (the content)
  17615. this._visualChildrenPlaceholder = this._contentPlaceholder;
  17616. };
  17617. ContentControl.prototype._buildContentUIElement = function () {
  17618. var c = this._content;
  17619. this.__contentUIElement = null;
  17620. // Already a UIElement
  17621. if (c instanceof BABYLON.UIElement) {
  17622. this.__contentUIElement = c;
  17623. }
  17624. else if ((typeof c === "string") || (typeof c === "boolean") || (typeof c === "number")) {
  17625. var l = new BABYLON.Label({ parent: this, id: "Content of " + this.id });
  17626. var binding = new BABYLON.DataBinding();
  17627. binding.propertyPathName = "content";
  17628. binding.stringFormat = function (v) { return "" + v; };
  17629. binding.dataSource = this;
  17630. l.createDataBinding(BABYLON.Label.textProperty, binding);
  17631. this.__contentUIElement = l;
  17632. }
  17633. else {
  17634. }
  17635. if (this.__contentUIElement) {
  17636. this.__contentUIElement._patchUIElement(this.ownerWindow, this);
  17637. }
  17638. };
  17639. ContentControl.prototype._getChildren = function () {
  17640. var children = new Array();
  17641. if (this.content) {
  17642. children.push(this._contentUIElement);
  17643. }
  17644. return children;
  17645. };
  17646. return ContentControl;
  17647. }(BABYLON.Control));
  17648. ContentControl.CONTENTCONTROL_PROPCOUNT = BABYLON.Control.CONTROL_PROPCOUNT + 2;
  17649. __decorate([
  17650. BABYLON.dependencyProperty(BABYLON.Control.CONTROL_PROPCOUNT + 0, function (pi) { return ContentControl_1.contentProperty = pi; })
  17651. ], ContentControl.prototype, "content", null);
  17652. ContentControl = ContentControl_1 = __decorate([
  17653. BABYLON.className("ContentControl", "BABYLON")
  17654. ], ContentControl);
  17655. BABYLON.ContentControl = ContentControl;
  17656. var ContentControl_1;
  17657. })(BABYLON || (BABYLON = {}));
  17658. var __extends = (this && this.__extends) || function (d, b) {
  17659. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17660. function __() { this.constructor = d; }
  17661. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17662. };
  17663. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  17664. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17665. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  17666. 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;
  17667. return c > 3 && r && Object.defineProperty(target, key, r), r;
  17668. };
  17669. var BABYLON;
  17670. (function (BABYLON) {
  17671. var FocusScopeData = (function () {
  17672. function FocusScopeData(focusScope) {
  17673. this.focusScope = focusScope;
  17674. this.focusedElement = null;
  17675. }
  17676. return FocusScopeData;
  17677. }());
  17678. var FocusManager = (function () {
  17679. function FocusManager() {
  17680. this._focusScopes = new BABYLON.StringDictionary();
  17681. this._rootScope = new FocusScopeData(null);
  17682. this._activeScope = null;
  17683. }
  17684. FocusManager.prototype.setFocusOn = function (el, focusScope) {
  17685. var fsd = (focusScope != null) ? this._focusScopes.getOrAddWithFactory(focusScope.uid, function (k) { return new FocusScopeData(focusScope); }) : this._rootScope;
  17686. if (fsd.focusedElement !== el) {
  17687. // Remove focus from current
  17688. if (fsd.focusedElement) {
  17689. fsd.focusedElement.isFocused = false;
  17690. }
  17691. fsd.focusedElement = el;
  17692. }
  17693. if (this._activeScope !== fsd) {
  17694. this._activeScope = fsd;
  17695. }
  17696. };
  17697. return FocusManager;
  17698. }());
  17699. BABYLON.FocusManager = FocusManager;
  17700. var GUISceneData = (function () {
  17701. function GUISceneData(scene) {
  17702. this.scene = scene;
  17703. this.screenSpaceCanvas = new BABYLON.ScreenSpaceCanvas2D(scene, { id: "GUI Canvas", cachingStrategy: BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE });
  17704. this.focusManager = new FocusManager();
  17705. }
  17706. return GUISceneData;
  17707. }());
  17708. var Window = Window_1 = (function (_super) {
  17709. __extends(Window, _super);
  17710. function Window(scene, settings) {
  17711. var _this;
  17712. if (!settings) {
  17713. settings = {};
  17714. }
  17715. _this = _super.call(this, settings) || this;
  17716. // Per default a Window is focus scope
  17717. _this.isFocusScope = true;
  17718. _this.isActive = false;
  17719. if (!_this._UIElementVisualToBuildList) {
  17720. _this._UIElementVisualToBuildList = new Array();
  17721. }
  17722. // Patch the owner and also the parent property through the whole tree
  17723. _this._patchUIElement(_this, null);
  17724. // Screen Space UI
  17725. if (!settings.worldPosition && !settings.worldRotation) {
  17726. _this._sceneData = Window_1.getSceneData(scene);
  17727. _this._canvas = _this._sceneData.screenSpaceCanvas;
  17728. _this._isWorldSpaceCanvas = false;
  17729. _this._left = (settings.left != null) ? settings.left : 0;
  17730. _this._bottom = (settings.bottom != null) ? settings.bottom : 0;
  17731. }
  17732. else {
  17733. var w = (settings.width == null) ? 100 : settings.width;
  17734. var h = (settings.height == null) ? 100 : settings.height;
  17735. var wpos = (settings.worldPosition == null) ? BABYLON.Vector3.Zero() : settings.worldPosition;
  17736. var wrot = (settings.worldRotation == null) ? BABYLON.Quaternion.Identity() : settings.worldRotation;
  17737. _this._canvas = new BABYLON.WorldSpaceCanvas2D(scene, new BABYLON.Size(w, h), { id: "GUI Canvas", cachingStrategy: BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE, worldPosition: wpos, worldRotation: wrot });
  17738. _this._isWorldSpaceCanvas = true;
  17739. }
  17740. _this._renderObserver = _this._canvas.renderObservable.add(function (e, s) { return _this._canvasPreRender(); }, BABYLON.Canvas2D.RENDEROBSERVABLE_PRE);
  17741. _this._disposeObserver = _this._canvas.disposeObservable.add(function (e, s) { return _this._canvasDisposed(); });
  17742. _this._canvas.propertyChanged.add(function (e, s) {
  17743. if (e.propertyName === "overPrim") {
  17744. _this._overPrimChanged(e.oldValue, e.newValue);
  17745. }
  17746. });
  17747. _this._mouseOverUIElement = null;
  17748. return _this;
  17749. }
  17750. Object.defineProperty(Window.prototype, "canvas", {
  17751. get: function () {
  17752. return this._canvas;
  17753. },
  17754. enumerable: true,
  17755. configurable: true
  17756. });
  17757. Object.defineProperty(Window.prototype, "left", {
  17758. get: function () {
  17759. return this._left;
  17760. },
  17761. set: function (value) {
  17762. var old = new BABYLON.Vector2(this._left, this._bottom);
  17763. this._left = value;
  17764. this.onPropertyChanged("_position", old, this._position);
  17765. },
  17766. enumerable: true,
  17767. configurable: true
  17768. });
  17769. Object.defineProperty(Window.prototype, "bottom", {
  17770. get: function () {
  17771. return this._bottom;
  17772. },
  17773. set: function (value) {
  17774. var old = new BABYLON.Vector2(this._left, this._bottom);
  17775. this._bottom = value;
  17776. this.onPropertyChanged("_position", old, this._position);
  17777. },
  17778. enumerable: true,
  17779. configurable: true
  17780. });
  17781. Object.defineProperty(Window.prototype, "position", {
  17782. get: function () {
  17783. return this._position;
  17784. },
  17785. set: function (value) {
  17786. this._left = value.x;
  17787. this._bottom = value.y;
  17788. },
  17789. enumerable: true,
  17790. configurable: true
  17791. });
  17792. Object.defineProperty(Window.prototype, "isActive", {
  17793. get: function () {
  17794. return this._isActive;
  17795. },
  17796. set: function (value) {
  17797. this._isActive = value;
  17798. },
  17799. enumerable: true,
  17800. configurable: true
  17801. });
  17802. Object.defineProperty(Window.prototype, "focusManager", {
  17803. get: function () {
  17804. return this._sceneData.focusManager;
  17805. },
  17806. enumerable: true,
  17807. configurable: true
  17808. });
  17809. Object.defineProperty(Window.prototype, "_position", {
  17810. get: function () {
  17811. return new BABYLON.Vector2(this.left, this.bottom);
  17812. },
  17813. enumerable: true,
  17814. configurable: true
  17815. });
  17816. Window.prototype.createVisualTree = function () {
  17817. _super.prototype.createVisualTree.call(this);
  17818. var p = this._visualPlaceholder;
  17819. p.createSimpleDataBinding(BABYLON.Group2D.positionProperty, "position");
  17820. };
  17821. Window.prototype._registerVisualToBuild = function (uiel) {
  17822. if (uiel._isFlagSet(BABYLON.UIElement.flagVisualToBuild)) {
  17823. return;
  17824. }
  17825. if (!this._UIElementVisualToBuildList) {
  17826. this._UIElementVisualToBuildList = new Array();
  17827. }
  17828. this._UIElementVisualToBuildList.push(uiel);
  17829. uiel._setFlags(BABYLON.UIElement.flagVisualToBuild);
  17830. };
  17831. Window.prototype._overPrimChanged = function (oldPrim, newPrim) {
  17832. var curOverEl = this._mouseOverUIElement;
  17833. var newOverEl = null;
  17834. var curGroup = newPrim ? newPrim.traverseUp(function (p) { return p instanceof BABYLON.Group2D; }) : null;
  17835. while (curGroup) {
  17836. var uiel = curGroup.getExternalData("_GUIOwnerElement_");
  17837. if (uiel) {
  17838. newOverEl = uiel;
  17839. break;
  17840. }
  17841. curGroup = curGroup.parent ? curGroup.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D; }) : null;
  17842. }
  17843. if (curOverEl === newOverEl) {
  17844. return;
  17845. }
  17846. if (curOverEl) {
  17847. curOverEl.isMouseOver = false;
  17848. }
  17849. if (newOverEl) {
  17850. newOverEl.isMouseOver = true;
  17851. }
  17852. this._mouseOverUIElement = newOverEl;
  17853. };
  17854. Window.prototype._canvasPreRender = function () {
  17855. // Check if we have visual to create
  17856. if (this._UIElementVisualToBuildList.length > 0) {
  17857. // Sort the UI Element to get the highest (so lowest hierarchy depth) in the hierarchy tree first
  17858. var sortedElementList = this._UIElementVisualToBuildList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  17859. for (var _i = 0, sortedElementList_1 = sortedElementList; _i < sortedElementList_1.length; _i++) {
  17860. var el = sortedElementList_1[_i];
  17861. el._createVisualTree();
  17862. }
  17863. this._UIElementVisualToBuildList.splice(0);
  17864. }
  17865. };
  17866. Window.prototype._canvasDisposed = function () {
  17867. this._canvas.disposeObservable.remove(this._disposeObserver);
  17868. this._canvas.renderObservable.remove(this._renderObserver);
  17869. };
  17870. Window.getSceneData = function (scene) {
  17871. return Window_1._sceneData.getOrAddWithFactory(scene.uid, function (k) { return new GUISceneData(scene); });
  17872. };
  17873. return Window;
  17874. }(BABYLON.ContentControl));
  17875. Window.WINDOW_PROPCOUNT = BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 4;
  17876. Window._sceneData = new BABYLON.StringDictionary();
  17877. __decorate([
  17878. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 0, function (pi) { return Window_1.leftProperty = pi; })
  17879. ], Window.prototype, "left", null);
  17880. __decorate([
  17881. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 1, function (pi) { return Window_1.bottomProperty = pi; })
  17882. ], Window.prototype, "bottom", null);
  17883. __decorate([
  17884. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 2, function (pi) { return Window_1.positionProperty = pi; })
  17885. ], Window.prototype, "position", null);
  17886. __decorate([
  17887. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 3, function (pi) { return Window_1.isActiveProperty = pi; })
  17888. ], Window.prototype, "isActive", null);
  17889. Window = Window_1 = __decorate([
  17890. BABYLON.className("Window", "BABYLON")
  17891. ], Window);
  17892. BABYLON.Window = Window;
  17893. var DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate_1 = (function (_super) {
  17894. __extends(DefaultWindowRenderingTemplate, _super);
  17895. function DefaultWindowRenderingTemplate() {
  17896. return _super.apply(this, arguments) || this;
  17897. }
  17898. DefaultWindowRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  17899. var r = new BABYLON.Rectangle2D({ parent: visualPlaceholder, fill: "#808080FF" });
  17900. return { root: r, contentPlaceholder: r };
  17901. };
  17902. return DefaultWindowRenderingTemplate;
  17903. }(BABYLON.UIElementRenderingTemplateBase));
  17904. DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate_1 = __decorate([
  17905. BABYLON.registerWindowRenderingTemplate("BABYLON.Window", "Default", function () { return new DefaultWindowRenderingTemplate_1(); })
  17906. ], DefaultWindowRenderingTemplate);
  17907. BABYLON.DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate;
  17908. var Window_1, DefaultWindowRenderingTemplate_1;
  17909. })(BABYLON || (BABYLON = {}));
  17910. var __extends = (this && this.__extends) || function (d, b) {
  17911. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17912. function __() { this.constructor = d; }
  17913. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17914. };
  17915. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  17916. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17917. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  17918. 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;
  17919. return c > 3 && r && Object.defineProperty(target, key, r), r;
  17920. };
  17921. var BABYLON;
  17922. (function (BABYLON) {
  17923. var Label = Label_1 = (function (_super) {
  17924. __extends(Label, _super);
  17925. function Label(settings) {
  17926. var _this;
  17927. if (!settings) {
  17928. settings = {};
  17929. }
  17930. _this = _super.call(this, settings) || this;
  17931. if (settings.text != null) {
  17932. _this.text = settings.text;
  17933. }
  17934. return _this;
  17935. }
  17936. Object.defineProperty(Label.prototype, "_position", {
  17937. get: function () {
  17938. return BABYLON.Vector2.Zero();
  17939. },
  17940. enumerable: true,
  17941. configurable: true
  17942. });
  17943. Label.prototype._getChildren = function () {
  17944. return Label_1._emptyArray;
  17945. };
  17946. Label.prototype.createVisualTree = function () {
  17947. _super.prototype.createVisualTree.call(this);
  17948. var p = this._visualChildrenPlaceholder;
  17949. };
  17950. Object.defineProperty(Label.prototype, "text", {
  17951. get: function () {
  17952. return this._text;
  17953. },
  17954. set: function (value) {
  17955. this._text = value;
  17956. },
  17957. enumerable: true,
  17958. configurable: true
  17959. });
  17960. return Label;
  17961. }(BABYLON.Control));
  17962. Label._emptyArray = new Array();
  17963. __decorate([
  17964. BABYLON.dependencyProperty(BABYLON.Control.CONTROL_PROPCOUNT + 0, function (pi) { return Label_1.textProperty = pi; })
  17965. ], Label.prototype, "text", null);
  17966. Label = Label_1 = __decorate([
  17967. BABYLON.className("Label", "BABYLON")
  17968. ], Label);
  17969. BABYLON.Label = Label;
  17970. var DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate_1 = (function (_super) {
  17971. __extends(DefaultLabelRenderingTemplate, _super);
  17972. function DefaultLabelRenderingTemplate() {
  17973. return _super.apply(this, arguments) || this;
  17974. }
  17975. DefaultLabelRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  17976. var r = new BABYLON.Text2D("", { parent: visualPlaceholder });
  17977. r.createSimpleDataBinding(BABYLON.Text2D.textProperty, "text");
  17978. r.dataSource = owner;
  17979. return { root: r, contentPlaceholder: r };
  17980. };
  17981. return DefaultLabelRenderingTemplate;
  17982. }(BABYLON.UIElementRenderingTemplateBase));
  17983. DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate_1 = __decorate([
  17984. BABYLON.registerWindowRenderingTemplate("BABYLON.Label", "Default", function () { return new DefaultLabelRenderingTemplate_1(); })
  17985. ], DefaultLabelRenderingTemplate);
  17986. BABYLON.DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate;
  17987. var Label_1, DefaultLabelRenderingTemplate_1;
  17988. })(BABYLON || (BABYLON = {}));
  17989. var __extends = (this && this.__extends) || function (d, b) {
  17990. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17991. function __() { this.constructor = d; }
  17992. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17993. };
  17994. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  17995. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17996. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  17997. 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;
  17998. return c > 3 && r && Object.defineProperty(target, key, r), r;
  17999. };
  18000. var BABYLON;
  18001. (function (BABYLON) {
  18002. var Button = Button_1 = (function (_super) {
  18003. __extends(Button, _super);
  18004. function Button(settings) {
  18005. var _this;
  18006. if (!settings) {
  18007. settings = {};
  18008. }
  18009. _this = _super.call(this, settings) || this;
  18010. if (settings.paddingAlignment == null) {
  18011. _this.paddingAlignment.horizontal = BABYLON.PrimitiveAlignment.AlignCenter;
  18012. _this.paddingAlignment.vertical = BABYLON.PrimitiveAlignment.AlignCenter;
  18013. }
  18014. _this._normalStateBackground = new BABYLON.ObservableStringDictionary(false);
  18015. _this._normalStateBorder = new BABYLON.ObservableStringDictionary(false);
  18016. _this._defaultStateBackground = new BABYLON.ObservableStringDictionary(false);
  18017. _this._defaultStateBorder = new BABYLON.ObservableStringDictionary(false);
  18018. _this._normalStateBackground.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#337AB7FF"));
  18019. _this._normalStateBackground.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#7BA9D0FF"));
  18020. _this._normalStateBackground.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#286090FF"));
  18021. _this._normalStateBackground.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#1E496EFF"));
  18022. _this._normalStateBorder.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#2E6DA4FF"));
  18023. _this._normalStateBorder.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#77A0C4FF"));
  18024. _this._normalStateBorder.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#204D74FF"));
  18025. _this._normalStateBorder.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#2E5D9EFF"));
  18026. _this._defaultStateBackground.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"));
  18027. _this._defaultStateBackground.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"));
  18028. _this._defaultStateBackground.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#E6E6E6FF"));
  18029. _this._defaultStateBackground.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#D4D4D4FF"));
  18030. _this._defaultStateBorder.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#CCCCCCFF"));
  18031. _this._defaultStateBorder.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#DEDEDEFF"));
  18032. _this._defaultStateBorder.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#ADADADFF"));
  18033. _this._defaultStateBorder.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#6C8EC5FF"));
  18034. return _this;
  18035. }
  18036. Object.defineProperty(Button, "pushedState", {
  18037. get: function () {
  18038. return Button_1._pushedState;
  18039. },
  18040. enumerable: true,
  18041. configurable: true
  18042. });
  18043. Object.defineProperty(Button.prototype, "isPushed", {
  18044. get: function () {
  18045. return this._isPushed;
  18046. },
  18047. set: function (value) {
  18048. this._isPushed = value;
  18049. },
  18050. enumerable: true,
  18051. configurable: true
  18052. });
  18053. Object.defineProperty(Button.prototype, "isDefault", {
  18054. get: function () {
  18055. return this._isDefault;
  18056. },
  18057. set: function (value) {
  18058. this._isDefault = value;
  18059. },
  18060. enumerable: true,
  18061. configurable: true
  18062. });
  18063. Object.defineProperty(Button.prototype, "isOutline", {
  18064. get: function () {
  18065. return this._isOutline;
  18066. },
  18067. set: function (value) {
  18068. this._isOutline = value;
  18069. },
  18070. enumerable: true,
  18071. configurable: true
  18072. });
  18073. Object.defineProperty(Button.prototype, "clickObservable", {
  18074. get: function () {
  18075. if (!this._clickObservable) {
  18076. this._clickObservable = new BABYLON.Observable();
  18077. }
  18078. return this._clickObservable;
  18079. },
  18080. enumerable: true,
  18081. configurable: true
  18082. });
  18083. Button.prototype._raiseClick = function () {
  18084. if (this._clickObservable && this._clickObservable.hasObservers()) {
  18085. this._clickObservable.notifyObservers(this);
  18086. }
  18087. };
  18088. Button.prototype.createVisualTree = function () {
  18089. var _this = this;
  18090. _super.prototype.createVisualTree.call(this);
  18091. var p = this._visualPlaceholder;
  18092. p.pointerEventObservable.add(function (e, s) {
  18093. // check if input must be discarded
  18094. if (!_this.isVisible || !_this.isEnabled) {
  18095. return;
  18096. }
  18097. // We reject an event coming from the placeholder because it means it's on an empty spot, so it's not valid.
  18098. if (e.relatedTarget === _this._visualPlaceholder) {
  18099. return;
  18100. }
  18101. if (s.mask === BABYLON.PrimitivePointerInfo.PointerUp) {
  18102. _this._raiseClick();
  18103. _this.isPushed = false;
  18104. }
  18105. else if (s.mask === BABYLON.PrimitivePointerInfo.PointerDown) {
  18106. _this.isPushed = true;
  18107. _this.isFocused = true;
  18108. }
  18109. }, BABYLON.PrimitivePointerInfo.PointerUp | BABYLON.PrimitivePointerInfo.PointerDown);
  18110. };
  18111. Object.defineProperty(Button.prototype, "normalStateBackground", {
  18112. get: function () {
  18113. return this._normalStateBackground;
  18114. },
  18115. enumerable: true,
  18116. configurable: true
  18117. });
  18118. Object.defineProperty(Button.prototype, "defaultStateBackground", {
  18119. get: function () {
  18120. return this._defaultStateBackground;
  18121. },
  18122. enumerable: true,
  18123. configurable: true
  18124. });
  18125. Object.defineProperty(Button.prototype, "normalStateBorder", {
  18126. get: function () {
  18127. return this._normalStateBorder;
  18128. },
  18129. enumerable: true,
  18130. configurable: true
  18131. });
  18132. Object.defineProperty(Button.prototype, "defaultStateBorder", {
  18133. get: function () {
  18134. return this._defaultStateBorder;
  18135. },
  18136. enumerable: true,
  18137. configurable: true
  18138. });
  18139. return Button;
  18140. }(BABYLON.ContentControl));
  18141. Button.BUTTON_PROPCOUNT = BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 3;
  18142. Button._pushedState = "Pushed";
  18143. __decorate([
  18144. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 0, function (pi) { return Button_1.isPushedProperty = pi; })
  18145. ], Button.prototype, "isPushed", null);
  18146. __decorate([
  18147. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 1, function (pi) { return Button_1.isDefaultProperty = pi; })
  18148. ], Button.prototype, "isDefault", null);
  18149. __decorate([
  18150. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 2, function (pi) { return Button_1.isOutlineProperty = pi; })
  18151. ], Button.prototype, "isOutline", null);
  18152. Button = Button_1 = __decorate([
  18153. BABYLON.className("Button", "BABYLON")
  18154. ], Button);
  18155. BABYLON.Button = Button;
  18156. var DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate_1 = (function (_super) {
  18157. __extends(DefaultButtonRenderingTemplate, _super);
  18158. function DefaultButtonRenderingTemplate() {
  18159. return _super.apply(this, arguments) || this;
  18160. }
  18161. DefaultButtonRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  18162. this._rect = new BABYLON.Rectangle2D({ parent: visualPlaceholder, fill: "#FF8080FF", border: "#FF8080FF", roundRadius: 10, borderThickness: 2 });
  18163. this.stateChange();
  18164. return { root: this._rect, contentPlaceholder: this._rect };
  18165. };
  18166. DefaultButtonRenderingTemplate.prototype.attach = function (owner) {
  18167. var _this = this;
  18168. _super.prototype.attach.call(this, owner);
  18169. this.owner.propertyChanged.add(function (e, s) { return _this.stateChange(); }, BABYLON.UIElement.isEnabledProperty.flagId |
  18170. BABYLON.UIElement.isFocusedProperty.flagId |
  18171. BABYLON.UIElement.isMouseOverProperty.flagId |
  18172. Button.isDefaultProperty.flagId |
  18173. Button.isOutlineProperty.flagId |
  18174. Button.isPushedProperty.flagId);
  18175. // Register for brush change and update the Visual
  18176. var button = owner;
  18177. button.normalStateBackground.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  18178. button.normalStateBorder.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  18179. button.defaultStateBackground.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  18180. button.defaultStateBorder.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  18181. };
  18182. DefaultButtonRenderingTemplate.prototype.stateChange = function () {
  18183. //console.log("state changed");
  18184. var b = this.owner;
  18185. var state = BABYLON.UIElement.enabledState;
  18186. var bg = b.isDefault ? b.defaultStateBackground.get(state) : b.normalStateBackground.get(state);
  18187. var bd = b.isDefault ? b.defaultStateBorder.get(state) : b.normalStateBorder.get(state);
  18188. if (b.isPushed) {
  18189. state = Button.pushedState;
  18190. if (b.isDefault) {
  18191. bg = b.defaultStateBackground.get(state);
  18192. bd = b.defaultStateBorder.get(state);
  18193. }
  18194. else {
  18195. bg = b.normalStateBackground.get(state);
  18196. bd = b.normalStateBorder.get(state);
  18197. }
  18198. }
  18199. else if (b.isMouseOver) {
  18200. state = BABYLON.UIElement.mouseOverState;
  18201. if (b.isDefault) {
  18202. bg = b.defaultStateBackground.get(state);
  18203. bd = b.defaultStateBorder.get(state);
  18204. }
  18205. else {
  18206. bg = b.normalStateBackground.get(state);
  18207. bd = b.normalStateBorder.get(state);
  18208. }
  18209. }
  18210. else if (!b.isEnabled) {
  18211. state = BABYLON.UIElement.disabledState;
  18212. if (b.isDefault) {
  18213. bg = b.defaultStateBackground.get(state);
  18214. bd = b.defaultStateBorder.get(state);
  18215. }
  18216. else {
  18217. bg = b.normalStateBackground.get(state);
  18218. bd = b.normalStateBorder.get(state);
  18219. }
  18220. }
  18221. this._rect.fill = bg;
  18222. this._rect.border = bd;
  18223. };
  18224. return DefaultButtonRenderingTemplate;
  18225. }(BABYLON.UIElementRenderingTemplateBase));
  18226. DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate_1 = __decorate([
  18227. BABYLON.registerWindowRenderingTemplate("BABYLON.Button", "Default", function () { return new DefaultButtonRenderingTemplate_1(); })
  18228. ], DefaultButtonRenderingTemplate);
  18229. BABYLON.DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate;
  18230. var Button_1, DefaultButtonRenderingTemplate_1;
  18231. })(BABYLON || (BABYLON = {}));