12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695 |
- BABYLON.Effect.ShadersStore['ellipse2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
- BABYLON.Effect.ShadersStore['ellipse2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt vec3 renderingInfo;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat ms=properties.z;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<ms) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=ms;\n}\nfloat angle=TWOPI*segi/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat ms=properties.z;\nfloat angle=TWOPI*(index-1.0)/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\n}\n#endif\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\nfloat x=dot(pos,transformX);\nfloat y=dot(pos,transformY);\nif (renderingInfo.z == 1.0) {\nfloat rw=renderingInfo.x;\nfloat rh=renderingInfo.y;\nfloat irw=2.0/rw;\nfloat irh=2.0/rh;\nx=(floor((x/irw)+0.5)*irw)+irw/2.0;\ny=(floor((y/irh)+0.5)*irh)+irh/2.0;\n}\ngl_Position=vec4(x,y,zBias.x,1);\n}";
- BABYLON.Effect.ShadersStore['lines2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
- BABYLON.Effect.ShadersStore['lines2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute vec2 position;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt vec3 renderingInfo;\natt float opacity;\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec2 boundingMin;\natt vec2 boundingMax;\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=position.xy;\npos.z=1.0;\npos.w=1.0;\nfloat x=dot(pos,transformX);\nfloat y=dot(pos,transformY);\nif (renderingInfo.z == 1.0) {\nfloat rw=renderingInfo.x;\nfloat rh=renderingInfo.y;\nfloat irw=2.0/rw;\nfloat irh=2.0/rh;\nx=(floor((x/irw)+0.5)*irw)+irw/2.0;\ny=(floor((y/irh)+0.5)*irh)+irh/2.0;\n}\ngl_Position=vec4(x,y,zBias.x,1);\n}";
- BABYLON.Effect.ShadersStore['rect2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
- BABYLON.Effect.ShadersStore['rect2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt vec3 renderingInfo;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n\n#define rsub0 17.0\n#define rsub1 33.0\n#define rsub2 49.0\n#define rsub3 65.0\n#define rsub 64.0\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (properties.z == 0.0) {\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<4.0) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=4.0;\n}\nif (segi == 0.0) {\npos2=vec2(1.0,1.0);\n} \nelse if (segi == 1.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (segi == 2.0) {\npos2=vec2(0.0,0.0);\n} \nelse {\npos2=vec2(0.0,1.0);\n}\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse if (index == 1.0) {\npos2=vec2(1.0,1.0);\n}\nelse if (index == 2.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (index == 3.0) {\npos2=vec2(0.0,0.0);\n}\nelse {\npos2=vec2(0.0,1.0);\n}\n#endif\n}\nelse\n{\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<rsub) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=rsub;\n}\n\nif (segi<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (segi<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (segi<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\n\nif (index<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (index<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (index<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\n}\n#endif\n}\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\nfloat x=dot(pos,transformX);\nfloat y=dot(pos,transformY);\nif (renderingInfo.z == 1.0) {\nfloat rw=renderingInfo.x;\nfloat rh=renderingInfo.y;\nfloat irw=2.0/rw;\nfloat irh=2.0/rh;\nx=(floor((x/irw)+0.5)*irw)+irw/2.0;\ny=(floor((y/irh)+0.5)*irh)+irh/2.0;\n}\ngl_Position=vec4(x,y,zBias.x,1);\n}";
- 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}";
- BABYLON.Effect.ShadersStore['sprite2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 topLeftUV;\natt vec2 sizeUV;\n#ifdef Scale9\natt vec2 scaleFactor;\n#endif\natt vec2 textureSize;\n\natt vec3 properties;\n#ifdef Scale9\natt vec4 scale9;\n#endif\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt vec3 renderingInfo;\natt float opacity;\n\n\nvarying vec2 vUV;\nvarying float vOpacity;\n#ifdef Scale9\nvarying vec2 vTopLeftUV;\nvarying vec2 vBottomRightUV;\nvarying vec4 vScale9;\nvarying vec2 vScaleFactor;\n#endif\nvoid main(void) {\nvec2 pos2;\nfloat frame=properties.x;\nfloat invertY=properties.y;\nfloat alignToPixel=properties.z;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x+(frame*sizeUV.x),topLeftUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x+(frame*sizeUV.x),(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 2.0) {\npos2=vec2( 1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 3.0) {\npos2=vec2( 1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),topLeftUV.y);\n}\nif (invertY == 1.0) {\nvUV.y=1.0-vUV.y;\n}\n\nvec4 pos;\n\n\n\n\npos.xy=pos2.xy*sizeUV*textureSize;\n\n#ifdef Scale9\nif (invertY == 1.0) {\nvTopLeftUV=vec2(topLeftUV.x,1.0-(topLeftUV.y+sizeUV.y));\nvBottomRightUV=vec2(topLeftUV.x+sizeUV.x,1.0-topLeftUV.y);\nvScale9=vec4(scale9.x,sizeUV.y-scale9.w,scale9.z,sizeUV.y-scale9.y);\n}\nelse {\nvTopLeftUV=topLeftUV;\nvBottomRightUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y+sizeUV.y);\nvScale9=scale9;\n}\nvScaleFactor=scaleFactor;\n#endif\nvOpacity=opacity;\npos.z=1.0;\npos.w=1.0;\nfloat x=dot(pos,transformX);\nfloat y=dot(pos,transformY);\nif (renderingInfo.z == 1.0) {\nfloat rw=renderingInfo.x;\nfloat rh=renderingInfo.y;\nfloat irw=2.0/rw;\nfloat irh=2.0/rh;\nx=(floor((x/irw))*irw)+irw/2.0;\ny=(floor((y/irh))*irh)+irh/2.0;\n}\ngl_Position=vec4(x,y,zBias.x,1.0);\n} ";
- BABYLON.Effect.ShadersStore['text2dPixelShader'] = "\nvarying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\n#ifdef SignedDistanceField\nfloat dist=texture2D(diffuseSampler,vUV).r;\nif (dist<0.5) {\ndiscard;\n}\n\n\n\n\n\ngl_FragColor=vec4(vColor.xyz*dist,vColor.a);\n#else\nvec4 color=texture2D(diffuseSampler,vUV);\nif (color.a == 0.0) {\ndiscard;\n}\n#ifdef FontTexture\ngl_FragColor=vec4(color.xxx*vColor.xyz*vColor.a,color.x*vColor.a);\n#else\ngl_FragColor=color*vColor;\n#endif\n#endif\n}";
- BABYLON.Effect.ShadersStore['text2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt vec3 renderingInfo;\natt float opacity;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 textureSize;\natt vec4 color;\natt float superSampleFactor;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y+sizeUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y);\n}\n\nelse if (index == 2.0) {\npos2=vec2(1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y);\n}\n\nelse if (index == 3.0) {\npos2=vec2(1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y+sizeUV.y);\n}\n\n\n\nvColor=color;\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*superSampleFactor*sizeUV*textureSize;\npos.z=1.0;\npos.w=1.0;\nfloat x=dot(pos,transformX);\nfloat y=dot(pos,transformY);\nif (renderingInfo.z == 1.0) {\nfloat rw=renderingInfo.x;\nfloat rh=renderingInfo.y;\nfloat irw=2.0/rw;\nfloat irh=2.0/rh;\nx=((floor((x/irw)+0.5)*irw)+irw/2.0)+0.5*irw;\ny=((floor((y/irh)+0.5)*irh)+irh/2.0)+0.5*irh;\n}\ngl_Position=vec4(x,y,zBias.x,1.0);\n}";
- BABYLON.Effect.ShadersStore['wireframe2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
- 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 vec3 renderingInfo;\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);\nfloat x=dot(p,transformX);\nfloat y=dot(p,transformY);\nif (renderingInfo.z == 1.0) {\nfloat rw=renderingInfo.x;\nfloat rh=renderingInfo.y;\nfloat irw=2.0/rw;\nfloat irh=2.0/rh;\nx=(floor((x/irw)+0.5)*irw)+irw/2.0;\ny=(floor((y/irh)+0.5)*irh)+irh/2.0;\n}\ngl_Position=vec4(x,y,zBias.x,1);\n}";
- var BABYLON;
- (function (BABYLON) {
- /**
- * A class storing a Matrix2D for 2D transformations
- * The stored matrix is a 3*3 Matrix2D
- * I [0,1] [mX, mY] R [ CosZ, SinZ] T [ 0, 0] S [Sx, 0]
- * D = [2,3] = [nX, nY] O = [-SinZ, CosZ] R = [ 0, 0] C = [ 0, Sy]
- * X [4,5] [tX, tY] T [ 0 , 0 ] N [Tx, Ty] L [ 0, 0]
- *
- * IDX = index, zero based. ROT = Z axis Rotation. TRN = Translation. SCL = Scale.
- */
- var Matrix2D = (function () {
- function Matrix2D() {
- this.m = new Float32Array(6);
- }
- Matrix2D.Zero = function () {
- return new Matrix2D();
- };
- Matrix2D.FromValuesToRef = function (m0, m1, m2, m3, m4, m5, result) {
- result.m[0] = m0;
- result.m[1] = m1;
- result.m[2] = m2;
- result.m[3] = m3;
- result.m[4] = m4;
- result.m[5] = m5;
- };
- Matrix2D.FromMatrix = function (source) {
- var result = new Matrix2D();
- Matrix2D.FromMatrixToRef(source, result);
- return result;
- };
- Matrix2D.FromMatrixToRef = function (source, result) {
- result.m[0] = source.m[0];
- result.m[1] = source.m[1];
- result.m[2] = source.m[4];
- result.m[3] = source.m[5];
- result.m[4] = source.m[8];
- result.m[5] = source.m[9];
- };
- Matrix2D.Rotation = function (angle) {
- var result = new Matrix2D();
- Matrix2D.RotationToRef(angle, result);
- return result;
- };
- Matrix2D.RotationToRef = function (angle, result) {
- var s = Math.sin(angle);
- var c = Math.cos(angle);
- result.m[0] = c;
- result.m[1] = s;
- result.m[2] = -s;
- result.m[3] = c;
- result.m[4] = 0;
- result.m[5] = 0;
- };
- Matrix2D.Translation = function (x, y) {
- var result = new Matrix2D();
- Matrix2D.TranslationToRef(x, y, result);
- return result;
- };
- Matrix2D.TranslationToRef = function (x, y, result) {
- result.m[0] = 1;
- result.m[1] = 0;
- result.m[2] = 0;
- result.m[3] = 1;
- result.m[4] = x;
- result.m[5] = y;
- };
- Matrix2D.Scaling = function (x, y) {
- var result = new Matrix2D();
- Matrix2D.ScalingToRef(x, y, result);
- return result;
- };
- Matrix2D.ScalingToRef = function (x, y, result) {
- result.m[0] = x;
- result.m[1] = 0;
- result.m[2] = 0;
- result.m[3] = y;
- result.m[4] = 0;
- result.m[5] = 0;
- };
- Matrix2D.Identity = function () {
- var res = new Matrix2D();
- Matrix2D.IdentityToRef(res);
- return res;
- };
- Matrix2D.IdentityToRef = function (res) {
- res.m[1] = res.m[2] = res.m[4] = res[5] = 0;
- res.m[0] = res.m[3] = 1;
- };
- Matrix2D.FromQuaternion = function (quaternion) {
- var result = new Matrix2D();
- Matrix2D.FromQuaternionToRef(quaternion, result);
- return result;
- };
- Matrix2D.FromQuaternionToRef = function (quaternion, result) {
- var xx = quaternion.x * quaternion.x;
- var yy = quaternion.y * quaternion.y;
- var zz = quaternion.z * quaternion.z;
- var xy = quaternion.x * quaternion.y;
- var zw = quaternion.z * quaternion.w;
- //var zx = quaternion.z * quaternion.x;
- //var yw = quaternion.y * quaternion.w;
- //var yz = quaternion.y * quaternion.z;
- //var xw = quaternion.x * quaternion.w;
- result.m[0] = 1.0 - (2.0 * (yy + zz));
- result.m[1] = 2.0 * (xy + zw);
- //result.m[2] = 2.0 * (zx - yw);
- //result.m[3] = 0;
- result.m[2] = 2.0 * (xy - zw);
- result.m[3] = 1.0 - (2.0 * (zz + xx));
- //result.m[6] = 2.0 * (yz + xw);
- //result.m[7] = 0;
- //result.m[8] = 2.0 * (zx + yw);
- //result.m[9] = 2.0 * (yz - xw);
- //result.m[10] = 1.0 - (2.0 * (yy + xx));
- //result.m[11] = 0;
- //result.m[12] = 0;
- //result.m[13] = 0;
- //result.m[14] = 0;
- //result.m[15] = 1.0;
- };
- Matrix2D.Compose = function (scale, rotation, translation) {
- var result = Matrix2D.Scaling(scale.x, scale.y);
- var rotationMatrix = Matrix2D.Rotation(rotation);
- result = result.multiply(rotationMatrix);
- result.setTranslation(translation);
- return result;
- };
- Matrix2D.Invert = function (source) {
- var result = new Matrix2D();
- source.invertToRef(result);
- return result;
- };
- Matrix2D.prototype.clone = function () {
- var result = new Matrix2D();
- result.copyFrom(this);
- return result;
- };
- Matrix2D.prototype.copyFrom = function (other) {
- for (var i = 0; i < 6; i++) {
- this.m[i] = other.m[i];
- }
- };
- Matrix2D.prototype.getTranslation = function () {
- return new BABYLON.Vector2(this.m[4], this.m[5]);
- };
- Matrix2D.prototype.setTranslation = function (translation) {
- this.m[4] = translation.x;
- this.m[5] = translation.y;
- };
- Matrix2D.prototype.determinant = function () {
- return this.m[0] * this.m[3] - this.m[1] * this.m[2];
- };
- Matrix2D.prototype.invertToThis = function () {
- this.invertToRef(this);
- };
- Matrix2D.prototype.invert = function () {
- var res = new Matrix2D();
- this.invertToRef(res);
- return res;
- };
- // http://mathworld.wolfram.com/MatrixInverse.html
- Matrix2D.prototype.invertToRef = function (res) {
- var l0 = this.m[0];
- var l1 = this.m[1];
- var l2 = this.m[2];
- var l3 = this.m[3];
- var l4 = this.m[4];
- var l5 = this.m[5];
- var det = this.determinant();
- if (det < (BABYLON.Epsilon * BABYLON.Epsilon)) {
- throw new Error("Can't invert matrix, near null determinant");
- }
- var detDiv = 1 / det;
- var det4 = l2 * l5 - l3 * l4;
- var det5 = l1 * l4 - l0 * l5;
- res.m[0] = l3 * detDiv;
- res.m[1] = -l1 * detDiv;
- res.m[2] = -l2 * detDiv;
- res.m[3] = l0 * detDiv;
- res.m[4] = det4 * detDiv;
- res.m[5] = det5 * detDiv;
- };
- Matrix2D.prototype.multiplyToThis = function (other) {
- this.multiplyToRef(other, this);
- };
- Matrix2D.prototype.multiply = function (other) {
- var res = new Matrix2D();
- this.multiplyToRef(other, res);
- return res;
- };
- Matrix2D.prototype.multiplyToRef = function (other, result) {
- var l0 = this.m[0];
- var l1 = this.m[1];
- var l2 = this.m[2];
- var l3 = this.m[3];
- var l4 = this.m[4];
- var l5 = this.m[5];
- var r0 = other.m[0];
- var r1 = other.m[1];
- var r2 = other.m[2];
- var r3 = other.m[3];
- var r4 = other.m[4];
- var r5 = other.m[5];
- result.m[0] = l0 * r0 + l1 * r2;
- result.m[1] = l0 * r1 + l1 * r3;
- result.m[2] = l2 * r0 + l3 * r2;
- result.m[3] = l2 * r1 + l3 * r3;
- result.m[4] = l4 * r0 + l5 * r2 + r4;
- result.m[5] = l4 * r1 + l5 * r3 + r5;
- };
- Matrix2D.prototype.transformFloats = function (x, y) {
- var res = BABYLON.Vector2.Zero();
- this.transformFloatsToRef(x, y, res);
- return res;
- };
- Matrix2D.prototype.transformFloatsToRef = function (x, y, r) {
- r.x = x * this.m[0] + y * this.m[2] + this.m[4];
- r.y = x * this.m[1] + y * this.m[3] + this.m[5];
- };
- Matrix2D.prototype.transformPoint = function (p) {
- var res = BABYLON.Vector2.Zero();
- this.transformFloatsToRef(p.x, p.y, res);
- return res;
- };
- Matrix2D.prototype.transformPointToRef = function (p, r) {
- this.transformFloatsToRef(p.x, p.y, r);
- };
- Matrix2D.prototype.decompose = function (scale, translation) {
- translation.x = this.m[4];
- translation.y = this.m[5];
- scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1]);
- scale.y = Math.sqrt(this.m[2] * this.m[2] + this.m[3] * this.m[3]);
- if (scale.x === 0 || scale.y === 0) {
- return null;
- }
- return Math.atan2(-this.m[2] / scale.y, this.m[0] / scale.x);
- };
- return Matrix2D;
- }());
- Matrix2D._decomp = new Matrix2D();
- BABYLON.Matrix2D = Matrix2D;
- /**
- * Stores information about a 2D Triangle.
- * This class stores the 3 vertices but also the center and radius of the triangle
- */
- var Tri2DInfo = (function () {
- /**
- * 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
- */
- function Tri2DInfo(a, b, c) {
- if (a === null && b === null && c === null) {
- this.a = BABYLON.Vector2.Zero();
- this.b = BABYLON.Vector2.Zero();
- this.c = BABYLON.Vector2.Zero();
- this.center = BABYLON.Vector2.Zero();
- this.radius = 0;
- return;
- }
- this.a = a.clone();
- this.b = b.clone();
- this.c = c.clone();
- this._updateCenterRadius();
- }
- Tri2DInfo.Zero = function () {
- return new Tri2DInfo(null, null, null);
- };
- Tri2DInfo.prototype.set = function (a, b, c) {
- this.a.copyFrom(a);
- this.b.copyFrom(b);
- this.c.copyFrom(c);
- this._updateCenterRadius();
- };
- Tri2DInfo.prototype.transformInPlace = function (transform) {
- transform.transformPointToRef(this.a, this.a);
- transform.transformPointToRef(this.b, this.b);
- transform.transformPointToRef(this.c, this.c);
- //Vector2.TransformToRef(this.a, transform, this.a);
- //Vector2.TransformToRef(this.b, transform, this.b);
- //Vector2.TransformToRef(this.c, transform, this.c);
- this._updateCenterRadius();
- };
- Tri2DInfo.prototype.doesContain = function (p) {
- return BABYLON.Vector2.PointInTriangle(p, this.a, this.b, this.c);
- };
- Tri2DInfo.prototype._updateCenterRadius = function () {
- this.center.x = (this.a.x + this.b.x + this.c.x) / 3;
- this.center.y = (this.a.y + this.b.y + this.c.y) / 3;
- var la = BABYLON.Vector2.DistanceSquared(this.a, this.center);
- var lb = BABYLON.Vector2.DistanceSquared(this.b, this.center);
- var lc = BABYLON.Vector2.DistanceSquared(this.c, this.center);
- var rs = Math.max(Math.max(la, lb), lc);
- this.radius = Math.sqrt(rs);
- };
- return Tri2DInfo;
- }());
- BABYLON.Tri2DInfo = Tri2DInfo;
- /**
- * Stores an array of 2D Triangles.
- * Internally the data is stored as a Float32Array to minimize the memory footprint.
- * This can use the Tri2DInfo class as proxy for storing/retrieving data.
- * The array can't grow, it's fixed size.
- */
- var Tri2DArray = (function () {
- function Tri2DArray(count) {
- this._count = count;
- this._array = new Float32Array(9 * count);
- }
- /**
- * Clear the content and allocate a new array to store the given count of triangles
- * @param count The new count of triangles to store
- */
- Tri2DArray.prototype.clear = function (count) {
- if (this._count === count) {
- return;
- }
- this._count = count;
- this._array = new Float32Array(9 * count);
- };
- /**
- * Store a given triangle at the given index
- * @param index the 0 based index to store the triangle in the array
- * @param a the A vertex of the triangle
- * @param b the B vertex of the triangle
- * @param c the C vertex of the triangle
- */
- Tri2DArray.prototype.storeTriangle = function (index, a, b, c) {
- var center = new BABYLON.Vector2((a.x + b.x + c.x) / 3, (a.y + b.y + c.y) / 3);
- var la = BABYLON.Vector2.DistanceSquared(a, center);
- var lb = BABYLON.Vector2.DistanceSquared(b, center);
- var lc = BABYLON.Vector2.DistanceSquared(c, center);
- var rs = Math.max(Math.max(la, lb), lc);
- var radius = Math.sqrt(rs);
- var offset = index * 9;
- this._array[offset + 0] = a.x;
- this._array[offset + 1] = a.y;
- this._array[offset + 2] = b.x;
- this._array[offset + 3] = b.y;
- this._array[offset + 4] = c.x;
- this._array[offset + 5] = c.y;
- this._array[offset + 6] = center.x;
- this._array[offset + 7] = center.y;
- this._array[offset + 8] = radius;
- };
- /**
- * Store a triangle in a Tri2DInfo object
- * @param index the index of the triangle to store
- * @param tri2dInfo the instance that will contain the data, it must be already allocated with its inner object also allocated
- */
- Tri2DArray.prototype.storeToTri2DInfo = function (index, tri2dInfo) {
- if (index >= this._count) {
- throw new Error("Can't fetch the triangle at index " + index + ", max index is " + (this._count - 1));
- }
- var offset = index * 9;
- tri2dInfo.a.x = this._array[offset + 0];
- tri2dInfo.a.y = this._array[offset + 1];
- tri2dInfo.b.x = this._array[offset + 2];
- tri2dInfo.b.y = this._array[offset + 3];
- tri2dInfo.c.x = this._array[offset + 4];
- tri2dInfo.c.y = this._array[offset + 5];
- tri2dInfo.center.x = this._array[offset + 6];
- tri2dInfo.center.y = this._array[offset + 7];
- tri2dInfo.radius = this._array[offset + 8];
- };
- /**
- * Transform the given triangle and store its result in the array
- * @param index The index to store the result to
- * @param tri2dInfo The triangle to transform
- * @param transform The transformation matrix
- */
- Tri2DArray.prototype.transformAndStoreToTri2DInfo = function (index, tri2dInfo, transform) {
- if (index >= this._count) {
- throw new Error("Can't fetch the triangle at index " + index + ", max index is " + (this._count - 1));
- }
- var offset = index * 9;
- tri2dInfo.a.x = this._array[offset + 0];
- tri2dInfo.a.y = this._array[offset + 1];
- tri2dInfo.b.x = this._array[offset + 2];
- tri2dInfo.b.y = this._array[offset + 3];
- tri2dInfo.c.x = this._array[offset + 4];
- tri2dInfo.c.y = this._array[offset + 5];
- tri2dInfo.transformInPlace(transform);
- };
- Object.defineProperty(Tri2DArray.prototype, "count", {
- /**
- * Get the element count that can be stored in this array
- * @returns {}
- */
- get: function () {
- return this._count;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Check if a given point intersects with at least one of the triangles stored in the array.
- * If true is returned the point is intersecting with at least one triangle, false if it doesn't intersect with any of them
- * @param p The point to check
- */
- Tri2DArray.prototype.doesContain = function (p) {
- Tri2DArray._checkInitStatics();
- var a = Tri2DArray.tempT[0];
- for (var i = 0; i < this.count; i++) {
- this.storeToTri2DInfo(i, a);
- if (a.doesContain(p)) {
- return true;
- }
- }
- return false;
- };
- /**
- * Make a intersection test between two sets of triangles. The triangles of setB will be transformed to the frame of reference of the setA using the given bToATransform matrix.
- * If true is returned at least one triangle intersects with another of the other set, otherwise false is returned.
- * @param setA The first set of triangles
- * @param setB The second set of triangles
- * @param bToATransform The transformation matrix to transform the setB triangles into the frame of reference of the setA
- */
- Tri2DArray.doesIntersect = function (setA, setB, bToATransform) {
- Tri2DArray._checkInitStatics();
- var a = Tri2DArray.tempT[0];
- var b = Tri2DArray.tempT[1];
- var v0 = Tri2DArray.tempV[0];
- for (var curB = 0; curB < setB.count; curB++) {
- setB.transformAndStoreToTri2DInfo(curB, b, bToATransform);
- for (var curA = 0; curA < setA.count; curA++) {
- setA.storeToTri2DInfo(curA, a);
- // Fast rejection first
- v0.x = a.center.x - b.center.x;
- v0.y = a.center.y - b.center.y;
- if (v0.lengthSquared() > ((a.radius * a.radius) + (b.radius * b.radius))) {
- continue;
- }
- // Actual intersection test
- if (Math2D.TriangleTriangleDosIntersect(a.a, a.b, a.c, b.a, b.b, b.c)) {
- return true;
- }
- }
- }
- return false;
- };
- Tri2DArray._checkInitStatics = function () {
- if (Tri2DArray.tempT !== null) {
- return;
- }
- Tri2DArray.tempT = new Array(2);
- Tri2DArray.tempT[0] = new Tri2DInfo(null, null, null);
- Tri2DArray.tempT[1] = new Tri2DInfo(null, null, null);
- Tri2DArray.tempV = new Array(6);
- for (var i = 0; i < 6; i++) {
- Tri2DArray.tempV[i] = BABYLON.Vector2.Zero();
- }
- };
- return Tri2DArray;
- }());
- Tri2DArray.tempV = null;
- Tri2DArray.tempT = null;
- BABYLON.Tri2DArray = Tri2DArray;
- /**
- * Some 2D Math helpers functions
- */
- var Math2D = (function () {
- function Math2D() {
- }
- Math2D.Dot = function (a, b) {
- return a.x * b.x + a.y * b.y;
- };
- // From http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
- // 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/
- Math2D.LineLineDoesIntersect = function (segA1, segA2, segB1, segB2) {
- var s1_x = segA2.x - segA1.x;
- var s1_y = segA2.y - segA1.y;
- var s2_x = segB2.x - segB1.x;
- var s2_y = segB2.y - segB1.y;
- var s = (-s1_y * (segA1.x - segB1.x) + s1_x * (segA1.y - segB1.y)) / (-s2_x * s1_y + s1_x * s2_y);
- var t = (s2_x * (segA1.y - segB1.y) - s2_y * (segA1.x - segB1.x)) / (-s2_x * s1_y + s1_x * s2_y);
- if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
- return true;
- }
- return false;
- };
- // From http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
- Math2D.LineLineIntersection = function (p0, p1, p2, p3) {
- var s1_x = p1.x - p0.x;
- var s1_y = p1.y - p0.y;
- var s2_x = p3.x - p2.x;
- var s2_y = p3.y - p2.y;
- var s = (-s1_y * (p0.x - p2.x) + s1_x * (p0.y - p2.y)) / (-s2_x * s1_y + s1_x * s2_y);
- var t = (s2_x * (p0.y - p2.y) - s2_y * (p0.x - p2.x)) / (-s2_x * s1_y + s1_x * s2_y);
- if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
- return { res: true, xr: p0.x + (t * s1_x), yr: p0.y + (t * s1_y) };
- }
- return { res: false, xr: 0, yr: 0 };
- };
- // Tell me that it's slow and I'll answer: yes it is!
- // If you fancy to implement the SAT (Separating Axis Theorem) version: BE MY VERY WELCOMED GUEST!
- Math2D.TriangleTriangleDosIntersect = function (tri1A, tri1B, tri1C, tri2A, tri2B, tri2C) {
- if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2A, tri2B))
- return true;
- if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2A, tri2C))
- return true;
- if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2B, tri2C))
- return true;
- if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2A, tri2B))
- return true;
- if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2A, tri2C))
- return true;
- if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2B, tri2C))
- return true;
- if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2A, tri2B))
- return true;
- if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2A, tri2C))
- return true;
- if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2B, tri2C))
- return true;
- if (BABYLON.Vector2.PointInTriangle(tri2A, tri1A, tri1B, tri1C) &&
- BABYLON.Vector2.PointInTriangle(tri2B, tri1A, tri1B, tri1C) &&
- BABYLON.Vector2.PointInTriangle(tri2C, tri1A, tri1B, tri1C))
- return true;
- if (BABYLON.Vector2.PointInTriangle(tri1A, tri2A, tri2B, tri2C) &&
- BABYLON.Vector2.PointInTriangle(tri1B, tri2A, tri2B, tri2C) &&
- BABYLON.Vector2.PointInTriangle(tri1C, tri2A, tri2B, tri2C))
- return true;
- return false;
- };
- return Math2D;
- }());
- Math2D.v0 = BABYLON.Vector2.Zero();
- Math2D.v1 = BABYLON.Vector2.Zero();
- Math2D.v2 = BABYLON.Vector2.Zero();
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.math2D.js.map
- var BABYLON;
- (function (BABYLON) {
- var PropertyChangedInfo = (function () {
- function PropertyChangedInfo() {
- }
- return PropertyChangedInfo;
- }());
- BABYLON.PropertyChangedInfo = PropertyChangedInfo;
- /**
- * The purpose of this class is to provide a base implementation of the IPropertyChanged interface for the user to avoid rewriting a code needlessly.
- * 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.
- * 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)
- */
- var PropertyChangedBase = (function () {
- function PropertyChangedBase() {
- this._propertyChanged = null;
- }
- /**
- * Protected method to call when there's a change of value in a property set
- * @param propName the name of the concerned property
- * @param oldValue its old value
- * @param newValue its new value
- * @param mask an optional observable mask
- */
- PropertyChangedBase.prototype.onPropertyChanged = function (propName, oldValue, newValue, mask) {
- if (this.propertyChanged.hasObservers()) {
- var pci = PropertyChangedBase.calling ? new PropertyChangedInfo() : PropertyChangedBase.pci;
- pci.oldValue = oldValue;
- pci.newValue = newValue;
- pci.propertyName = propName;
- try {
- PropertyChangedBase.calling = true;
- this.propertyChanged.notifyObservers(pci, mask);
- }
- finally {
- PropertyChangedBase.calling = false;
- }
- }
- };
- Object.defineProperty(PropertyChangedBase.prototype, "propertyChanged", {
- /**
- * An observable that is triggered when a property (using of the XXXXLevelProperty decorator) has its value changing.
- * 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)
- */
- get: function () {
- if (!this._propertyChanged) {
- this._propertyChanged = new BABYLON.Observable();
- }
- return this._propertyChanged;
- },
- enumerable: true,
- configurable: true
- });
- return PropertyChangedBase;
- }());
- PropertyChangedBase.pci = new PropertyChangedInfo();
- PropertyChangedBase.calling = false;
- BABYLON.PropertyChangedBase = PropertyChangedBase;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.IPropertyChanged.js.map
- var BABYLON;
- (function (BABYLON) {
- // logging stuffs
- var C2DLogging = (function () {
- function C2DLogging() {
- }
- C2DLogging.logFrameRender = function (frameCount) {
- C2DLogging.snooze = true;
- C2DLogging._logFramesCount = frameCount;
- };
- C2DLogging.setPostMessage = function (message) {
- if (C2DLoggingInternals.enableLog) {
- C2DLoggingInternals.postMessages[C2DLoggingInternals.callDepth - 1] = message();
- }
- };
- C2DLogging._startFrameRender = function () {
- if (C2DLogging._logFramesCount === 0) {
- return;
- }
- C2DLogging.snooze = false;
- };
- C2DLogging._endFrameRender = function () {
- if (C2DLogging._logFramesCount === 0) {
- return;
- }
- C2DLogging.snooze = true;
- --C2DLogging._logFramesCount;
- };
- return C2DLogging;
- }());
- // Set to true to temporary disable logging.
- C2DLogging.snooze = true;
- C2DLogging._logFramesCount = 0;
- BABYLON.C2DLogging = C2DLogging;
- var C2DLoggingInternals = (function () {
- function C2DLoggingInternals() {
- }
- C2DLoggingInternals.computeIndent = function () {
- // Compute the indent
- var indent = null;
- if (C2DLoggingInternals.callDepth < 20) {
- indent = C2DLoggingInternals.depths[C2DLoggingInternals.callDepth];
- }
- else {
- indent = "|";
- for (var i = 0; i <= C2DLoggingInternals.callDepth; i++) {
- indent = indent + "-";
- }
- }
- return indent;
- };
- C2DLoggingInternals.getFormattedValue = function (a) {
- if (a instanceof BABYLON.Prim2DBase) {
- return a.id;
- }
- if (a == null) {
- return "[null]";
- }
- return a.toString();
- };
- return C2DLoggingInternals;
- }());
- //-------------FLAG TO CHANGE TO ENABLE/DISABLE LOGGING ACTIVATION--------------
- // This flag can't be changed at runtime you must manually change it in the code
- C2DLoggingInternals.enableLog = false;
- C2DLoggingInternals.callDepth = 0;
- C2DLoggingInternals.depths = [
- "|-", "|--", "|---", "|----", "|-----", "|------", "|-------", "|--------", "|---------", "|----------",
- "|-----------", "|------------", "|-------------", "|--------------", "|---------------", "|----------------", "|-----------------", "|------------------", "|-------------------", "|--------------------"
- ];
- C2DLoggingInternals.postMessages = [];
- function logProp(message, alsoGet, setNoProlog, getNoProlog) {
- if (message === void 0) { message = ""; }
- if (alsoGet === void 0) { alsoGet = false; }
- if (setNoProlog === void 0) { setNoProlog = false; }
- if (getNoProlog === void 0) { getNoProlog = false; }
- return function (target, propName, descriptor) {
- if (!C2DLoggingInternals.enableLog) {
- return descriptor;
- }
- var getter = descriptor.get, setter = descriptor.set;
- if (getter && alsoGet) {
- descriptor.get = function () {
- if (C2DLogging.snooze) {
- return getter.call(this);
- }
- else {
- var indent = C2DLoggingInternals.computeIndent();
- var id = this.id || "";
- if (message !== null && message !== "") {
- console.log(message);
- }
- var isSPP = this instanceof BABYLON.SmartPropertyPrim;
- var flags = isSPP ? this._flags : 0;
- var depth = C2DLoggingInternals.callDepth;
- if (!getNoProlog) {
- console.log(indent + " [" + id + "] (" + depth + ") ==> get " + propName + " property");
- }
- ++C2DLoggingInternals.callDepth;
- C2DLogging.setPostMessage(function () { return "[no msg]"; });
- // Call the initial getter
- var r = getter.call(this);
- --C2DLoggingInternals.callDepth;
- var flagsStr = "";
- if (isSPP) {
- var nflags = this._flags;
- var newFlags = this._getFlagsDebug((nflags & flags) ^ nflags);
- var removedFlags = this._getFlagsDebug((nflags & flags) ^ flags);
- flagsStr = "";
- if (newFlags !== "") {
- flagsStr = " +++[" + newFlags + "]";
- }
- if (removedFlags !== "") {
- if (flagsStr !== "") {
- flagsStr += ",";
- }
- flagsStr += " ---[" + removedFlags + "]";
- }
- }
- console.log(indent + " [" + id + "] (" + depth + ")" + (getNoProlog ? "" : " <==") + " get " + propName + " property => " + C2DLoggingInternals.getFormattedValue(r) + flagsStr + ", " + C2DLoggingInternals.postMessages[C2DLoggingInternals.callDepth]);
- return r;
- }
- };
- }
- // Overload the property setter implementation to add our own logic
- if (setter) {
- descriptor.set = function (val) {
- if (C2DLogging.snooze) {
- setter.call(this, val);
- }
- else {
- var indent = C2DLoggingInternals.computeIndent();
- var id = this.id || "";
- if (message !== null && message !== "") {
- console.log(message);
- }
- var isSPP = this instanceof BABYLON.SmartPropertyPrim;
- var flags = isSPP ? this._flags : 0;
- var depth = C2DLoggingInternals.callDepth;
- if (!setNoProlog) {
- console.log(indent + " [" + id + "] (" + depth + ") ==> set " + propName + " property with " + C2DLoggingInternals.getFormattedValue(val));
- }
- ++C2DLoggingInternals.callDepth;
- C2DLogging.setPostMessage(function () { return "[no msg]"; });
- // Change the value
- setter.call(this, val);
- --C2DLoggingInternals.callDepth;
- var flagsStr = "";
- if (isSPP) {
- var nflags = this._flags;
- var newFlags = this._getFlagsDebug((nflags & flags) ^ nflags);
- var removedFlags = this._getFlagsDebug((nflags & flags) ^ flags);
- flagsStr = "";
- if (newFlags !== "") {
- flagsStr = " +++[" + newFlags + "]";
- }
- if (removedFlags !== "") {
- if (flagsStr !== "") {
- flagsStr += ",";
- }
- flagsStr += " ---[" + removedFlags + "]";
- }
- }
- console.log(indent + " [" + id + "] (" + depth + ")" + (setNoProlog ? "" : " <==") + " set " + propName + " property, " + C2DLoggingInternals.postMessages[C2DLoggingInternals.callDepth] + flagsStr);
- }
- };
- }
- return descriptor;
- };
- }
- BABYLON.logProp = logProp;
- function logMethod(message, noProlog) {
- if (message === void 0) { message = ""; }
- if (noProlog === void 0) { noProlog = false; }
- return function (target, key, descriptor) {
- if (!C2DLoggingInternals.enableLog) {
- return descriptor;
- }
- if (descriptor === undefined) {
- descriptor = Object.getOwnPropertyDescriptor(target, key);
- }
- var originalMethod = descriptor.value;
- //editing the descriptor/value parameter
- descriptor.value = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i - 0] = arguments[_i];
- }
- if (C2DLogging.snooze) {
- return originalMethod.apply(this, args);
- }
- else {
- var a = args.map(function (a) { return C2DLoggingInternals.getFormattedValue(a) + ", "; }).join();
- a = a.slice(0, a.length - 2);
- var indent = C2DLoggingInternals.computeIndent();
- var id = this.id || "";
- if (message !== null && message !== "") {
- console.log(message);
- }
- var isSPP = this instanceof BABYLON.SmartPropertyPrim;
- var flags = isSPP ? this._flags : 0;
- var depth = C2DLoggingInternals.callDepth;
- if (!noProlog) {
- console.log(indent + " [" + id + "] (" + depth + ") ==> call: " + key + " (" + a + ")");
- }
- ++C2DLoggingInternals.callDepth;
- C2DLogging.setPostMessage(function () { return "[no msg]"; });
- // Call the method!
- var result = originalMethod.apply(this, args);
- --C2DLoggingInternals.callDepth;
- var flagsStr = "";
- if (isSPP) {
- var nflags = this._flags;
- var newFlags = this._getFlagsDebug((nflags & flags) ^ nflags);
- var removedFlags = this._getFlagsDebug((nflags & flags) ^ flags);
- flagsStr = "";
- if (newFlags !== "") {
- flagsStr = " +++[" + newFlags + "]";
- }
- if (removedFlags !== "") {
- if (flagsStr !== "") {
- flagsStr += ",";
- }
- flagsStr += " ---[" + removedFlags + "]";
- }
- }
- console.log(indent + " [" + id + "] (" + depth + ")" + (noProlog ? "" : " <==") + " call: " + key + " (" + a + ") Res: " + C2DLoggingInternals.getFormattedValue(result) + ", " + C2DLoggingInternals.postMessages[C2DLoggingInternals.callDepth] + flagsStr);
- return result;
- }
- };
- // return edited descriptor as opposed to overwriting the descriptor
- return descriptor;
- };
- }
- BABYLON.logMethod = logMethod;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.c2dlogging.js.map
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var BABYLON;
- (function (BABYLON) {
- /**
- * Class for the ObservableArray.onArrayChanged observable
- */
- var ArrayChanged = (function () {
- function ArrayChanged() {
- this.action = 0;
- this.newItems = new Array();
- this.removedItems = new Array();
- this.changedItems = new Array();
- this.newStartingIndex = -1;
- this.removedStartingIndex = -1;
- }
- Object.defineProperty(ArrayChanged, "clearAction", {
- /**
- * The content of the array was totally cleared
- */
- get: function () {
- return ArrayChanged._clearAction;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ArrayChanged, "newItemsAction", {
- /**
- * A new item was added, the newItems field contains the key/value pairs
- */
- get: function () {
- return ArrayChanged._newItemsAction;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ArrayChanged, "removedItemsAction", {
- /**
- * An existing item was removed, the removedKey field contains its key
- */
- get: function () {
- return ArrayChanged._removedItemsAction;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ArrayChanged, "changedItemAction", {
- /**
- * One or many items in the array were changed, the
- */
- get: function () {
- return ArrayChanged._changedItemAction;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ArrayChanged, "replacedArrayAction", {
- /**
- * The array's content was totally changed
- * Depending on the method that used this mode the ChangedArray object may contains more information
- */
- get: function () {
- return ArrayChanged._replacedArrayAction;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ArrayChanged, "lengthChangedAction", {
- /**
- * The length of the array changed
- */
- get: function () {
- return ArrayChanged._lengthChangedAction;
- },
- enumerable: true,
- configurable: true
- });
- ArrayChanged.prototype.clear = function () {
- this.action = 0;
- this.newItems.splice(0);
- this.removedItems.splice(0);
- this.changedItems.splice(0);
- this.removedStartingIndex = this.removedStartingIndex = this.changedStartingIndex = 0;
- };
- return ArrayChanged;
- }());
- ArrayChanged._clearAction = 0x1;
- ArrayChanged._newItemsAction = 0x2;
- ArrayChanged._removedItemsAction = 0x4;
- ArrayChanged._replacedArrayAction = 0x8;
- ArrayChanged._lengthChangedAction = 0x10;
- ArrayChanged._changedItemAction = 0x20;
- BABYLON.ArrayChanged = ArrayChanged;
- var OAWatchedObjectChangedInfo = (function () {
- function OAWatchedObjectChangedInfo() {
- }
- return OAWatchedObjectChangedInfo;
- }());
- BABYLON.OAWatchedObjectChangedInfo = OAWatchedObjectChangedInfo;
- /**
- * This class mimics the Javascript Array and TypeScript Array<T> classes, adding new features concerning the Observable pattern.
- *
- */
- var ObservableArray = (function (_super) {
- __extends(ObservableArray, _super);
- /**
- * Create an Observable Array.
- * @param watchObjectsPropertyChange
- * @param array and optional array that will be encapsulated by this ObservableArray instance. That's right, it's NOT a copy!
- */
- function ObservableArray(watchObjectsPropertyChange, array) {
- var _this = _super.call(this) || this;
- _this.dci = new ArrayChanged();
- _this._callingArrayChanged = false;
- _this._array = (array != null) ? array : new Array();
- _this.dci = new ArrayChanged();
- _this._callingArrayChanged = false;
- _this._arrayChanged = null;
- _this._callingWatchedObjectChanged = false;
- _this._watchObjectsPropertyChange = watchObjectsPropertyChange;
- _this._watchedObjectList = _this._watchObjectsPropertyChange ? new BABYLON.StringDictionary() : null;
- _this._woci = new OAWatchedObjectChangedInfo();
- return _this;
- }
- Object.defineProperty(ObservableArray.prototype, "length", {
- /**
- * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.
- */
- get: function () {
- return this._array.length;
- },
- set: function (value) {
- if (value === this._array.length) {
- return;
- }
- var oldLength = this._array.length;
- this._array.length = value;
- this.onPropertyChanged("length", oldLength, this._array.length);
- },
- enumerable: true,
- configurable: true
- });
- ObservableArray.prototype.getAt = function (index) {
- return this._array[index];
- };
- ObservableArray.prototype.setAt = function (index, value) {
- if (index < 0) {
- return false;
- }
- var insertion = (index >= this._array.length) || this._array[index] === undefined;
- var oldLength = 0;
- if (insertion) {
- oldLength = this._array.length;
- }
- else if (this._watchObjectsPropertyChange) {
- this._removeWatchedElement(this._array[index]);
- }
- this._array[index] = value;
- if (this._watchObjectsPropertyChange) {
- this._addWatchedElement(value);
- }
- if (insertion) {
- this.onPropertyChanged("length", oldLength, this._array.length);
- }
- var ac = this.getArrayChangedObject();
- if (ac) {
- ac.action = insertion ? ArrayChanged.newItemsAction : ArrayChanged.changedItemAction;
- if (insertion) {
- ac.newItems.splice(0, ac.newItems.length, { index: index, value: value });
- ac.newStartingIndex = index;
- ac.changedItems.splice(0);
- }
- else {
- ac.newItems.splice(0);
- ac.changedStartingIndex = index;
- ac.changedItems.splice(0, ac.changedItems.length, { index: index, value: value });
- }
- ac.removedItems.splice(0);
- ac.removedStartingIndex = -1;
- this.callArrayChanged(ac);
- }
- };
- /**
- * Returns a string representation of an array.
- */
- ObservableArray.prototype.toString = function () {
- return this._array.toString();
- };
- ObservableArray.prototype.toLocaleString = function () {
- return this._array.toLocaleString();
- };
- /**
- * Appends new elements to an array, and returns the new length of the array.
- * @param items New elements of the Array.
- */
- ObservableArray.prototype.push = function () {
- var items = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- items[_i] = arguments[_i];
- }
- var oldLength = this._array.length;
- var n = (_a = this._array).push.apply(_a, items);
- if (this._watchObjectsPropertyChange) {
- this._addWatchedElement.apply(this, items);
- }
- this.onPropertyChanged("length", oldLength, this._array.length);
- var ac = this.getArrayChangedObject();
- if (ac) {
- ac.action = ArrayChanged.newItemsAction;
- ac.newStartingIndex = oldLength;
- this.feedNotifArray.apply(this, [ac.newItems, oldLength].concat(items));
- this.callArrayChanged(ac);
- }
- return n;
- var _a;
- };
- /**
- * Removes the last element from an array and returns it.
- */
- ObservableArray.prototype.pop = function () {
- var firstRemove = this._array.length - 1;
- var res = this._array.pop();
- if (res && this._watchObjectsPropertyChange) {
- this._removeWatchedElement(res);
- }
- if (firstRemove !== -1) {
- this.onPropertyChanged("length", this._array.length + 1, this._array.length);
- var ac = this.getArrayChangedObject();
- if (ac) {
- ac.action = ArrayChanged.removedItemsAction;
- ac.removedStartingIndex = firstRemove;
- this.feedNotifArray(ac.removedItems, firstRemove, res);
- }
- }
- return res;
- };
- /**
- * Combines two or more arrays.
- * @param items Additional items to add to the end of array1.
- */
- ObservableArray.prototype.concat = function () {
- var items = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- items[_i] = arguments[_i];
- }
- return new ObservableArray(this._watchObjectsPropertyChange, (_a = this._array).concat.apply(_a, items));
- var _a;
- };
- /**
- * Adds all the elements of an array separated by the specified separator string.
- * @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.
- */
- ObservableArray.prototype.join = function (separator) {
- return this._array.join(separator);
- };
- /**
- * Reverses the elements in an Array.
- * The arrayChanged action is
- */
- ObservableArray.prototype.reverse = function () {
- var res = this._array.reverse();
- var ac = this.getArrayChangedObject();
- ac.action = ArrayChanged.replacedArrayAction;
- return res;
- };
- /**
- * Removes the first element from an array and returns it, shift all subsequents element one element before.
- * The ArrayChange action is replacedArrayAction, the whole array changes and must be reevaluate as such, the removed element is in removedItems.
- *
- */
- ObservableArray.prototype.shift = function () {
- var oldLength = this._array.length;
- var res = this._array.shift();
- if (this._watchedObjectChanged && res != null) {
- this._removeWatchedElement(res);
- }
- if (oldLength !== 0) {
- this.onPropertyChanged("length", oldLength, this._array.length);
- var ac = this.getArrayChangedObject();
- if (ac) {
- ac.action = ArrayChanged.replacedArrayAction;
- ac.removedItems.splice(0, ac.removedItems.length, { index: 0, value: res });
- ac.newItems.splice(0);
- ac.changedItems.splice(0);
- ac.removedStartingIndex = 0;
- this.callArrayChanged(ac);
- }
- }
- return res;
- };
- /**
- * Returns a section of an array.
- * @param start The beginning of the specified portion of the array.
- * @param end The end of the specified portion of the array.
- */
- ObservableArray.prototype.slice = function (start, end) {
- return new ObservableArray(this._watchObjectsPropertyChange, this._array.slice(start, end));
- };
- /**
- * Sorts an array.
- * @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.
- * On the contrary of the Javascript Array's implementation, this method returns nothing
- */
- ObservableArray.prototype.sort = function (compareFn) {
- var oldLength = this._array.length;
- this._array.sort(compareFn);
- if (oldLength !== 0) {
- var ac = this.getArrayChangedObject();
- if (ac) {
- ac.clear();
- ac.action = ArrayChanged.replacedArrayAction;
- this.callArrayChanged(ac);
- }
- }
- };
- /**
- * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
- * @param start The zero-based location in the array from which to start removing elements.
- * @param deleteCount The number of elements to remove.
- * @param items Elements to insert into the array in place of the deleted elements.
- */
- ObservableArray.prototype.splice = function (start, deleteCount) {
- var items = [];
- for (var _i = 2; _i < arguments.length; _i++) {
- items[_i - 2] = arguments[_i];
- }
- var oldLength = this._array.length;
- if (this._watchObjectsPropertyChange) {
- for (var i = start; i < start + deleteCount; i++) {
- var val = this._array[i];
- if (this._watchObjectsPropertyChange && val != null) {
- this._removeWatchedElement(val);
- }
- }
- }
- var res = (_a = this._array).splice.apply(_a, [start, deleteCount].concat(items));
- if (this._watchObjectsPropertyChange) {
- this._addWatchedElement.apply(this, items);
- }
- if (oldLength !== this._array.length) {
- this.onPropertyChanged("length", oldLength, this._array.length);
- }
- var ac = this.getArrayChangedObject();
- if (ac) {
- ac.clear();
- ac.action = ArrayChanged.replacedArrayAction;
- this.callArrayChanged(ac);
- }
- return res;
- var _a;
- };
- /**
- * Inserts new elements at the start of an array.
- * @param items Elements to insert at the start of the Array.
- * The ChangedArray action is replacedArrayAction, newItems contains the list of the added items
- */
- ObservableArray.prototype.unshift = function () {
- var items = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- items[_i] = arguments[_i];
- }
- var oldLength = this._array.length;
- var res = (_a = this._array).unshift.apply(_a, items);
- if (this._watchObjectsPropertyChange) {
- this._addWatchedElement.apply(this, items);
- }
- this.onPropertyChanged("length", oldLength, this._array.length);
- var ac = this.getArrayChangedObject();
- if (ac) {
- ac.clear();
- ac.action = ArrayChanged.replacedArrayAction;
- ac.newStartingIndex = 0, this.feedNotifArray.apply(this, [ac.newItems, 0].concat(items));
- this.callArrayChanged(ac);
- }
- return res;
- var _a;
- };
- /**
- * Returns the index of the first occurrence of a value in an array.
- * @param searchElement The value to locate in the array.
- * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
- */
- ObservableArray.prototype.indexOf = function (searchElement, fromIndex) {
- return this._array.indexOf(searchElement, fromIndex);
- };
- /**
- * Returns the index of the last occurrence of a specified value in an array.
- * @param searchElement The value to locate in the array.
- * @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.
- */
- ObservableArray.prototype.lastIndexOf = function (searchElement, fromIndex) {
- return this._array.lastIndexOf(searchElement, fromIndex);
- };
- /**
- * Determines whether all the members of an array satisfy the specified test.
- * @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.
- * @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.
- */
- ObservableArray.prototype.every = function (callbackfn, thisArg) {
- return this._array.every(callbackfn, thisArg);
- };
- /**
- * Determines whether the specified callback function returns true for any element of an array.
- * @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.
- * @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.
- */
- ObservableArray.prototype.some = function (callbackfn, thisArg) {
- return this._array.some(callbackfn, thisArg);
- };
- /**
- * Performs the specified action for each element in an array.
- * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
- * @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.
- */
- ObservableArray.prototype.forEach = function (callbackfn, thisArg) {
- return this._array.forEach(callbackfn, thisArg);
- };
- /**
- * Calls a defined callback function on each element of an array, and returns an array that contains the results.
- * @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.
- * @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.
- */
- ObservableArray.prototype.map = function (callbackfn, thisArg) {
- return this._array.map(callbackfn, thisArg);
- };
- /**
- * Returns the elements of an array that meet the condition specified in a callback function.
- * @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.
- * @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.
- */
- ObservableArray.prototype.filter = function (callbackfn, thisArg) {
- return this._array.filter(callbackfn, thisArg);
- };
- /**
- * 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.
- * @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.
- * @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.
- */
- ObservableArray.prototype.reduce = function (callbackfn, initialValue) {
- return this._array.reduce(callbackfn);
- };
- /**
- * 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.
- * @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.
- * @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.
- */
- ObservableArray.prototype.reduceRight = function (callbackfn, initialValue) {
- return this._array.reduceRight(callbackfn);
- };
- Object.defineProperty(ObservableArray.prototype, "arrayChanged", {
- get: function () {
- if (!this._arrayChanged) {
- this._arrayChanged = new BABYLON.Observable();
- }
- return this._arrayChanged;
- },
- enumerable: true,
- configurable: true
- });
- ObservableArray.prototype.getArrayChangedObject = function () {
- if (this._arrayChanged && this._arrayChanged.hasObservers()) {
- var ac = this._callingArrayChanged ? new ArrayChanged() : this.dci;
- return ac;
- }
- return null;
- };
- ObservableArray.prototype.feedNotifArray = function (array, startindIndex) {
- var items = [];
- for (var _i = 2; _i < arguments.length; _i++) {
- items[_i - 2] = arguments[_i];
- }
- array.splice(0);
- for (var i = 0; i < items.length; i++) {
- var value = this._array[i + startindIndex];
- if (value !== undefined) {
- array.push({ index: i + startindIndex, value: value });
- }
- }
- };
- ObservableArray.prototype.callArrayChanged = function (ac) {
- try {
- this._callingArrayChanged = true;
- this.arrayChanged.notifyObservers(ac, ac.action);
- }
- finally {
- this._callingArrayChanged = false;
- }
- };
- Object.defineProperty(ObservableArray.prototype, "watchedObjectChanged", {
- get: function () {
- if (!this._watchedObjectChanged) {
- this._watchedObjectChanged = new BABYLON.Observable();
- }
- return this._watchedObjectChanged;
- },
- enumerable: true,
- configurable: true
- });
- ObservableArray.prototype._addWatchedElement = function () {
- var _this = this;
- var items = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- items[_i] = arguments[_i];
- }
- var _loop_1 = function (curItem) {
- if (curItem["propertyChanged"]) {
- var key_1 = curItem["__ObsArrayObjID__"];
- // The object may already be part of another ObsArray, so there already be a valid ID
- if (!key_1) {
- key_1 = BABYLON.Tools.RandomId();
- curItem["__ObsArrayObjID__"] = key_1;
- }
- this_1._watchedObjectList.add(key_1, curItem.propertyChanged.add(function (e, d) {
- _this.onWatchedObjectChanged(key_1, curItem, e);
- }));
- }
- };
- var this_1 = this;
- for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
- var curItem = items_1[_a];
- _loop_1(curItem);
- }
- };
- ObservableArray.prototype._removeWatchedElement = function () {
- var items = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- items[_i] = arguments[_i];
- }
- for (var _a = 0, items_2 = items; _a < items_2.length; _a++) {
- var curItem = items_2[_a];
- var key = curItem["__ObsArrayObjID__"];
- if (key != null) {
- var observer = this._watchedObjectList.getAndRemove(key);
- curItem.propertyChanged.remove(observer);
- }
- }
- };
- ObservableArray.prototype.onWatchedObjectChanged = function (key, object, propChanged) {
- if (this._watchedObjectChanged && this._watchedObjectChanged.hasObservers()) {
- var woci = this._callingWatchedObjectChanged ? new OAWatchedObjectChangedInfo() : this._woci;
- woci.object = object;
- woci.propertyChanged = propChanged;
- try {
- this._callingWatchedObjectChanged = true;
- this.watchedObjectChanged.notifyObservers(woci);
- }
- finally {
- this._callingWatchedObjectChanged = false;
- }
- }
- };
- return ObservableArray;
- }(BABYLON.PropertyChangedBase));
- BABYLON.ObservableArray = ObservableArray;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.observableArray.js.map
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var BABYLON;
- (function (BABYLON) {
- /**
- * Class for the ObservableStringDictionary.onDictionaryChanged observable
- */
- var DictionaryChanged = (function () {
- function DictionaryChanged() {
- }
- Object.defineProperty(DictionaryChanged, "clearAction", {
- /**
- * The content of the dictionary was totally cleared
- */
- get: function () {
- return DictionaryChanged._clearAction;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DictionaryChanged, "newItemAction", {
- /**
- * A new item was added, the newItem field contains the key/value pair
- */
- get: function () {
- return DictionaryChanged._newItemAction;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DictionaryChanged, "removedItemAction", {
- /**
- * An existing item was removed, the removedKey field contains its key
- */
- get: function () {
- return DictionaryChanged._removedItemAction;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DictionaryChanged, "itemValueChangedAction", {
- /**
- * An existing item had a value change, the changedItem field contains the key/value
- */
- get: function () {
- return DictionaryChanged._itemValueChangedAction;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DictionaryChanged, "replacedAction", {
- /**
- * The dictionary's content was reset and replaced by the content of another dictionary.
- * DictionaryChanged<T> contains no further information about this action
- */
- get: function () {
- return DictionaryChanged._replacedAction;
- },
- enumerable: true,
- configurable: true
- });
- return DictionaryChanged;
- }());
- DictionaryChanged._clearAction = 0x1;
- DictionaryChanged._newItemAction = 0x2;
- DictionaryChanged._removedItemAction = 0x4;
- DictionaryChanged._itemValueChangedAction = 0x8;
- DictionaryChanged._replacedAction = 0x10;
- BABYLON.DictionaryChanged = DictionaryChanged;
- var OSDWatchedObjectChangedInfo = (function () {
- function OSDWatchedObjectChangedInfo() {
- }
- return OSDWatchedObjectChangedInfo;
- }());
- BABYLON.OSDWatchedObjectChangedInfo = OSDWatchedObjectChangedInfo;
- var ObservableStringDictionary = (function (_super) {
- __extends(ObservableStringDictionary, _super);
- function ObservableStringDictionary(watchObjectsPropertyChange) {
- var _this = _super.call(this) || this;
- _this._propertyChanged = null;
- _this._dictionaryChanged = null;
- _this.dci = new DictionaryChanged();
- _this._callingDicChanged = false;
- _this._watchedObjectChanged = null;
- _this._callingWatchedObjectChanged = false;
- _this._woci = new OSDWatchedObjectChangedInfo();
- _this._watchObjectsPropertyChange = watchObjectsPropertyChange;
- _this._watchedObjectList = _this._watchObjectsPropertyChange ? new BABYLON.StringDictionary() : null;
- return _this;
- }
- /**
- * This will clear this dictionary and copy the content from the 'source' one.
- * If the T value is a custom object, it won't be copied/cloned, the same object will be used
- * @param source the dictionary to take the content from and copy to this dictionary
- */
- ObservableStringDictionary.prototype.copyFrom = function (source) {
- var _this = this;
- var oldCount = this.count;
- // Don't rely on this class' implementation for clear/add otherwise tons of notification will be thrown
- _super.prototype.clear.call(this);
- source.forEach(function (t, v) { return _this._add(t, v, false, _this._watchObjectsPropertyChange); });
- this.onDictionaryChanged(DictionaryChanged.replacedAction, null, null, null);
- this.onPropertyChanged("count", oldCount, this.count);
- };
- /**
- * Get a value from its key or add it if it doesn't exist.
- * This method will ensure you that a given key/data will be present in the dictionary.
- * @param key the given key to get the matching value from
- * @param factory the factory that will create the value if the key is not present in the dictionary.
- * The factory will only be invoked if there's no data for the given key.
- * @return the value corresponding to the key.
- */
- ObservableStringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
- var _this = this;
- var val = _super.prototype.getOrAddWithFactory.call(this, key, function (k) {
- var v = factory(key);
- _this._add(key, v, true, _this._watchObjectsPropertyChange);
- return v;
- });
- return val;
- };
- /**
- * Add a new key and its corresponding value
- * @param key the key to add
- * @param value the value corresponding to the key
- * @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
- */
- ObservableStringDictionary.prototype.add = function (key, value) {
- return this._add(key, value, true, this._watchObjectsPropertyChange);
- };
- ObservableStringDictionary.prototype.getAndRemove = function (key) {
- var val = _super.prototype.get.call(this, key);
- this._remove(key, true, val);
- return val;
- };
- ObservableStringDictionary.prototype._add = function (key, value, fireNotif, registerWatcher) {
- if (_super.prototype.add.call(this, key, value)) {
- if (fireNotif) {
- this.onDictionaryChanged(DictionaryChanged.newItemAction, { key: key, value: value }, null, null);
- this.onPropertyChanged("count", this.count - 1, this.count);
- }
- if (registerWatcher) {
- this._addWatchedElement(key, value);
- }
- return true;
- }
- return false;
- };
- ObservableStringDictionary.prototype._addWatchedElement = function (key, el) {
- var _this = this;
- if (el["propertyChanged"]) {
- this._watchedObjectList.add(key, el.propertyChanged.add(function (e, d) {
- _this.onWatchedObjectChanged(key, el, e);
- }));
- }
- };
- ObservableStringDictionary.prototype._removeWatchedElement = function (key, el) {
- var observer = this._watchedObjectList.getAndRemove(key);
- if (el["propertyChanged"]) {
- el.propertyChanged.remove(observer);
- }
- };
- ObservableStringDictionary.prototype.set = function (key, value) {
- var oldValue = this.get(key);
- if (this._watchObjectsPropertyChange) {
- this._removeWatchedElement(key, oldValue);
- }
- if (_super.prototype.set.call(this, key, value)) {
- this.onDictionaryChanged(DictionaryChanged.itemValueChangedAction, null, null, { key: key, oldValue: oldValue, newValue: value });
- this._addWatchedElement(key, value);
- return true;
- }
- return false;
- };
- /**
- * Remove a key/value from the dictionary.
- * @param key the key to remove
- * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
- */
- ObservableStringDictionary.prototype.remove = function (key) {
- return this._remove(key, true);
- };
- ObservableStringDictionary.prototype._remove = function (key, fireNotif, element) {
- if (!element) {
- element = this.get(key);
- }
- if (!element) {
- return false;
- }
- if (_super.prototype.remove.call(this, key) === undefined) {
- return false;
- }
- this.onDictionaryChanged(DictionaryChanged.removedItemAction, null, key, null);
- this.onPropertyChanged("count", this.count + 1, this.count);
- if (this._watchObjectsPropertyChange) {
- this._removeWatchedElement(key, element);
- }
- return true;
- };
- /**
- * Clear the whole content of the dictionary
- */
- ObservableStringDictionary.prototype.clear = function () {
- var _this = this;
- if (this._watchedObjectList) {
- this._watchedObjectList.forEach(function (k, v) {
- var el = _this.get(k);
- _this._removeWatchedElement(k, el);
- });
- this._watchedObjectList.clear();
- }
- var oldCount = this.count;
- _super.prototype.clear.call(this);
- this.onDictionaryChanged(DictionaryChanged.clearAction, null, null, null);
- this.onPropertyChanged("count", oldCount, 0);
- };
- Object.defineProperty(ObservableStringDictionary.prototype, "propertyChanged", {
- get: function () {
- if (!this._propertyChanged) {
- this._propertyChanged = new BABYLON.Observable();
- }
- return this._propertyChanged;
- },
- enumerable: true,
- configurable: true
- });
- ObservableStringDictionary.prototype.onPropertyChanged = function (propName, oldValue, newValue, mask) {
- if (this._propertyChanged && this._propertyChanged.hasObservers()) {
- var pci = ObservableStringDictionary.callingPropChanged ? new BABYLON.PropertyChangedInfo() : ObservableStringDictionary.pci;
- pci.oldValue = oldValue;
- pci.newValue = newValue;
- pci.propertyName = propName;
- try {
- ObservableStringDictionary.callingPropChanged = true;
- this.propertyChanged.notifyObservers(pci, mask);
- }
- finally {
- ObservableStringDictionary.callingPropChanged = false;
- }
- }
- };
- Object.defineProperty(ObservableStringDictionary.prototype, "dictionaryChanged", {
- get: function () {
- if (!this._dictionaryChanged) {
- this._dictionaryChanged = new BABYLON.Observable();
- }
- return this._dictionaryChanged;
- },
- enumerable: true,
- configurable: true
- });
- ObservableStringDictionary.prototype.onDictionaryChanged = function (action, newItem, removedKey, changedItem) {
- if (this._dictionaryChanged && this._dictionaryChanged.hasObservers()) {
- var dci = this._callingDicChanged ? new DictionaryChanged() : this.dci;
- dci.action = action;
- dci.newItem = newItem;
- dci.removedKey = removedKey;
- dci.changedItem = changedItem;
- try {
- this._callingDicChanged = true;
- this.dictionaryChanged.notifyObservers(dci, action);
- }
- finally {
- this._callingDicChanged = false;
- }
- }
- };
- Object.defineProperty(ObservableStringDictionary.prototype, "watchedObjectChanged", {
- get: function () {
- if (!this._watchedObjectChanged) {
- this._watchedObjectChanged = new BABYLON.Observable();
- }
- return this._watchedObjectChanged;
- },
- enumerable: true,
- configurable: true
- });
- ObservableStringDictionary.prototype.onWatchedObjectChanged = function (key, object, propChanged) {
- if (this._watchedObjectChanged && this._watchedObjectChanged.hasObservers()) {
- var woci = this._callingWatchedObjectChanged ? new OSDWatchedObjectChangedInfo() : this._woci;
- woci.key = key;
- woci.object = object;
- woci.propertyChanged = propChanged;
- try {
- this._callingWatchedObjectChanged = true;
- this.watchedObjectChanged.notifyObservers(woci);
- }
- finally {
- this._callingWatchedObjectChanged = false;
- }
- }
- };
- return ObservableStringDictionary;
- }(BABYLON.StringDictionary));
- ObservableStringDictionary.pci = new BABYLON.PropertyChangedInfo();
- ObservableStringDictionary.callingPropChanged = false;
- BABYLON.ObservableStringDictionary = ObservableStringDictionary;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.observableStringDictionary.js.map
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- /**
- * This class given information about a given character.
- */
- var CharInfo = (function () {
- function CharInfo() {
- }
- return CharInfo;
- }());
- BABYLON.CharInfo = CharInfo;
- /**
- * This is an abstract base class to hold a Texture that will contain a FontMap
- */
- var BaseFontTexture = (function (_super) {
- __extends(BaseFontTexture, _super);
- function BaseFontTexture(url, scene, noMipmap, invertY, samplingMode, premultipliedAlpha) {
- if (noMipmap === void 0) { noMipmap = false; }
- if (invertY === void 0) { invertY = true; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- if (premultipliedAlpha === void 0) { premultipliedAlpha = false; }
- var _this = _super.call(this, url, scene, noMipmap, invertY, samplingMode) || this;
- _this._cachedFontId = null;
- _this._charInfos = new BABYLON.StringDictionary();
- _this._isPremultipliedAlpha = premultipliedAlpha;
- return _this;
- }
- Object.defineProperty(BaseFontTexture.prototype, "isSuperSampled", {
- /**
- * Is the Font is using Super Sampling (each font texel is doubled).
- */
- get: function () {
- return this._superSample;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(BaseFontTexture.prototype, "isSignedDistanceField", {
- /**
- * Is the Font was rendered using the Signed Distance Field algorithm
- * @returns {}
- */
- get: function () {
- return this._signedDistanceField;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(BaseFontTexture.prototype, "isPremultipliedAlpha", {
- /**
- * True if the font was drawn using multiplied alpha
- */
- get: function () {
- return this._isPremultipliedAlpha;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(BaseFontTexture.prototype, "spaceWidth", {
- /**
- * Get the Width (in pixel) of the Space character
- */
- get: function () {
- return this._spaceWidth;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(BaseFontTexture.prototype, "lineHeight", {
- /**
- * Get the Line height (in pixel)
- */
- get: function () {
- return this._lineHeight;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Measure the width/height that will take a given text
- * @param text the text to measure
- * @param tabulationSize the size (in space character) of the tabulation character, default value must be 4
- */
- BaseFontTexture.prototype.measureText = function (text, tabulationSize) {
- var maxWidth = 0;
- var curWidth = 0;
- var lineCount = 1;
- var charxpos = 0;
- // Parse each char of the string
- for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
- var char = text_1[_i];
- // Next line feed?
- if (char === "\n") {
- maxWidth = Math.max(maxWidth, curWidth);
- charxpos = 0;
- curWidth = 0;
- ++lineCount;
- continue;
- }
- // Tabulation ?
- if (char === "\t") {
- var nextPos = charxpos + tabulationSize;
- nextPos = nextPos - (nextPos % tabulationSize);
- curWidth += (nextPos - charxpos) * this.spaceWidth;
- charxpos = nextPos;
- continue;
- }
- if (char < " ") {
- continue;
- }
- var ci = this.getChar(char);
- if (!ci) {
- throw new Error("Character " + char + " is not supported by FontTexture " + this.name);
- }
- curWidth += ci.charWidth;
- ++charxpos;
- }
- maxWidth = Math.max(maxWidth, curWidth);
- return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
- };
- return BaseFontTexture;
- }(BABYLON.Texture));
- BABYLON.BaseFontTexture = BaseFontTexture;
- var BitmapFontInfo = (function () {
- function BitmapFontInfo() {
- this.kerningDic = new BABYLON.StringDictionary();
- this.charDic = new BABYLON.StringDictionary();
- }
- return BitmapFontInfo;
- }());
- BABYLON.BitmapFontInfo = BitmapFontInfo;
- var BitmapFontTexture = (function (_super) {
- __extends(BitmapFontTexture, _super);
- function BitmapFontTexture(scene, bmFontUrl, textureUrl, noMipmap, invertY, samplingMode, premultipliedAlpha, onLoad, onError) {
- if (textureUrl === void 0) { textureUrl = null; }
- if (noMipmap === void 0) { noMipmap = false; }
- if (invertY === void 0) { invertY = true; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- if (premultipliedAlpha === void 0) { premultipliedAlpha = false; }
- if (onLoad === void 0) { onLoad = null; }
- if (onError === void 0) { onError = null; }
- var _this = _super.call(this, null, scene, noMipmap, invertY, samplingMode, premultipliedAlpha) || this;
- _this._usedCounter = 1;
- var xhr = new XMLHttpRequest();
- xhr.onreadystatechange = function () {
- if (xhr.readyState === XMLHttpRequest.DONE) {
- if (xhr.status === 200) {
- var ext = bmFontUrl.split('.').pop().split(/\#|\?/)[0];
- var plugins = BitmapFontTexture.plugins.get(ext.toLocaleLowerCase());
- if (!plugins) {
- if (onError) {
- onError("couldn't find a plugin for this file extension", -1);
- }
- return;
- }
- var _loop_1 = function (p) {
- var ret = p.loadFont(xhr.response, scene, invertY);
- if (ret) {
- var bfi = ret.bfi;
- if (textureUrl != null) {
- bfi.textureUrl = textureUrl;
- }
- else {
- var baseUrl = bmFontUrl.substr(0, bmFontUrl.lastIndexOf("/") + 1);
- bfi.textureUrl = baseUrl + bfi.textureFile;
- }
- _this._texture = scene.getEngine().createTexture(bfi.textureUrl, noMipmap, invertY, scene, samplingMode, function () {
- if (ret.bfi && onLoad) {
- onLoad();
- }
- });
- _this._lineHeight = bfi.lineHeight;
- _this._charInfos.copyFrom(bfi.charDic);
- var ci = _this.getChar(" ");
- if (ci) {
- _this._spaceWidth = ci.charWidth;
- }
- else {
- _this._charInfos.first(function (k, v) { return _this._spaceWidth = v.charWidth; });
- }
- if (!ret.bfi && onError) {
- onError(ret.errorMsg, ret.errorCode);
- }
- return { value: void 0 };
- }
- };
- for (var _i = 0, plugins_1 = plugins; _i < plugins_1.length; _i++) {
- var p = plugins_1[_i];
- var state_1 = _loop_1(p);
- if (typeof state_1 === "object")
- return state_1.value;
- }
- if (onError) {
- onError("No plugin to load this BMFont file format", -1);
- }
- }
- else {
- if (onError) {
- onError("Couldn't load file through HTTP Request, HTTP Status " + xhr.status, xhr.status);
- }
- }
- }
- };
- xhr.open("GET", bmFontUrl, true);
- xhr.send();
- return _this;
- }
- BitmapFontTexture.GetCachedFontTexture = function (scene, fontTexture) {
- var dic = scene.getOrAddExternalDataWithFactory("BitmapFontTextureCache", function () { return new BABYLON.StringDictionary(); });
- var ft = dic.get(fontTexture.uid);
- if (ft) {
- ++ft._usedCounter;
- return ft;
- }
- dic.add(fontTexture.uid, fontTexture);
- return ft;
- };
- BitmapFontTexture.ReleaseCachedFontTexture = function (scene, fontTexture) {
- var dic = scene.getExternalData("BitmapFontTextureCache");
- if (!dic) {
- return;
- }
- var font = dic.get(fontTexture.uid);
- if (--font._usedCounter === 0) {
- dic.remove(fontTexture.uid);
- font.dispose();
- }
- };
- Object.defineProperty(BitmapFontTexture.prototype, "isDynamicFontTexture", {
- /**
- * 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()
- */
- get: function () {
- return false;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * This method does nothing for a BitmapFontTexture object as it's a static texture
- */
- BitmapFontTexture.prototype.update = function () {
- };
- /**
- * Retrieve the CharInfo object for a given character
- * @param char the character to retrieve the CharInfo object from (e.g.: "A", "a", etc.)
- */
- BitmapFontTexture.prototype.getChar = function (char) {
- return this._charInfos.get(char);
- };
- /**
- * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
- * When the other party is done with this object, decCachedFontTextureCounter must be called.
- */
- BitmapFontTexture.prototype.incCachedFontTextureCounter = function () {
- ++this._usedCounter;
- };
- /**
- * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
- */
- BitmapFontTexture.prototype.decCachedFontTextureCounter = function () {
- var dic = this.getScene().getExternalData("BitmapFontTextureCache");
- if (!dic) {
- return;
- }
- if (--this._usedCounter === 0) {
- dic.remove(this._cachedFontId);
- this.dispose();
- }
- };
- BitmapFontTexture.addLoader = function (fileExtension, plugin) {
- var a = BitmapFontTexture.plugins.getOrAddWithFactory(fileExtension.toLocaleLowerCase(), function () { return new Array(); });
- a.push(plugin);
- };
- return BitmapFontTexture;
- }(BaseFontTexture));
- BitmapFontTexture.plugins = new BABYLON.StringDictionary();
- BABYLON.BitmapFontTexture = BitmapFontTexture;
- /**
- * This class is a special kind of texture which generates on the fly characters of a given css style "fontName".
- * The generated texture will be updated when new characters will be retrieved using the getChar() method, but you have
- * to call the update() method for the texture to fetch these changes, you can harmlessly call update any time you want, if no
- * change were made, nothing will happen.
- * The Font Texture can be rendered in three modes: normal size, super sampled size (x2) or using Signed Distance Field rendering.
- * 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).
- * 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.
- */
- var FontTexture = (function (_super) {
- __extends(FontTexture, _super);
- /**
- * Create a new instance of the FontTexture class
- * @param name the name of the texture
- * @param font the font to use, use the W3C CSS notation
- * @param scene the scene that owns the texture
- * @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
- * @param samplingMode the texture sampling mode
- * @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.
- */
- function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
- if (maxCharCount === void 0) { maxCharCount = 200; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- if (superSample === void 0) { superSample = false; }
- if (signedDistanceField === void 0) { signedDistanceField = false; }
- var _this = _super.call(this, null, scene, true, false, samplingMode) || this;
- _this._curCharCount = 0;
- _this._lastUpdateCharCount = -1;
- _this._usedCounter = 1;
- _this.name = name;
- _this.debugMode = false;
- _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- _this._sdfScale = 8;
- _this._signedDistanceField = signedDistanceField;
- _this._superSample = false;
- _this._isPremultipliedAlpha = !signedDistanceField;
- _this.name = "FontTexture " + font;
- // SDF will use super sample no matter what, the resolution is otherwise too poor to produce correct result
- if (superSample || signedDistanceField) {
- var sfont = _this.getSuperSampleFont(font);
- if (sfont) {
- _this._superSample = true;
- font = sfont;
- }
- }
- // First canvas creation to determine the size of the texture to create
- _this._canvas = document.createElement("canvas");
- _this._context = _this._canvas.getContext("2d");
- _this._context.font = font;
- _this._context.fillStyle = "white";
- _this._context.textBaseline = "top";
- var res = _this.getFontHeight(font, "j$|");
- _this._lineHeightSuper = res.height; //+4;
- _this._lineHeight = _this._superSample ? (Math.ceil(_this._lineHeightSuper / 2)) : _this._lineHeightSuper;
- _this._offset = res.offset;
- res = _this.getFontHeight(font, "f");
- _this._baseLine = res.height + res.offset - _this._offset;
- var maxCharWidth = Math.max(_this._context.measureText("W").width, _this._context.measureText("_").width);
- _this._spaceWidthSuper = _this._context.measureText(" ").width;
- _this._spaceWidth = _this._superSample ? (_this._spaceWidthSuper / 2) : _this._spaceWidthSuper;
- _this._xMargin = Math.ceil(maxCharWidth / 32);
- _this._yMargin = _this._xMargin;
- // This is an approximate size, but should always be able to fit at least the maxCharCount
- var totalEstSurface = (Math.ceil(_this._lineHeightSuper) + (_this._yMargin * 2)) * (Math.ceil(maxCharWidth) + (_this._xMargin * 2)) * maxCharCount;
- var edge = Math.sqrt(totalEstSurface);
- var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
- // Create the texture that will store the font characters
- _this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
- var textureSize = _this.getSize();
- _this.hasAlpha = _this._signedDistanceField === false;
- // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
- _this._canvas = document.createElement("canvas");
- _this._canvas.width = textureSize.width;
- _this._canvas.height = textureSize.height;
- _this._context = _this._canvas.getContext("2d");
- _this._context.textBaseline = "top";
- _this._context.font = font;
- _this._context.fillStyle = "white";
- _this._context.imageSmoothingEnabled = false;
- _this._context.clearRect(0, 0, textureSize.width, textureSize.height);
- // 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
- // 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)
- // So you can see this context as an intermediate one, because it is.
- if (_this._signedDistanceField) {
- var sdfC = document.createElement("canvas");
- var s = _this._sdfScale;
- sdfC.width = (Math.ceil(maxCharWidth) + _this._xMargin * 2) * s;
- sdfC.height = (Math.ceil(_this._lineHeightSuper) + _this._yMargin * 2) * s;
- var sdfCtx = sdfC.getContext("2d");
- sdfCtx.scale(s, s);
- sdfCtx.textBaseline = "top";
- sdfCtx.font = font;
- sdfCtx.fillStyle = "white";
- sdfCtx.imageSmoothingEnabled = false;
- _this._sdfCanvas = sdfC;
- _this._sdfContext = sdfCtx;
- }
- _this._currentFreePosition = BABYLON.Vector2.Zero();
- // Add the basic ASCII based characters
- for (var i = 0x20; i < 0x7F; i++) {
- var c = String.fromCharCode(i);
- _this.getChar(c);
- }
- _this.update();
- return _this;
- //this._saveToImage("");
- }
- Object.defineProperty(FontTexture.prototype, "isDynamicFontTexture", {
- get: function () {
- return true;
- },
- enumerable: true,
- configurable: true
- });
- FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField, bilinearFiltering) {
- if (supersample === void 0) { supersample = false; }
- if (signedDistanceField === void 0) { signedDistanceField = false; }
- if (bilinearFiltering === void 0) { bilinearFiltering = false; }
- var dic = scene.getOrAddExternalDataWithFactory("FontTextureCache", function () { return new BABYLON.StringDictionary(); });
- var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF") + (bilinearFiltering ? "_+BF" : "_-BF");
- var ft = dic.get(lfn);
- if (ft) {
- ++ft._usedCounter;
- return ft;
- }
- ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, (signedDistanceField || bilinearFiltering) ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, supersample, signedDistanceField);
- ft._cachedFontId = lfn;
- dic.add(lfn, ft);
- return ft;
- };
- FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField, bilinearFiltering) {
- if (supersample === void 0) { supersample = false; }
- if (signedDistanceField === void 0) { signedDistanceField = false; }
- if (bilinearFiltering === void 0) { bilinearFiltering = false; }
- var dic = scene.getExternalData("FontTextureCache");
- if (!dic) {
- return;
- }
- var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF") + (bilinearFiltering ? "_+BF" : "_-BF");
- var font = dic.get(lfn);
- if (--font._usedCounter === 0) {
- dic.remove(lfn);
- font.dispose();
- }
- };
- FontTexture.prototype._saveToImage = function (url) {
- var base64Image = this._canvas.toDataURL("image/png");
- //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
- if (("download" in document.createElement("a"))) {
- var a = window.document.createElement("a");
- a.href = base64Image;
- var date = new Date();
- var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) +
- "-" +
- date.getDate() +
- "_" +
- date.getHours() +
- "-" +
- ('0' + date.getMinutes()).slice(-2);
- a.setAttribute("download", "screenshot_" + stringDate + ".png");
- window.document.body.appendChild(a);
- a.addEventListener("click", function () {
- a.parentElement.removeChild(a);
- });
- a.click();
- //Or opening a new tab with the image if it is not possible to automatically start download.
- }
- else {
- var newWindow = window.open("");
- var img = newWindow.document.createElement("img");
- img.src = base64Image;
- newWindow.document.body.appendChild(img);
- }
- };
- /**
- * Make sure the given char is present in the font map.
- * @param char the character to get or add
- * @return the CharInfo instance corresponding to the given character
- */
- FontTexture.prototype.getChar = function (char) {
- var _this = this;
- if (char.length !== 1) {
- return null;
- }
- var info = this._charInfos.get(char);
- if (info) {
- return info;
- }
- info = new CharInfo();
- var measure = this._context.measureText(char);
- var textureSize = this.getSize();
- // we reached the end of the current line?
- var width = Math.ceil(measure.width + 0.5);
- if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
- this._currentFreePosition.x = 0;
- this._currentFreePosition.y += Math.ceil(this._lineHeightSuper + this._yMargin * 2);
- // No more room?
- if (this._currentFreePosition.y > textureSize.height) {
- return this.getChar("!");
- }
- }
- var curPosX = this._currentFreePosition.x + 0.5;
- var curPosY = this._currentFreePosition.y + 0.5;
- var curPosXMargin = curPosX + this._xMargin;
- var curPosYMargin = curPosY + this._yMargin;
- var drawDebug = function (ctx) {
- ctx.strokeStyle = "green";
- ctx.beginPath();
- ctx.rect(curPosXMargin, curPosYMargin, width, _this._lineHeightSuper);
- ctx.closePath();
- ctx.stroke();
- ctx.strokeStyle = "blue";
- ctx.beginPath();
- ctx.moveTo(curPosXMargin, curPosYMargin + Math.round(_this._baseLine));
- ctx.lineTo(curPosXMargin + width, curPosYMargin + Math.round(_this._baseLine));
- ctx.closePath();
- ctx.stroke();
- };
- // 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)
- if (this._signedDistanceField) {
- var s = this._sdfScale;
- this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
- // Coordinates are subject to the context's scale
- this._sdfContext.fillText(char, this._xMargin + 0.5, this._yMargin + 0.5 - this._offset);
- // Canvas Pixel Coordinates, no scale
- var data = this._sdfContext.getImageData(0, 0, (width + (this._xMargin * 2)) * s, this._sdfCanvas.height);
- var res = this._computeSDFChar(data);
- this._context.putImageData(res, curPosX, curPosY);
- if (this.debugMode) {
- drawDebug(this._context);
- }
- }
- else {
- if (this.debugMode) {
- drawDebug(this._context);
- }
- // Draw the character in the HTML canvas
- this._context.fillText(char, curPosXMargin, curPosYMargin - this._offset);
- // Premul Alpha manually
- var id = this._context.getImageData(curPosXMargin, curPosYMargin, width, this._lineHeightSuper);
- for (var i = 0; i < id.data.length; i += 4) {
- var v = id.data[i + 3];
- if (v > 0 && v < 255) {
- id.data[i + 0] = v;
- id.data[i + 1] = v;
- id.data[i + 2] = v;
- id.data[i + 3] = v;
- }
- }
- this._context.putImageData(id, curPosXMargin, curPosYMargin);
- }
- // Fill the CharInfo object
- info.topLeftUV = new BABYLON.Vector2((curPosXMargin - 0.5) / textureSize.width, (this._currentFreePosition.y - 0.5 + this._yMargin) / textureSize.height);
- info.bottomRightUV = new BABYLON.Vector2((curPosXMargin - 0.5 + width) / textureSize.width, info.topLeftUV.y + (this._lineHeightSuper / textureSize.height));
- info.yOffset = info.xOffset = 0;
- //console.log(`Char: ${char}, Offset: ${curPosX}, ${this._currentFreePosition.y + this._yMargin}, Size: ${width}, ${this._lineHeightSuper}, UV: ${info.topLeftUV}, ${info.bottomRightUV}`);
- if (this._signedDistanceField) {
- var off = 1 / textureSize.width;
- info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
- info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
- }
- info.charWidth = this._superSample ? (width / 2) : width;
- info.xAdvance = info.charWidth;
- // Add the info structure
- this._charInfos.add(char, info);
- this._curCharCount++;
- // Set the next position
- this._currentFreePosition.x += Math.ceil(width + this._xMargin * 2);
- return info;
- };
- FontTexture.prototype._computeSDFChar = function (source) {
- var scl = this._sdfScale;
- var sw = source.width;
- var sh = source.height;
- var dw = sw / scl;
- var dh = sh / scl;
- var roffx = 0;
- var roffy = 0;
- // We shouldn't look beyond half of the biggest between width and height
- var radius = scl;
- var br = radius - 1;
- var lookupSrc = function (dx, dy, offX, offY, lookVis) {
- var sx = dx * scl;
- var sy = dy * scl;
- // Looking out of the area? return true to make the test going on
- if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
- return true;
- }
- // Get the pixel we want
- var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
- var res = (val > 0) === lookVis;
- if (!res) {
- roffx = offX;
- roffy = offY;
- }
- return res;
- };
- var lookupArea = function (dx, dy, lookVis) {
- // 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
- if (lookupSrc(dx, dy, 0, br, lookVis) &&
- lookupSrc(dx, dy, 0, -br, lookVis) &&
- lookupSrc(dx, dy, -br, 0, lookVis) &&
- lookupSrc(dx, dy, br, 0, lookVis)) {
- return 0;
- }
- for (var i = 1; i <= radius; i++) {
- // Quick test N, S, W, E
- 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)) {
- return i * i; // Squared Distance is simple to compute in this case
- }
- // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
- for (var j = 1; j <= i; j++) {
- if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
- !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
- !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
- !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
- // We found the nearest texel having and opposite state, store the squared length
- var res_1 = (i * i) + (j * j);
- var count = 1;
- // 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
- if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
- res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
- ++count;
- }
- if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
- res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
- ++count;
- }
- if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
- res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
- ++count;
- }
- if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
- res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
- ++count;
- }
- if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
- res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
- ++count;
- }
- if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
- res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
- ++count;
- }
- if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
- res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
- ++count;
- }
- if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
- res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
- ++count;
- }
- // Compute the average based on the accumulated distance
- return res_1 / count;
- }
- }
- }
- return 0;
- };
- var tmp = new Array(dw * dh);
- for (var y = 0; y < dh; y++) {
- for (var x = 0; x < dw; x++) {
- var curState = lookupSrc(x, y, 0, 0, true);
- var d = lookupArea(x, y, curState);
- if (d === 0) {
- d = radius * radius * 2;
- }
- tmp[(y * dw) + x] = curState ? d : -d;
- }
- }
- var res = this._context.createImageData(dw, dh);
- var size = dw * dh;
- for (var j = 0; j < size; j++) {
- var d = tmp[j];
- var sign = (d < 0) ? -1 : 1;
- d = Math.sqrt(Math.abs(d)) * sign;
- d *= 127.5 / radius;
- d += 127.5;
- if (d < 0) {
- d = 0;
- }
- else if (d > 255) {
- d = 255;
- }
- d += 0.5;
- res.data[j * 4 + 0] = d;
- res.data[j * 4 + 1] = d;
- res.data[j * 4 + 2] = d;
- res.data[j * 4 + 3] = 255;
- }
- return res;
- };
- FontTexture.prototype.getSuperSampleFont = function (font) {
- // Eternal thank to http://stackoverflow.com/a/10136041/802124
- 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*$/;
- var res = font.toLocaleLowerCase().match(regex);
- if (res == null) {
- return null;
- }
- var size = parseInt(res[4]);
- res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
- var newFont = "";
- for (var j = 1; j < res.length; j++) {
- if (res[j] != null) {
- newFont += res[j] + " ";
- }
- }
- return newFont;
- };
- // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
- FontTexture.prototype.getFontHeight = function (font, chars) {
- var fontDraw = document.createElement("canvas");
- fontDraw.width = 600;
- fontDraw.height = 600;
- var ctx = fontDraw.getContext('2d');
- ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
- ctx.textBaseline = 'top';
- ctx.fillStyle = 'white';
- ctx.font = font;
- ctx.fillText(chars, 0, 0);
- var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
- var start = -1;
- var end = -1;
- for (var row = 0; row < fontDraw.height; row++) {
- for (var column = 0; column < fontDraw.width; column++) {
- var index = (row * fontDraw.width + column) * 4;
- var pix = pixels[index];
- if (pix === 0) {
- if (column === fontDraw.width - 1 && start !== -1) {
- end = row;
- row = fontDraw.height;
- break;
- }
- continue;
- }
- else {
- if (start === -1) {
- start = row;
- }
- break;
- }
- }
- }
- return { height: (end - start) + 1, offset: start };
- };
- Object.defineProperty(FontTexture.prototype, "canRescale", {
- get: function () {
- return false;
- },
- enumerable: true,
- configurable: true
- });
- FontTexture.prototype.getContext = function () {
- return this._context;
- };
- /**
- * Call this method when you've call getChar() at least one time, this will update the texture if needed.
- * Don't be afraid to call it, if no new character was added, this method simply does nothing.
- */
- FontTexture.prototype.update = function () {
- // Update only if there's new char added since the previous update
- if (this._lastUpdateCharCount < this._curCharCount) {
- this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
- this._lastUpdateCharCount = this._curCharCount;
- }
- };
- // cloning should be prohibited, there's no point to duplicate this texture at all
- FontTexture.prototype.clone = function () {
- return null;
- };
- /**
- * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
- * When the other party is done with this object, decCachedFontTextureCounter must be called.
- */
- FontTexture.prototype.incCachedFontTextureCounter = function () {
- ++this._usedCounter;
- };
- /**
- * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
- */
- FontTexture.prototype.decCachedFontTextureCounter = function () {
- var dic = this.getScene().getExternalData("FontTextureCache");
- if (!dic) {
- return;
- }
- if (--this._usedCounter === 0) {
- dic.remove(this._cachedFontId);
- this.dispose();
- }
- };
- return FontTexture;
- }(BaseFontTexture));
- BABYLON.FontTexture = FontTexture;
- /**
- * Orginial code from cocos2d-js, converted to TypeScript by Nockawa
- * Load the Text version of the BMFont format, no XML or binary supported, just plain old text
- */
- var BMFontLoaderTxt = BMFontLoaderTxt_1 = (function () {
- function BMFontLoaderTxt() {
- }
- BMFontLoaderTxt.prototype._parseStrToObj = function (str) {
- var arr = str.match(BMFontLoaderTxt_1.ITEM_EXP);
- if (!arr) {
- return null;
- }
- var obj = {};
- for (var i = 0, li = arr.length; i < li; i++) {
- var tempStr = arr[i];
- var index = tempStr.indexOf("=");
- var key = tempStr.substring(0, index);
- var value = tempStr.substring(index + 1);
- if (value.match(BMFontLoaderTxt_1.INT_EXP))
- value = parseInt(value);
- else if (value[0] === '"')
- value = value.substring(1, value.length - 1);
- obj[key] = value;
- }
- return obj;
- };
- BMFontLoaderTxt.prototype._buildCharInfo = function (bfi, initialLine, obj, textureSize, invertY, chars) {
- var char = null;
- var x = null;
- var y = null;
- var width = null;
- var height = null;
- var xoffset = 0;
- var yoffset = 0;
- var xadvance = 0;
- var ci = new CharInfo();
- for (var key in obj) {
- var value = obj[key];
- switch (key) {
- case "id":
- char = String.fromCharCode(value);
- break;
- case "x":
- x = value;
- break;
- case "y":
- y = value;
- break;
- case "width":
- width = value;
- break;
- case "height":
- height = value;
- break;
- case "xadvance":
- xadvance = value;
- break;
- case "xoffset":
- xoffset = value;
- break;
- case "yoffset":
- yoffset = value;
- break;
- }
- }
- if (x != null && y != null && width != null && height != null && char != null) {
- ci.xAdvance = xadvance;
- ci.xOffset = xoffset;
- ci.yOffset = bfi.lineHeight - height - yoffset;
- if (invertY) {
- ci.topLeftUV = new BABYLON.Vector2(1 - (x / textureSize.width), 1 - (y / textureSize.height));
- ci.bottomRightUV = new BABYLON.Vector2(1 - ((x + width) / textureSize.width), 1 - ((y + height) / textureSize.height));
- }
- else {
- ci.topLeftUV = new BABYLON.Vector2(x / textureSize.width, y / textureSize.height);
- ci.bottomRightUV = new BABYLON.Vector2((x + width) / textureSize.width, (y + height) / textureSize.height);
- }
- ci.charWidth = width;
- chars.add(char, ci);
- }
- else {
- console.log("Error while parsing line " + initialLine);
- }
- };
- BMFontLoaderTxt.prototype.loadFont = function (fontContent, scene, invertY) {
- var fontStr = fontContent;
- var bfi = new BitmapFontInfo();
- var errorCode = 0;
- var errorMsg = "OK";
- //padding
- var info = fontStr.match(BMFontLoaderTxt_1.INFO_EXP);
- var infoObj = this._parseStrToObj(info[0]);
- if (!infoObj) {
- return null;
- }
- var paddingArr = infoObj["padding"].split(",");
- bfi.padding = new BABYLON.Vector4(parseInt(paddingArr[0]), parseInt(paddingArr[1]), parseInt(paddingArr[2]), parseInt(paddingArr[3]));
- //common
- var commonObj = this._parseStrToObj(fontStr.match(BMFontLoaderTxt_1.COMMON_EXP)[0]);
- bfi.lineHeight = commonObj["lineHeight"];
- bfi.baseLine = commonObj["base"];
- bfi.textureSize = new BABYLON.Size(commonObj["scaleW"], commonObj["scaleH"]);
- var maxTextureSize = scene.getEngine()._gl.getParameter(0xd33);
- if (commonObj["scaleW"] > maxTextureSize.width || commonObj["scaleH"] > maxTextureSize.height) {
- errorMsg = "FontMap texture's size is bigger than what WebGL supports";
- errorCode = -1;
- }
- else {
- if (commonObj["pages"] !== 1) {
- errorMsg = "FontMap must contain one page only.";
- errorCode = -1;
- }
- else {
- //page
- var pageObj = this._parseStrToObj(fontStr.match(BMFontLoaderTxt_1.PAGE_EXP)[0]);
- if (pageObj["id"] !== 0) {
- errorMsg = "Only one page of ID 0 is supported";
- errorCode = -1;
- }
- else {
- bfi.textureFile = pageObj["file"];
- //char
- var charLines = fontStr.match(BMFontLoaderTxt_1.CHAR_EXP);
- for (var i = 0, li = charLines.length; i < li; i++) {
- var charObj = this._parseStrToObj(charLines[i]);
- this._buildCharInfo(bfi, charLines[i], charObj, bfi.textureSize, invertY, bfi.charDic);
- }
- //kerning
- var kerningLines = fontStr.match(BMFontLoaderTxt_1.KERNING_EXP);
- if (kerningLines) {
- for (var i = 0, li = kerningLines.length; i < li; i++) {
- var kerningObj = this._parseStrToObj(kerningLines[i]);
- bfi.kerningDic.add(((kerningObj["first"] << 16) | (kerningObj["second"] & 0xffff)).toString(), kerningObj["amount"]);
- }
- }
- }
- }
- }
- return { bfi: bfi, errorCode: errorCode, errorMsg: errorMsg };
- };
- return BMFontLoaderTxt;
- }());
- BMFontLoaderTxt.INFO_EXP = /info [^\r\n]*(\r\n|$)/gi;
- BMFontLoaderTxt.COMMON_EXP = /common [^\n]*(\n|$)/gi;
- BMFontLoaderTxt.PAGE_EXP = /page [^\n]*(\n|$)/gi;
- BMFontLoaderTxt.CHAR_EXP = /char [^\n]*(\n|$)/gi;
- BMFontLoaderTxt.KERNING_EXP = /kerning [^\n]*(\n|$)/gi;
- BMFontLoaderTxt.ITEM_EXP = /\w+=[^ \r\n]+/gi;
- BMFontLoaderTxt.INT_EXP = /^[\-]?\d+$/;
- BMFontLoaderTxt = BMFontLoaderTxt_1 = __decorate([
- BitmapFontLoaderPlugin("fnt", new BMFontLoaderTxt_1())
- ], BMFontLoaderTxt);
- ;
- function BitmapFontLoaderPlugin(fileExtension, plugin) {
- return function () {
- BitmapFontTexture.addLoader(fileExtension, plugin);
- };
- }
- BABYLON.BitmapFontLoaderPlugin = BitmapFontLoaderPlugin;
- var BMFontLoaderTxt_1;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.fontTexture.js.map
- var BABYLON;
- (function (BABYLON) {
- /**
- * Stores 2D Bounding Information.
- * This class handles a circle area and a bounding rectangle one.
- */
- var BoundingInfo2D = (function () {
- function BoundingInfo2D() {
- this.radius = 0;
- this.center = BABYLON.Vector2.Zero();
- this.extent = BABYLON.Vector2.Zero();
- this._worldAABBDirty = false;
- this._worldAABBDirtyObservable = null;
- this._worldAABB = BABYLON.Vector4.Zero();
- }
- /**
- * Create a BoundingInfo2D object from a given size
- * @param size the size that will be used to set the extend, radius will be computed from it.
- */
- BoundingInfo2D.CreateFromSize = function (size) {
- var r = new BoundingInfo2D();
- BoundingInfo2D.CreateFromSizeToRef(size, r);
- return r;
- };
- /**
- * Create a BoundingInfo2D object from a given radius
- * @param radius the radius to use, the extent will be computed from it.
- */
- BoundingInfo2D.CreateFromRadius = function (radius) {
- var r = new BoundingInfo2D();
- BoundingInfo2D.CreateFromRadiusToRef(radius, r);
- return r;
- };
- /**
- * Create a BoundingInfo2D object from a list of points.
- * The resulted object will be the smallest bounding area that includes all the given points.
- * @param points an array of points to compute the bounding object from.
- */
- BoundingInfo2D.CreateFromPoints = function (points) {
- var r = new BoundingInfo2D();
- BoundingInfo2D.CreateFromPointsToRef(points, r);
- return r;
- };
- /**
- * Update a BoundingInfo2D object using the given Size as input
- * @param size the bounding data will be computed from this size.
- * @param b must be a valid/allocated object, it will contain the result of the operation
- */
- BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
- if (!size) {
- size = BABYLON.Size.Zero();
- }
- b.center.x = +size.width / 2;
- b.center.y = +size.height / 2;
- b.extent.x = b.center.x;
- b.extent.y = b.center.y;
- b.radius = b.extent.length();
- b._worldAABBDirty = true;
- };
- /**
- * Update a BoundingInfo2D object using the given radius as input
- * @param radius the bounding data will be computed from this radius
- * @param b must be a valid/allocated object, it will contain the result of the operation
- */
- BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
- b.center.x = b.center.y = 0;
- var r = +radius;
- b.extent.x = r;
- b.extent.y = r;
- b.radius = r;
- b._worldAABBDirty = true;
- };
- /**
- * Update a BoundingInfo2D object using the given points array as input
- * @param points the point array to use to update the bounding data
- * @param b must be a valid/allocated object, it will contain the result of the operation
- */
- BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
- var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
- for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
- var p = points_1[_i];
- xmin = Math.min(p.x, xmin);
- xmax = Math.max(p.x, xmax);
- ymin = Math.min(p.y, ymin);
- ymax = Math.max(p.y, ymax);
- }
- BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
- };
- /**
- * Update a BoundingInfo2D object using the given min/max values as input
- * @param xmin the smallest x coordinate
- * @param xmax the biggest x coordinate
- * @param ymin the smallest y coordinate
- * @param ymax the buggest y coordinate
- * @param b must be a valid/allocated object, it will contain the result of the operation
- */
- BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
- var w = xmax - xmin;
- var h = ymax - ymin;
- b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
- b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
- b.radius = b.extent.length();
- b._worldAABBDirty = true;
- };
- BoundingInfo2D.prototype.toString = function () {
- return "Center: " + this.center + ", Extent: " + this.extent + ", Radius: " + this.radius;
- };
- /**
- * Duplicate this instance and return a new one
- * @return the duplicated instance
- */
- BoundingInfo2D.prototype.clone = function () {
- var r = new BoundingInfo2D();
- r.center = this.center.clone();
- r.radius = this.radius;
- r.extent = this.extent.clone();
- return r;
- };
- BoundingInfo2D.prototype.clear = function () {
- this.center.copyFromFloats(0, 0);
- this.radius = 0;
- this.extent.copyFromFloats(0, 0);
- this._worldAABBDirty = true;
- };
- BoundingInfo2D.prototype.copyFrom = function (src) {
- this.center.copyFrom(src.center);
- this.radius = src.radius;
- this.extent.copyFrom(src.extent);
- this._worldAABBDirty = true;
- };
- BoundingInfo2D.prototype.equals = function (other) {
- if (!other) {
- return false;
- }
- return other.center.equals(this.center) && other.extent.equals(this.extent);
- };
- /**
- * return the max extend of the bounding info
- */
- BoundingInfo2D.prototype.max = function () {
- var r = BABYLON.Vector2.Zero();
- this.maxToRef(r);
- return r;
- };
- /**
- * return the min/max extend of the bounding info.
- * x, y, z, w are left, bottom, right and top
- */
- BoundingInfo2D.prototype.minMax = function () {
- var r = BABYLON.Vector4.Zero();
- this.minMaxToRef(r);
- return r;
- };
- /**
- * Update a vector2 with the max extend of the bounding info
- * @param result must be a valid/allocated vector2 that will contain the result of the operation
- */
- BoundingInfo2D.prototype.maxToRef = function (result) {
- result.x = this.center.x + this.extent.x;
- result.y = this.center.y + this.extent.y;
- };
- /**
- * Update a vector4 with the min/max extend of the bounding info
- * x, y, z, w are left, bottom, right and top
- * @param result must be a valid/allocated vector4 that will contain the result of the operation
- */
- BoundingInfo2D.prototype.minMaxToRef = function (result) {
- result.x = this.center.x - this.extent.x;
- result.y = this.center.y - this.extent.y;
- result.z = this.center.x + this.extent.x;
- result.w = this.center.y + this.extent.y;
- };
- /**
- * Return the size of the boundingInfo rect surface
- */
- BoundingInfo2D.prototype.size = function () {
- var r = BABYLON.Size.Zero();
- this.sizeToRef(r);
- return r;
- };
- /**
- * Stores in the result object the size of the boundingInfo rect surface
- * @param result
- */
- BoundingInfo2D.prototype.sizeToRef = function (result) {
- result.width = this.extent.x * 2;
- result.height = this.extent.y * 2;
- };
- /**
- * Inflate the boundingInfo with the given vector
- * @param offset the extent will be incremented with offset and the radius will be computed again
- */
- BoundingInfo2D.prototype.inflate = function (offset) {
- this.extent.addInPlace(offset);
- this.radius = this.extent.length();
- };
- /**
- * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
- * @param matrix the transformation matrix to apply
- * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
- */
- BoundingInfo2D.prototype.transform = function (matrix) {
- var r = new BoundingInfo2D();
- this.transformToRef(matrix, r);
- return r;
- };
- /**
- * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
- * @param other the second BoundingInfo2D to compute the union with this one
- * @return a new instance containing the result of the union
- */
- BoundingInfo2D.prototype.union = function (other) {
- var r = new BoundingInfo2D();
- this.unionToRef(other, r);
- return r;
- };
- BoundingInfo2D.prototype.worldAABBIntersectionTest = function (other) {
- var a = this.worldAABB;
- var b = other.worldAABB;
- return b.z >= a.x && b.x <= a.z && b.w >= a.y && b.y <= a.w;
- };
- /**
- * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
- * 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.
- * @param matrix The matrix to use to compute the transformation
- * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
- */
- BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
- // Construct a bounding box based on the extent values
- var p = BoundingInfo2D._transform;
- p[0].x = this.center.x + this.extent.x;
- p[0].y = this.center.y + this.extent.y;
- p[1].x = this.center.x + this.extent.x;
- p[1].y = this.center.y - this.extent.y;
- p[2].x = this.center.x - this.extent.x;
- p[2].y = this.center.y - this.extent.y;
- p[3].x = this.center.x - this.extent.x;
- p[3].y = this.center.y + this.extent.y;
- // Transform the four points of the bounding box with the matrix
- for (var i = 0; i < 4; i++) {
- matrix.transformPointToRef(p[i], p[i]);
- }
- BoundingInfo2D.CreateFromPointsToRef(p, result);
- };
- BoundingInfo2D.prototype._updateWorldAABB = function (worldMatrix) {
- // Construct a bounding box based on the extent values
- var p = BoundingInfo2D._transform;
- p[0].x = this.center.x + this.extent.x;
- p[0].y = this.center.y + this.extent.y;
- p[1].x = this.center.x + this.extent.x;
- p[1].y = this.center.y - this.extent.y;
- p[2].x = this.center.x - this.extent.x;
- p[2].y = this.center.y - this.extent.y;
- p[3].x = this.center.x - this.extent.x;
- p[3].y = this.center.y + this.extent.y;
- // Transform the four points of the bounding box with the matrix
- for (var i = 0; i < 4; i++) {
- worldMatrix.transformPointToRef(p[i], p[i]);
- }
- this._worldAABB.x = Math.min(Math.min(p[0].x, p[1].x), Math.min(p[2].x, p[3].x));
- this._worldAABB.y = Math.min(Math.min(p[0].y, p[1].y), Math.min(p[2].y, p[3].y));
- this._worldAABB.z = Math.max(Math.max(p[0].x, p[1].x), Math.max(p[2].x, p[3].x));
- this._worldAABB.w = Math.max(Math.max(p[0].y, p[1].y), Math.max(p[2].y, p[3].y));
- };
- Object.defineProperty(BoundingInfo2D.prototype, "worldAABBDirtyObservable", {
- get: function () {
- if (!this._worldAABBDirtyObservable) {
- this._worldAABBDirtyObservable = new BABYLON.Observable();
- }
- return this._worldAABBDirtyObservable;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(BoundingInfo2D.prototype, "isWorldAABBDirty", {
- get: function () {
- return this._worldAABBDirty;
- },
- enumerable: true,
- configurable: true
- });
- BoundingInfo2D.prototype.dirtyWorldAABB = function () {
- if (this._worldAABBDirty) {
- return;
- }
- this._worldAABBDirty = true;
- if (this._worldAABBDirtyObservable && this._worldAABBDirtyObservable.hasObservers()) {
- this._worldAABBDirtyObservable.notifyObservers(this);
- }
- };
- Object.defineProperty(BoundingInfo2D.prototype, "worldAABB", {
- /**
- * Retrieve the world AABB, the Vector4's data is x=xmin, y=ymin, z=xmax, w=ymax
- */
- get: function () {
- if (this._worldAABBDirty) {
- if (!this.worldMatrixAccess) {
- throw new Error("you must set the worldMatrixAccess function first");
- }
- this._updateWorldAABB(this.worldMatrixAccess());
- this._worldAABBDirty = false;
- }
- return this._worldAABB;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
- * 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.
- * @param other the second object used to compute the union
- * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
- */
- BoundingInfo2D.prototype.unionToRef = function (other, result) {
- var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
- var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
- var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
- var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
- BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
- };
- /**
- * Check if the given point is inside the BoundingInfo.
- * The test is first made on the radius, then inside the rectangle described by the extent
- * @param pickPosition the position to test
- * @return true if the point is inside, false otherwise
- */
- BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
- // is it inside the radius?
- var pickLocal = pickPosition.subtract(this.center);
- if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
- // is it inside the rectangle?
- return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
- }
- return false;
- };
- return BoundingInfo2D;
- }());
- BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
- BABYLON.BoundingInfo2D = BoundingInfo2D;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.bounding2d.js.map
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var BABYLON;
- (function (BABYLON) {
- /**
- * The base class for all implementation of a Primitive Collision Manager
- */
- var PrimitiveCollisionManagerBase = (function () {
- function PrimitiveCollisionManagerBase(owner) {
- this._owner = owner;
- }
- PrimitiveCollisionManagerBase.allocBasicPCM = function (owner, enableBorders) {
- return new BasicPrimitiveCollisionManager(owner, enableBorders);
- };
- return PrimitiveCollisionManagerBase;
- }());
- BABYLON.PrimitiveCollisionManagerBase = PrimitiveCollisionManagerBase;
- /**
- * Base class of an Actor
- */
- var ActorInfoBase = (function () {
- function ActorInfoBase() {
- }
- return ActorInfoBase;
- }());
- BABYLON.ActorInfoBase = ActorInfoBase;
- var ActorInfo = (function (_super) {
- __extends(ActorInfo, _super);
- function ActorInfo(owner, actor, deep) {
- var _this = _super.call(this) || this;
- _this.owner = owner;
- _this.prim = actor;
- _this.flags = 0;
- _this.presentInClusters = new BABYLON.StringDictionary();
- _this.intersectWith = new BABYLON.ObservableStringDictionary(false);
- _this.setFlags((deep ? ActorInfo.flagDeep : 0) | ActorInfo.flagDirty);
- var bi = (deep ? actor.boundingInfo : actor.levelBoundingInfo);
- // Dirty Actor if its WorldAABB changed
- bi.worldAABBDirtyObservable.add(function (e, d) {
- _this.owner.actorDirty(_this);
- });
- // Dirty Actor if it's getting enabled/disabled
- actor.propertyChanged.add(function (e, d) {
- if (d.mask === -1) {
- return;
- }
- _this.setFlagsValue(ActorInfo.flagEnabled, e.newValue === true);
- _this.owner.actorDirty(_this);
- }, BABYLON.Prim2DBase.isVisibleProperty.flagId);
- return _this;
- }
- ActorInfo.prototype.setFlags = function (flags) {
- this.flags |= flags;
- };
- ActorInfo.prototype.clearFlags = function (flags) {
- this.flags &= ~flags;
- };
- ActorInfo.prototype.isAllFlagsSet = function (flags) {
- return (this.flags & flags) === flags;
- };
- ActorInfo.prototype.isSomeFlagsSet = function (flags) {
- return (this.flags & flags) !== 0;
- };
- ActorInfo.prototype.setFlagsValue = function (flags, value) {
- if (value) {
- this.flags |= flags;
- }
- else {
- this.flags &= ~flags;
- }
- };
- Object.defineProperty(ActorInfo.prototype, "worldAABB", {
- get: function () {
- return (this.isSomeFlagsSet(ActorInfo.flagDeep) ? this.prim.boundingInfo : this.prim.levelBoundingInfo).worldAABB;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActorInfo.prototype, "isEnabled", {
- get: function () {
- return this.isSomeFlagsSet(ActorInfo.flagEnabled);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActorInfo.prototype, "isDeep", {
- get: function () {
- return this.isSomeFlagsSet(ActorInfo.flagDeep);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActorInfo.prototype, "isDirty", {
- get: function () {
- return this.isSomeFlagsSet(ActorInfo.flagDirty);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActorInfo.prototype, "isRemoved", {
- get: function () {
- return this.isSomeFlagsSet(ActorInfo.flagRemoved);
- },
- enumerable: true,
- configurable: true
- });
- return ActorInfo;
- }(ActorInfoBase));
- ActorInfo.flagDeep = 0x0001; // set if the actor boundingInfo must be used instead of the levelBoundingInfo
- ActorInfo.flagEnabled = 0x0002; // set if the actor is enabled and should be considered for intersection tests
- ActorInfo.flagDirty = 0x0004; // set if the actor's AABB is dirty
- ActorInfo.flagRemoved = 0x0008; // set if the actor was removed from the PCM
- var ClusterInfo = (function () {
- function ClusterInfo() {
- this.actors = new BABYLON.StringDictionary();
- }
- ClusterInfo.prototype.clear = function () {
- this.actors.clear();
- };
- return ClusterInfo;
- }());
- var BasicPrimitiveCollisionManager = (function (_super) {
- __extends(BasicPrimitiveCollisionManager, _super);
- function BasicPrimitiveCollisionManager(owner, enableBorders) {
- var _this = _super.call(this, owner) || this;
- _this._actors = new BABYLON.StringDictionary();
- _this._dirtyActors = new BABYLON.StringDictionary();
- _this._clusters = null;
- _this._maxActorByCluster = 0;
- _this._AABBRenderPrim = null;
- _this._canvasSize = BABYLON.Size.Zero();
- _this._ClusterRenderPrim = null;
- _this._debugTextBackground = null;
- _this._clusterDirty = true;
- _this._clusterSize = new BABYLON.Size(2, 2);
- _this._clusterStep = BABYLON.Vector2.Zero();
- _this._lastClusterResizeCounter = 0;
- _this._freeClusters = new Array();
- _this._enableBorder = enableBorders;
- _this._debugUpdateOpCount = new BABYLON.PerfCounter();
- _this._debugUpdateTime = new BABYLON.PerfCounter();
- _this._intersectedActors = new BABYLON.ObservableStringDictionary(false);
- _this._borderIntersecteddActors = new Array(4);
- for (var j = 0; j < 4; j++) {
- _this._borderIntersecteddActors[j] = new BABYLON.ObservableStringDictionary(false);
- }
- var flagId = BABYLON.Canvas2D.actualSizeProperty.flagId;
- if (!BasicPrimitiveCollisionManager.WAABBCorners) {
- BasicPrimitiveCollisionManager.WAABBCorners = new Array(4);
- for (var i = 0; i < 4; i++) {
- BasicPrimitiveCollisionManager.WAABBCorners[i] = BABYLON.Vector2.Zero();
- }
- BasicPrimitiveCollisionManager.WAABBCornersCluster = new Array(4);
- for (var i = 0; i < 4; i++) {
- BasicPrimitiveCollisionManager.WAABBCornersCluster[i] = BABYLON.Vector2.Zero();
- }
- }
- owner.propertyChanged.add(function (e, d) {
- if (d.mask === -1) {
- return;
- }
- _this._clusterDirty = true;
- console.log("canvas size changed");
- }, flagId);
- _this.debugRenderAABB = false;
- _this.debugRenderClusters = false;
- _this.debugStats = false;
- return _this;
- }
- BasicPrimitiveCollisionManager.prototype._addActor = function (actor, deep) {
- var _this = this;
- return this._actors.getOrAddWithFactory(actor.uid, function () {
- var ai = new ActorInfo(_this, actor, deep);
- _this.actorDirty(ai);
- return ai;
- });
- };
- BasicPrimitiveCollisionManager.prototype._removeActor = function (actor) {
- var ai = this._actors.getAndRemove(actor.uid);
- ai.setFlags(ActorInfo.flagRemoved);
- this.actorDirty(ai);
- };
- BasicPrimitiveCollisionManager.prototype.actorDirty = function (actor) {
- actor.setFlags(ActorInfo.flagDirty);
- this._dirtyActors.add(actor.prim.uid, actor);
- };
- BasicPrimitiveCollisionManager.prototype._update = function () {
- this._canvasSize.copyFrom(this._owner.actualSize);
- // Should we update the WireFrame2D Primitive that displays the WorldAABB ?
- if (this.debugRenderAABB) {
- if (this._dirtyActors.count > 0 || this._debugRenderAABBDirty) {
- this._updateAABBDisplay();
- }
- }
- if (this._AABBRenderPrim) {
- this._AABBRenderPrim.levelVisible = this.debugRenderAABB;
- }
- var cw = this._clusterSize.width;
- var ch = this._clusterSize.height;
- // Check for Cluster resize
- if (((this._clusterSize.width < 16 && this._clusterSize.height < 16 && this._maxActorByCluster >= 10) ||
- (this._clusterSize.width > 2 && this._clusterSize.height > 2 && this._maxActorByCluster <= 7)) &&
- this._lastClusterResizeCounter > 100) {
- if (this._maxActorByCluster >= 10) {
- ++cw;
- ++ch;
- }
- else {
- --cw;
- --ch;
- }
- console.log("Change cluster size to " + cw + ":" + ch + ", max actor " + this._maxActorByCluster);
- this._clusterDirty = true;
- }
- // Should we update the WireFrame2D Primitive that displays the clusters
- if (this.debugRenderClusters && this._clusterDirty) {
- this._updateClusterDisplay(cw, ch);
- }
- if (this._ClusterRenderPrim) {
- this._ClusterRenderPrim.levelVisible = this.debugRenderClusters;
- }
- var updateStats = this.debugStats && (this._dirtyActors.count > 0 || this._clusterDirty);
- this._debugUpdateTime.beginMonitoring();
- // If the Cluster Size changed: rebuild it and add all actors. Otherwise add only new (dirty) actors
- if (this._clusterDirty) {
- this._initializeCluster(cw, ch);
- this._rebuildAllActors();
- }
- else {
- this._rebuildDirtyActors();
- ++this._lastClusterResizeCounter;
- }
- // Proceed to the collision detection between primitives
- this._collisionDetection();
- this._debugUpdateTime.endMonitoring();
- if (updateStats) {
- this._updateDebugStats();
- }
- if (this._debugTextBackground) {
- this._debugTextBackground.levelVisible = updateStats;
- }
- // Reset the dirty actor list: everything is processed
- this._dirtyActors.clear();
- };
- Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "debugRenderAABB", {
- /**
- * Renders the World AABB of all Actors
- */
- get: function () {
- return this._debugRenderAABB;
- },
- set: function (val) {
- if (this._debugRenderAABB === val) {
- return;
- }
- this._debugRenderAABB = val;
- this._debugRenderAABBDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "intersectedActors", {
- get: function () {
- return this._intersectedActors;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "leftBorderIntersectedActors", {
- get: function () {
- return this._borderIntersecteddActors[0];
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "bottomBorderIntersectedActors", {
- get: function () {
- return this._borderIntersecteddActors[1];
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "rightBorderIntersectedActors", {
- get: function () {
- return this._borderIntersecteddActors[2];
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "topBorderIntersectedActors", {
- get: function () {
- return this._borderIntersecteddActors[3];
- },
- enumerable: true,
- configurable: true
- });
- BasicPrimitiveCollisionManager.prototype._initializeCluster = function (countW, countH) {
- // Check for free
- if (this._clusters) {
- for (var w = 0; w < this._clusterSize.height; w++) {
- for (var h = 0; h < this._clusterSize.width; h++) {
- this._freeClusterInfo(this._clusters[w][h]);
- }
- }
- }
- // Allocate
- this._clusterSize.copyFromFloats(countW, countH);
- this._clusters = [];
- for (var w = 0; w < this._clusterSize.height; w++) {
- this._clusters[w] = [];
- for (var h = 0; h < this._clusterSize.width; h++) {
- var ci = this._allocClusterInfo();
- this._clusters[w][h] = ci;
- }
- }
- this._clusterStep.copyFromFloats(this._owner.actualWidth / countW, this._owner.actualHeight / countH);
- this._maxActorByCluster = 0;
- this._lastClusterResizeCounter = 0;
- this._clusterDirty = false;
- };
- BasicPrimitiveCollisionManager.prototype._rebuildAllActors = function () {
- var _this = this;
- this._actors.forEach(function (k, ai) {
- _this._processActor(ai);
- });
- };
- BasicPrimitiveCollisionManager.prototype._rebuildDirtyActors = function () {
- var _this = this;
- this._dirtyActors.forEach(function (k, ai) {
- _this._processActor(ai);
- });
- };
- BasicPrimitiveCollisionManager.prototype._processActor = function (actor) {
- var _this = this;
- // Check if the actor is being disabled or removed
- if (!actor.isEnabled || actor.isRemoved) {
- actor.presentInClusters.forEach(function (k, ci) {
- ci.actors.remove(actor.prim.uid);
- });
- actor.presentInClusters.clear();
- return;
- }
- var wab = actor.worldAABB;
- // Build the worldAABB corners
- var wac = BasicPrimitiveCollisionManager.WAABBCorners;
- wac[0].copyFromFloats(wab.x, wab.y); // Bottom/Left
- wac[1].copyFromFloats(wab.z, wab.y); // Bottom/Right
- wac[2].copyFromFloats(wab.z, wab.w); // Top/Right
- wac[3].copyFromFloats(wab.x, wab.w); // Top/Left
- var cs = this._clusterStep;
- var wacc = BasicPrimitiveCollisionManager.WAABBCornersCluster;
- for (var i = 0; i < 4; i++) {
- var p = wac[i];
- var cx = (p.x - (p.x % cs.x)) / cs.x;
- var cy = (p.y - (p.y % cs.y)) / cs.y;
- wacc[i].copyFromFloats(Math.floor(cx), Math.floor(cy));
- }
- var opCount = 0;
- var totalClusters = 0;
- var newCI = new Array();
- var sx = Math.max(0, wacc[0].x); // Start Cluster X
- var sy = Math.max(0, wacc[0].y); // Start Cluster Y
- var ex = Math.min(this._clusterSize.width - 1, wacc[2].x); // End Cluster X
- var ey = Math.min(this._clusterSize.height - 1, wacc[2].y); // End Cluster Y
- if (this._enableBorder) {
- if (wac[0].x < 0) {
- this._borderIntersecteddActors[0].add(actor.prim.uid, actor.prim);
- }
- else {
- this._borderIntersecteddActors[0].remove(actor.prim.uid);
- }
- if (wac[0].y < 0) {
- this._borderIntersecteddActors[1].add(actor.prim.uid, actor.prim);
- }
- else {
- this._borderIntersecteddActors[1].remove(actor.prim.uid);
- }
- if (wac[2].x >= this._canvasSize.width) {
- this._borderIntersecteddActors[2].add(actor.prim.uid, actor.prim);
- }
- else {
- this._borderIntersecteddActors[2].remove(actor.prim.uid);
- }
- if (wac[2].y >= this._canvasSize.height) {
- this._borderIntersecteddActors[3].add(actor.prim.uid, actor.prim);
- }
- else {
- this._borderIntersecteddActors[3].remove(actor.prim.uid);
- }
- }
- for (var y = sy; y <= ey; y++) {
- var _loop_1 = function (x) {
- var k = x + ":" + y;
- var cx = x, cy = y;
- var ci = actor.presentInClusters.getOrAddWithFactory(k, function (k) {
- var nci = _this._getCluster(cx, cy);
- nci.actors.add(actor.prim.uid, actor);
- _this._maxActorByCluster = Math.max(_this._maxActorByCluster, nci.actors.count);
- ++opCount;
- ++totalClusters;
- return nci;
- });
- newCI.push(ci);
- };
- for (var x = sx; x <= ex; x++) {
- _loop_1(x);
- }
- }
- // Check if there were no change
- if (opCount === 0 && actor.presentInClusters.count === totalClusters) {
- return;
- }
- // Build the array of the cluster where the actor is no longer in
- var clusterToRemove = new Array();
- actor.presentInClusters.forEach(function (k, ci) {
- if (newCI.indexOf(ci) === -1) {
- clusterToRemove.push(k);
- // remove the primitive from the Cluster Info object
- ci.actors.remove(actor.prim.uid);
- }
- });
- // Remove these clusters from the actor's dictionary
- for (var _i = 0, clusterToRemove_1 = clusterToRemove; _i < clusterToRemove_1.length; _i++) {
- var key = clusterToRemove_1[_i];
- actor.presentInClusters.remove(key);
- }
- };
- // 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.
- // Then for a given Actor that is dirty we evaluate the intersection with all the other actors present in the same Cluster(s)
- // So it's basically O(n²), BUT only inside a Cluster and only for dirty Actors.
- BasicPrimitiveCollisionManager.prototype._collisionDetection = function () {
- var _this = this;
- var hash = BasicPrimitiveCollisionManager.CandidatesActors;
- var prev = BasicPrimitiveCollisionManager.PreviousIntersections;
- var opCount = 0;
- this._dirtyActors.forEach(function (k1, ai1) {
- ++opCount;
- // Build the list of candidates
- hash.clear();
- ai1.presentInClusters.forEach(function (k, ci) {
- ++opCount;
- ci.actors.forEach(function (k, v) { return hash.add(k, v); });
- });
- var wab1 = ai1.worldAABB;
- // Save the previous intersections
- prev.clear();
- prev.copyFrom(ai1.intersectWith);
- ai1.intersectWith.clear();
- // For each candidate
- hash.forEach(function (k2, ai2) {
- ++opCount;
- // Check if we're testing against itself
- if (k1 === k2) {
- return;
- }
- var wab2 = ai2.worldAABB;
- if (wab2.z >= wab1.x && wab2.x <= wab1.z && wab2.w >= wab1.y && wab2.y <= wab1.w) {
- if (ai1.prim.intersectOtherPrim(ai2.prim)) {
- ++opCount;
- ai1.intersectWith.add(k2, ai2);
- if (k1 < k2) {
- _this._intersectedActors.add(k1 + ";" + k2, { a: ai1.prim, b: ai2.prim });
- }
- else {
- _this._intersectedActors.add(k2 + ";" + k1, { a: ai2.prim, b: ai1.prim });
- }
- }
- }
- });
- // Check and remove the associations that no longer exist in the main intersection list
- prev.forEach(function (k, ai) {
- if (!ai1.intersectWith.contains(k)) {
- ++opCount;
- _this._intersectedActors.remove((k < k1 ? k : k1) + ";" + (k < k1 ? k1 : k));
- }
- });
- });
- this._debugUpdateOpCount.fetchNewFrame();
- this._debugUpdateOpCount.addCount(opCount, true);
- };
- BasicPrimitiveCollisionManager.prototype._getCluster = function (x, y) {
- return this._clusters[x][y];
- };
- BasicPrimitiveCollisionManager.prototype._updateDebugStats = function () {
- var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
- var txt = "Primitive Collision Stats\n" +
- (" - PCM Execution Time: " + format(this._debugUpdateTime.lastSecAverage) + "ms\n") +
- (" - Operation Count: " + format(this._debugUpdateOpCount.current) + ", (avg:" + format(this._debugUpdateOpCount.lastSecAverage) + ", t:" + format(this._debugUpdateOpCount.total) + ")\n") +
- (" - Max Actor per Cluster: " + this._maxActorByCluster + "\n") +
- (" - Intersections count: " + this.intersectedActors.count);
- if (!this._debugTextBackground) {
- this._debugTextBackground = new BABYLON.Rectangle2D({
- id: "###DEBUG PMC STATS###", parent: this._owner, marginAlignment: "h: left, v: top", fill: "#C0404080", padding: "10", margin: "10", roundRadius: 10, children: [
- new BABYLON.Text2D(txt, { id: "###DEBUG PMC TEXT###", fontName: "12pt Lucida Console" })
- ]
- });
- }
- else {
- this._debugTextBackground.levelVisible = true;
- var text2d = this._debugTextBackground.children[0];
- text2d.text = txt;
- }
- };
- BasicPrimitiveCollisionManager.prototype._updateAABBDisplay = function () {
- var g = new BABYLON.WireFrameGroup2D("main", new BABYLON.Color4(0.5, 0.8, 1.0, 1.0));
- var v = BABYLON.Vector2.Zero();
- this._actors.forEach(function (k, ai) {
- if (ai.isEnabled) {
- var ab = ai.worldAABB;
- v.x = ab.x;
- v.y = ab.y;
- g.startLineStrip(v);
- v.x = ab.z;
- g.pushVertex(v);
- v.y = ab.w;
- g.pushVertex(v);
- v.x = ab.x;
- g.pushVertex(v);
- v.y = ab.y;
- g.endLineStrip(v);
- }
- });
- if (!this._AABBRenderPrim) {
- this._AABBRenderPrim = new BABYLON.WireFrame2D([g], { parent: this._owner, alignToPixel: true, id: "###DEBUG PCM AABB###" });
- }
- else {
- this._AABBRenderPrim.wireFrameGroups.set("main", g);
- this._AABBRenderPrim.wireFrameGroupsDirty();
- }
- this._debugRenderAABBDirty = false;
- };
- BasicPrimitiveCollisionManager.prototype._updateClusterDisplay = function (cw, ch) {
- var g = new BABYLON.WireFrameGroup2D("main", new BABYLON.Color4(0.8, 0.1, 0.5, 1.0));
- var v1 = BABYLON.Vector2.Zero();
- var v2 = BABYLON.Vector2.Zero();
- // Vertical lines
- var step = (this._owner.actualWidth - 1) / cw;
- v1.y = 0;
- v2.y = this._owner.actualHeight;
- for (var x = 0; x <= cw; x++) {
- g.pushVertex(v1);
- g.pushVertex(v2);
- v1.x += step;
- v2.x += step;
- }
- // Horizontal lines
- step = (this._owner.actualHeight - 1) / ch;
- v1.x = v1.y = v2.y = 0;
- v2.x = this._owner.actualWidth;
- for (var y = 0; y <= ch; y++) {
- g.pushVertex(v1);
- g.pushVertex(v2);
- v1.y += step;
- v2.y += step;
- }
- if (!this._ClusterRenderPrim) {
- this._ClusterRenderPrim = new BABYLON.WireFrame2D([g], { parent: this._owner, alignToPixel: true, id: "###DEBUG PCM Clusters###" });
- }
- else {
- this._ClusterRenderPrim.wireFrameGroups.set("main", g);
- this._ClusterRenderPrim.wireFrameGroupsDirty();
- }
- };
- // 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
- // ClusterInfo object and we have two method to allocate/free them. This way we always deal with the same objects.
- // The free array never shrink, always grows...For the better...and the worst!
- BasicPrimitiveCollisionManager.prototype._allocClusterInfo = function () {
- if (this._freeClusters.length === 0) {
- for (var i = 0; i < 8; i++) {
- this._freeClusters.push(new ClusterInfo());
- }
- }
- return this._freeClusters.pop();
- };
- BasicPrimitiveCollisionManager.prototype._freeClusterInfo = function (ci) {
- ci.clear();
- this._freeClusters.push(ci);
- };
- return BasicPrimitiveCollisionManager;
- }(PrimitiveCollisionManagerBase));
- BasicPrimitiveCollisionManager.WAABBCorners = null;
- BasicPrimitiveCollisionManager.WAABBCornersCluster = null;
- BasicPrimitiveCollisionManager.CandidatesActors = new BABYLON.StringDictionary();
- BasicPrimitiveCollisionManager.PreviousIntersections = new BABYLON.StringDictionary();
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.primitiveCollisionManager.js.map
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var LayoutEngineBase = (function () {
- function LayoutEngineBase() {
- this.layoutDirtyOnPropertyChangedMask = 0;
- }
- LayoutEngineBase.prototype.updateLayout = function (prim) {
- };
- Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
- get: function () {
- return false;
- },
- enumerable: true,
- configurable: true
- });
- LayoutEngineBase.prototype.isLocked = function () {
- return this._isLocked;
- };
- LayoutEngineBase.prototype.lock = function () {
- if (this._isLocked) {
- return false;
- }
- this._isLocked = true;
- return true;
- };
- return LayoutEngineBase;
- }());
- LayoutEngineBase = __decorate([
- BABYLON.className("LayoutEngineBase", "BABYLON")
- /**
- * This is the base class you have to extend in order to implement your own Layout Engine.
- * Note that for performance reason, each different Layout Engine type can be exposed as one/many singleton or must be instanced each time.
- * If data has to be associated to a given primitive you can use the SmartPropertyPrim.addExternalData API to do it.
- */
- ], LayoutEngineBase);
- BABYLON.LayoutEngineBase = LayoutEngineBase;
- var CanvasLayoutEngine = CanvasLayoutEngine_1 = (function (_super) {
- __extends(CanvasLayoutEngine, _super);
- function CanvasLayoutEngine() {
- var _this = _super.call(this) || this;
- _this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId | BABYLON.Prim2DBase.actualSizeProperty.flagId;
- return _this;
- }
- Object.defineProperty(CanvasLayoutEngine, "Singleton", {
- get: function () {
- if (!CanvasLayoutEngine_1._singleton) {
- CanvasLayoutEngine_1._singleton = new CanvasLayoutEngine_1();
- }
- return CanvasLayoutEngine_1._singleton;
- },
- enumerable: true,
- configurable: true
- });
- // A very simple (no) layout computing...
- // The Canvas and its direct children gets the Canvas' size as Layout Area
- // Indirect children have their Layout Area to the actualSize (margin area) of their parent
- CanvasLayoutEngine.prototype.updateLayout = function (prim) {
- // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
- if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
- prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
- for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
- var child = _a[_i];
- this._doUpdate(child);
- }
- }
- };
- CanvasLayoutEngine.prototype._doUpdate = function (prim) {
- // Canvas ?
- if (prim instanceof BABYLON.Canvas2D) {
- prim.layoutArea = prim.actualSize; //.multiplyByFloats(prim.scaleX, prim.scaleY);
- }
- else if (prim.parent instanceof BABYLON.Canvas2D) {
- prim.layoutArea = prim.owner.actualSize; //.multiplyByFloats(prim.owner.scaleX, prim.owner.scaleY);
- }
- else {
- var contentArea = prim.parent.contentArea;
- // Can be null if the parent's content area depend of its children, the computation will be done in many passes
- if (contentArea) {
- prim.layoutArea = contentArea;
- }
- }
- BABYLON.C2DLogging.setPostMessage(function () { return "Prim: " + prim.id + " has layoutArea: " + prim.layoutArea; });
- };
- Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
- get: function () {
- return true;
- },
- enumerable: true,
- configurable: true
- });
- return CanvasLayoutEngine;
- }(LayoutEngineBase));
- CanvasLayoutEngine._singleton = null;
- __decorate([
- BABYLON.logMethod()
- ], CanvasLayoutEngine.prototype, "updateLayout", null);
- __decorate([
- BABYLON.logMethod()
- ], CanvasLayoutEngine.prototype, "_doUpdate", null);
- CanvasLayoutEngine = CanvasLayoutEngine_1 = __decorate([
- BABYLON.className("CanvasLayoutEngine", "BABYLON")
- /**
- * The default Layout Engine, primitive are positioning into a Canvas, using their x/y coordinates.
- * This layout must be used as a Singleton through the CanvasLayoutEngine.Singleton property.
- */
- ], CanvasLayoutEngine);
- BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
- var StackPanelLayoutEngine = StackPanelLayoutEngine_1 = (function (_super) {
- __extends(StackPanelLayoutEngine, _super);
- function StackPanelLayoutEngine() {
- var _this = _super.call(this) || this;
- _this._isHorizontal = true;
- _this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId | BABYLON.Prim2DBase.actualSizeProperty.flagId;
- return _this;
- }
- Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
- get: function () {
- if (!StackPanelLayoutEngine_1._horizontal) {
- StackPanelLayoutEngine_1._horizontal = new StackPanelLayoutEngine_1();
- StackPanelLayoutEngine_1._horizontal.isHorizontal = true;
- StackPanelLayoutEngine_1._horizontal.lock();
- }
- return StackPanelLayoutEngine_1._horizontal;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
- get: function () {
- if (!StackPanelLayoutEngine_1._vertical) {
- StackPanelLayoutEngine_1._vertical = new StackPanelLayoutEngine_1();
- StackPanelLayoutEngine_1._vertical.isHorizontal = false;
- StackPanelLayoutEngine_1._vertical.lock();
- }
- return StackPanelLayoutEngine_1._vertical;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
- get: function () {
- return this._isHorizontal;
- },
- set: function (val) {
- if (this.isLocked()) {
- return;
- }
- this._isHorizontal = val;
- },
- enumerable: true,
- configurable: true
- });
- StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
- if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
- var primLayoutArea = prim.layoutArea;
- var isSizeAuto = prim.isSizeAuto;
- // If we're not in autoSize the layoutArea of the prim having the stack panel must be computed in order for us to compute the children' position.
- // If there's at least one auto size (Horizontal or Vertical) we will have to figure the layoutArea ourselves
- if (!primLayoutArea && !isSizeAuto) {
- return;
- }
- // console.log("Compute Stack Panel Layout " + ++StackPanelLayoutEngine.computeCounter);
- var x = 0;
- var y = 0;
- var horizonStackPanel = this.isHorizontal;
- // If the stack panel is horizontal we check if the primitive height is auto or not, if it's auto then we have to compute the required height, otherwise we just take the actualHeight. If the stack panel is vertical we do the same but with width
- var max = 0;
- var stackPanelLayoutArea = StackPanelLayoutEngine_1.stackPanelLayoutArea;
- if (horizonStackPanel) {
- if (prim.isVerticalSizeAuto) {
- max = 0;
- stackPanelLayoutArea.height = 0;
- }
- else {
- max = prim.layoutArea.height;
- stackPanelLayoutArea.height = prim.layoutArea.height;
- stackPanelLayoutArea.width = 0;
- }
- }
- else {
- if (prim.isHorizontalSizeAuto) {
- max = 0;
- stackPanelLayoutArea.width = 0;
- }
- else {
- max = prim.layoutArea.width;
- stackPanelLayoutArea.width = prim.layoutArea.width;
- stackPanelLayoutArea.height = 0;
- }
- }
- for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
- var child = _a[_i];
- if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
- continue;
- }
- if (child._hasMargin) {
- // Calling computeWithAlignment will return us the area taken by "child" which is its layoutArea
- // We also have the dstOffset which will give us the y position in horizontal mode or x position in vertical mode.
- // The alignment offset on the other axis is simply ignored as it doesn't make any sense (e.g. horizontal alignment is ignored in horizontal mode)
- child.margin.computeWithAlignment(stackPanelLayoutArea, child.actualSize, child.marginAlignment, child.actualScale, StackPanelLayoutEngine_1.dstOffset, StackPanelLayoutEngine_1.dstArea, true);
- child.layoutArea = StackPanelLayoutEngine_1.dstArea;
- }
- else {
- child.margin.computeArea(child.actualSize, child.actualScale, StackPanelLayoutEngine_1.dstArea);
- child.layoutArea = StackPanelLayoutEngine_1.dstArea;
- }
- max = Math.max(max, horizonStackPanel ? StackPanelLayoutEngine_1.dstArea.height : StackPanelLayoutEngine_1.dstArea.width);
- }
- for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
- var child = _c[_b];
- if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
- continue;
- }
- var layoutArea = child.layoutArea;
- if (horizonStackPanel) {
- child.layoutAreaPos = new BABYLON.Vector2(x, 0);
- x += layoutArea.width;
- child.layoutArea = new BABYLON.Size(layoutArea.width, max);
- }
- else {
- child.layoutAreaPos = new BABYLON.Vector2(0, y);
- y += layoutArea.height;
- child.layoutArea = new BABYLON.Size(max, layoutArea.height);
- }
- }
- prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
- }
- };
- Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
- get: function () {
- return false;
- },
- enumerable: true,
- configurable: true
- });
- return StackPanelLayoutEngine;
- }(LayoutEngineBase));
- StackPanelLayoutEngine._horizontal = null;
- StackPanelLayoutEngine._vertical = null;
- StackPanelLayoutEngine.stackPanelLayoutArea = BABYLON.Size.Zero();
- StackPanelLayoutEngine.dstOffset = BABYLON.Vector4.Zero();
- StackPanelLayoutEngine.dstArea = BABYLON.Size.Zero();
- StackPanelLayoutEngine.computeCounter = 0;
- StackPanelLayoutEngine = StackPanelLayoutEngine_1 = __decorate([
- BABYLON.className("StackPanelLayoutEngine", "BABYLON")
- /**
- * A stack panel layout. Primitive will be stack either horizontally or vertically.
- * This Layout type must be used as a Singleton, use the StackPanelLayoutEngine.Horizontal for an horizontal stack panel or StackPanelLayoutEngine.Vertical for a vertical one.
- */
- ], StackPanelLayoutEngine);
- BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
- /**
- * GridData is used specify what row(s) and column(s) a primitive is placed in when its parent is using a Grid Panel Layout.
- */
- var GridData = (function () {
- /**
- * Create a Grid Data that describes where a primitive will be placed in a Grid Panel Layout.
- * @param row the row number of the grid
- * @param column the column number of the grid
- * @param rowSpan the number of rows a primitive will occupy
- * @param columnSpan the number of columns a primitive will occupy
- **/
- function GridData(row, column, rowSpan, columnSpan) {
- this.row = row;
- this.column = column;
- this.rowSpan = (rowSpan == null) ? 1 : rowSpan;
- this.columnSpan = (columnSpan == null) ? 1 : columnSpan;
- }
- return GridData;
- }());
- BABYLON.GridData = GridData;
- var GridDimensionDefinition = (function () {
- function GridDimensionDefinition() {
- }
- GridDimensionDefinition.prototype._parse = function (value, res) {
- var v = value.toLocaleLowerCase().trim();
- if (v.indexOf("auto") === 0) {
- res(null, null, GridDimensionDefinition.Auto);
- }
- else if (v.indexOf("*") !== -1) {
- var i = v.indexOf("*");
- var w = 1;
- if (i > 0) {
- w = parseFloat(v.substr(0, i));
- }
- res(w, null, GridDimensionDefinition.Stars);
- }
- else {
- var w = parseFloat(v);
- res(w, w, GridDimensionDefinition.Pixels);
- }
- };
- return GridDimensionDefinition;
- }());
- GridDimensionDefinition.Pixels = 1;
- GridDimensionDefinition.Stars = 2;
- GridDimensionDefinition.Auto = 3;
- var RowDefinition = (function (_super) {
- __extends(RowDefinition, _super);
- function RowDefinition() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- return RowDefinition;
- }(GridDimensionDefinition));
- var ColumnDefinition = (function (_super) {
- __extends(ColumnDefinition, _super);
- function ColumnDefinition() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- return ColumnDefinition;
- }(GridDimensionDefinition));
- var GridPanelLayoutEngine = GridPanelLayoutEngine_1 = (function (_super) {
- __extends(GridPanelLayoutEngine, _super);
- function GridPanelLayoutEngine(settings) {
- var _this = _super.call(this) || this;
- _this._children = [];
- _this._rowBottoms = [];
- _this._columnLefts = [];
- _this._rowHeights = [];
- _this._columnWidths = [];
- _this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId | BABYLON.Prim2DBase.actualSizeProperty.flagId;
- _this._rows = new Array();
- _this._columns = new Array();
- if (settings.rows) {
- var _loop_1 = function (row) {
- var r = new RowDefinition();
- r._parse(row.height, function (v, vp, t) {
- r.height = v;
- r.heightPixels = vp;
- r.heightType = t;
- });
- this_1._rows.push(r);
- };
- var this_1 = this;
- for (var _i = 0, _a = settings.rows; _i < _a.length; _i++) {
- var row = _a[_i];
- _loop_1(row);
- }
- }
- if (settings.columns) {
- var _loop_2 = function (col) {
- var r = new ColumnDefinition();
- r._parse(col.width, function (v, vp, t) {
- r.width = v;
- r.widthPixels = vp;
- r.widthType = t;
- });
- this_2._columns.push(r);
- };
- var this_2 = this;
- for (var _b = 0, _c = settings.columns; _b < _c.length; _b++) {
- var col = _c[_b];
- _loop_2(col);
- }
- }
- return _this;
- }
- GridPanelLayoutEngine.prototype.updateLayout = function (prim) {
- if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
- if (!prim.layoutArea) {
- return;
- }
- for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
- var child = _a[_i];
- if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
- continue;
- }
- if (child._hasMargin) {
- child.margin.computeWithAlignment(prim.layoutArea, child.actualSize, child.marginAlignment, child.actualScale, GridPanelLayoutEngine_1.dstOffset, GridPanelLayoutEngine_1.dstArea, true);
- }
- else {
- child.margin.computeArea(child.actualSize, child.actualScale, GridPanelLayoutEngine_1.dstArea);
- }
- child.layoutArea = GridPanelLayoutEngine_1.dstArea;
- }
- this._updateGrid(prim);
- var _children = this._children;
- var rl = this._rows.length;
- var cl = this._columns.length;
- var columnWidth = 0;
- var rowHeight = 0;
- var dstArea = GridPanelLayoutEngine_1.dstArea;
- var dstAreaPos = GridPanelLayoutEngine_1.dstAreaPos;
- for (var i = 0; i < _children.length; i++) {
- var children = _children[i];
- if (children) {
- var bottom = this._rowBottoms[i];
- var rowHeight_1 = this._rowHeights[i];
- var oBottom = bottom;
- var oRowHeight = rowHeight_1;
- for (var j = 0; j < children.length; j++) {
- var left = this._columnLefts[j];
- var columnWidth_1 = this._columnWidths[j];
- var child = children[j];
- if (child) {
- var gd = child.layoutData;
- if (gd.columnSpan > 1) {
- for (var k = j + 1; k < gd.columnSpan + j && k < cl; k++) {
- columnWidth_1 += this._columnWidths[k];
- }
- }
- if (gd.rowSpan > 1) {
- for (var k = i + 1; k < gd.rowSpan + i && k < rl; k++) {
- rowHeight_1 += this._rowHeights[k];
- bottom = this._rowBottoms[k];
- }
- }
- dstArea.width = columnWidth_1;
- dstArea.height = rowHeight_1;
- child.layoutArea = dstArea;
- dstAreaPos.x = left;
- dstAreaPos.y = bottom;
- child.layoutAreaPos = dstAreaPos;
- bottom = oBottom;
- rowHeight_1 = oRowHeight;
- }
- }
- }
- }
- prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
- }
- };
- Object.defineProperty(GridPanelLayoutEngine.prototype, "isChildPositionAllowed", {
- get: function () {
- return false;
- },
- enumerable: true,
- configurable: true
- });
- GridPanelLayoutEngine.prototype._getMaxChildHeightInRow = function (rowNum) {
- var rows = this._rows;
- var cl = this._columns.length;
- var rl = this._rows.length;
- var children = this._children;
- var row = rows[rowNum];
- var maxHeight = 0;
- if (children && children[rowNum]) {
- for (var i = 0; i < cl; i++) {
- var child = children[rowNum][i];
- if (child) {
- var span = child.layoutData.rowSpan;
- if (maxHeight < child.layoutArea.height / span) {
- maxHeight = child.layoutArea.height / span;
- }
- }
- }
- }
- return maxHeight;
- };
- GridPanelLayoutEngine.prototype._getMaxChildWidthInColumn = function (colNum) {
- var columns = this._columns;
- var cl = this._columns.length;
- var rl = this._rows.length;
- var children = this._children;
- var column = columns[colNum];
- var maxWidth = 0;
- if (children) {
- for (var i = 0; i < rl; i++) {
- if (children[i]) {
- var child = children[i][colNum];
- if (child) {
- var span = child.layoutData.columnSpan;
- if (maxWidth < child.layoutArea.width / span) {
- maxWidth = child.layoutArea.width / span;
- }
- }
- }
- }
- }
- return maxWidth;
- };
- GridPanelLayoutEngine.prototype._updateGrid = function (prim) {
- var _children = this._children;
- //remove prim.children from _children
- for (var i_1 = 0; i_1 < _children.length; i_1++) {
- var children = _children[i_1];
- if (children) {
- children.length = 0;
- }
- }
- var childrenThatSpan;
- //add prim.children to _children
- for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
- var child = _a[_i];
- if (!child.layoutData) {
- continue;
- }
- var gd = child.layoutData;
- if (!_children[gd.row]) {
- _children[gd.row] = [];
- }
- if (gd.columnSpan == 1 && gd.rowSpan == 1) {
- _children[gd.row][gd.column] = child;
- }
- else {
- if (!childrenThatSpan) {
- childrenThatSpan = [];
- }
- //when children span, we need to add them to _children whereever they span to so that
- //_getMaxChildHeightInRow and _getMaxChildWidthInColumn will work correctly.
- childrenThatSpan.push(child);
- for (var i_2 = gd.row; i_2 < gd.row + gd.rowSpan; i_2++) {
- for (var j = gd.column; j < gd.column + gd.columnSpan; j++) {
- _children[i_2][j] = child;
- }
- }
- }
- }
- var rows = this._rows;
- var columns = this._columns;
- var rl = this._rows.length;
- var cl = this._columns.length;
- //get fixed and auto row heights first
- var starIndexes = [];
- var totalStars = 0;
- var rowHeights = 0;
- var columnWidths = 0;
- for (var i_3 = 0; i_3 < rl; i_3++) {
- var row = this._rows[i_3];
- if (row.heightType == GridDimensionDefinition.Auto) {
- this._rowHeights[i_3] = this._getMaxChildHeightInRow(i_3);
- rowHeights += this._rowHeights[i_3];
- }
- else if (row.heightType == GridDimensionDefinition.Pixels) {
- var maxChildHeight = this._getMaxChildHeightInRow(i_3);
- this._rowHeights[i_3] = Math.max(row.heightPixels, maxChildHeight);
- rowHeights += this._rowHeights[i_3];
- }
- else if (row.heightType == GridDimensionDefinition.Stars) {
- starIndexes.push(i_3);
- totalStars += row.height;
- }
- }
- //star row heights
- if (starIndexes.length > 0) {
- var remainingHeight = prim.contentArea.height - rowHeights;
- for (var i_4 = 0; i_4 < starIndexes.length; i_4++) {
- var rowIndex = starIndexes[i_4];
- var starHeight = (this._rows[rowIndex].height / totalStars) * remainingHeight;
- var maxChildHeight = this._getMaxChildHeightInRow(i_4);
- this._rowHeights[rowIndex] = Math.max(starHeight, maxChildHeight);
- }
- }
- //get fixed and auto column widths
- starIndexes.length = 0;
- totalStars = 0;
- for (var i_5 = 0; i_5 < cl; i_5++) {
- var column = this._columns[i_5];
- if (column.widthType == GridDimensionDefinition.Auto) {
- this._columnWidths[i_5] = this._getMaxChildWidthInColumn(i_5);
- columnWidths += this._columnWidths[i_5];
- }
- else if (column.widthType == GridDimensionDefinition.Pixels) {
- var maxChildWidth = this._getMaxChildWidthInColumn(i_5);
- this._columnWidths[i_5] = Math.max(column.widthPixels, maxChildWidth);
- columnWidths += this._columnWidths[i_5];
- }
- else if (column.widthType == GridDimensionDefinition.Stars) {
- starIndexes.push(i_5);
- totalStars += column.width;
- }
- }
- //star column widths
- if (starIndexes.length > 0) {
- var remainingWidth = prim.contentArea.width - columnWidths;
- for (var i_6 = 0; i_6 < starIndexes.length; i_6++) {
- var columnIndex = starIndexes[i_6];
- var starWidth = (this._columns[columnIndex].width / totalStars) * remainingWidth;
- var maxChildWidth = this._getMaxChildWidthInColumn(i_6);
- this._columnWidths[columnIndex] = Math.max(starWidth, maxChildWidth);
- }
- }
- var y = 0;
- this._rowBottoms[rl - 1] = y;
- for (var i_7 = rl - 2; i_7 >= 0; i_7--) {
- y += this._rowHeights[i_7 + 1];
- this._rowBottoms[i_7] = y;
- }
- var x = 0;
- this._columnLefts[0] = x;
- for (var i_8 = 1; i_8 < cl; i_8++) {
- x += this._columnWidths[i_8 - 1];
- this._columnLefts[i_8] = x;
- }
- //remove duplicate references to children that span
- if (childrenThatSpan) {
- for (var i = 0; i < childrenThatSpan.length; i++) {
- var child = childrenThatSpan[i];
- var gd = child.layoutData;
- for (var i_9 = gd.row; i_9 < gd.row + gd.rowSpan; i_9++) {
- for (var j = gd.column; j < gd.column + gd.columnSpan; j++) {
- if (i_9 == gd.row && j == gd.column) {
- continue;
- }
- if (_children[i_9][j] == child) {
- _children[i_9][j] = null;
- }
- }
- }
- }
- }
- };
- return GridPanelLayoutEngine;
- }(LayoutEngineBase));
- GridPanelLayoutEngine.dstOffset = BABYLON.Vector4.Zero();
- GridPanelLayoutEngine.dstArea = BABYLON.Size.Zero();
- GridPanelLayoutEngine.dstAreaPos = BABYLON.Vector2.Zero();
- GridPanelLayoutEngine = GridPanelLayoutEngine_1 = __decorate([
- BABYLON.className("GridPanelLayoutEngine", "BABYLON")
- /**
- * A grid panel layout. Grid panel is a table that has rows and columns.
- * When adding children to a primitive that is using grid panel layout, you must assign a GridData object to the child to indicate where the child will appear in the grid.
- */
- ], GridPanelLayoutEngine);
- BABYLON.GridPanelLayoutEngine = GridPanelLayoutEngine;
- var CanvasLayoutEngine_1, StackPanelLayoutEngine_1, GridPanelLayoutEngine_1;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.canvas2dLayoutEngine.js.map
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- /**
- * Base class implementing the ILocable interface.
- * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
- */
- var LockableBase = (function () {
- function LockableBase() {
- }
- LockableBase.prototype.isLocked = function () {
- return this._isLocked;
- };
- LockableBase.prototype.lock = function () {
- if (this._isLocked) {
- return true;
- }
- this.onLock();
- this._isLocked = true;
- return false;
- };
- /**
- * Protected handler that will be called when the instance is about to be locked.
- */
- LockableBase.prototype.onLock = function () {
- };
- return LockableBase;
- }());
- BABYLON.LockableBase = LockableBase;
- var SolidColorBrush2D = (function (_super) {
- __extends(SolidColorBrush2D, _super);
- function SolidColorBrush2D(color, lock) {
- if (lock === void 0) { lock = false; }
- var _this = _super.call(this) || this;
- _this._color = color;
- if (lock) {
- {
- _this.lock();
- }
- }
- return _this;
- }
- /**
- * Return true if the brush is transparent, false if it's totally opaque
- */
- SolidColorBrush2D.prototype.isTransparent = function () {
- return this._color && this._color.a < 1.0;
- };
- Object.defineProperty(SolidColorBrush2D.prototype, "color", {
- /**
- * The color used by this instance to render
- * @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.
- */
- get: function () {
- return this._color;
- },
- set: function (value) {
- if (this.isLocked()) {
- return;
- }
- this._color = value;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
- */
- SolidColorBrush2D.prototype.toString = function () {
- return this._color.toHexString();
- };
- return SolidColorBrush2D;
- }(LockableBase));
- SolidColorBrush2D = __decorate([
- BABYLON.className("SolidColorBrush2D", "BABYLON")
- /**
- * This class implements a Brush that will be drawn with a uniform solid color (i.e. the same color everywhere in the content where the brush is assigned to).
- */
- ], SolidColorBrush2D);
- BABYLON.SolidColorBrush2D = SolidColorBrush2D;
- var GradientColorBrush2D = (function (_super) {
- __extends(GradientColorBrush2D, _super);
- function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
- if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
- if (rotation === void 0) { rotation = 0; }
- if (scale === void 0) { scale = 1; }
- if (lock === void 0) { lock = false; }
- var _this = _super.call(this) || this;
- _this._color1 = color1;
- _this._color2 = color2;
- _this._translation = translation;
- _this._rotation = rotation;
- _this._scale = scale;
- if (lock) {
- _this.lock();
- }
- return _this;
- }
- /**
- * Return true if the brush is transparent, false if it's totally opaque
- */
- GradientColorBrush2D.prototype.isTransparent = function () {
- return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
- };
- Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
- /**
- * First color, the blend will start from this color
- */
- get: function () {
- return this._color1;
- },
- set: function (value) {
- if (this.isLocked()) {
- return;
- }
- this._color1 = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
- /**
- * Second color, the blend will end to this color
- */
- get: function () {
- return this._color2;
- },
- set: function (value) {
- if (this.isLocked()) {
- return;
- }
- this._color2 = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
- /**
- * Translation vector to apply on the blend
- * Default is [0;0]
- */
- get: function () {
- return this._translation;
- },
- set: function (value) {
- if (this.isLocked()) {
- return;
- }
- this._translation = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
- /**
- * Rotation in radian to apply to the brush
- * Default direction of the brush is vertical, you can change this using this property.
- * Default is 0.
- */
- get: function () {
- return this._rotation;
- },
- set: function (value) {
- if (this.isLocked()) {
- return;
- }
- this._rotation = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
- /**
- * Scale factor to apply to the gradient.
- * Default is 1: no scale.
- */
- get: function () {
- return this._scale;
- },
- set: function (value) {
- if (this.isLocked()) {
- return;
- }
- this._scale = value;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Return a string describing the brush
- */
- GradientColorBrush2D.prototype.toString = function () {
- return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
- };
- /**
- * Build a unique key string for the given parameters
- */
- GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
- return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
- };
- return GradientColorBrush2D;
- }(LockableBase));
- GradientColorBrush2D = __decorate([
- BABYLON.className("GradientColorBrush2D", "BABYLON")
- /**
- * This class implements a Gradient Color Brush, the brush color will blend from a first given color to a second one.
- */
- ], GradientColorBrush2D);
- BABYLON.GradientColorBrush2D = GradientColorBrush2D;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.brushes2d.js.map
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var Prim2DClassInfo = (function () {
- function Prim2DClassInfo() {
- }
- return Prim2DClassInfo;
- }());
- BABYLON.Prim2DClassInfo = Prim2DClassInfo;
- var Prim2DPropInfo = (function () {
- function Prim2DPropInfo() {
- }
- return Prim2DPropInfo;
- }());
- Prim2DPropInfo.PROPKIND_MODEL = 1;
- Prim2DPropInfo.PROPKIND_INSTANCE = 2;
- Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
- BABYLON.Prim2DPropInfo = Prim2DPropInfo;
- var ClassTreeInfo = (function () {
- function ClassTreeInfo(baseClass, type, classContentFactory) {
- this._baseClass = baseClass;
- this._type = type;
- this._subClasses = new Array();
- this._levelContent = new BABYLON.StringDictionary();
- this._classContentFactory = classContentFactory;
- }
- Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
- get: function () {
- if (!this._classContent) {
- this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
- }
- return this._classContent;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ClassTreeInfo.prototype, "type", {
- get: function () {
- return this._type;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
- get: function () {
- return this._levelContent;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
- get: function () {
- if (!this._fullContent) {
- var dic_1 = new BABYLON.StringDictionary();
- var curLevel = this;
- while (curLevel) {
- curLevel.levelContent.forEach(function (k, v) { return dic_1.add(k, v); });
- curLevel = curLevel._baseClass;
- }
- this._fullContent = dic_1;
- }
- return this._fullContent;
- },
- enumerable: true,
- configurable: true
- });
- ClassTreeInfo.prototype.getLevelOf = function (type) {
- // Are we already there?
- if (type === this._type) {
- return this;
- }
- var baseProto = Object.getPrototypeOf(type);
- var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
- if (!curProtoContent) {
- this.getLevelOf(baseProto);
- }
- return this.getOrAddType(baseProto, type);
- };
- ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
- // Are we at the level corresponding to the baseType?
- // If so, get or add the level we're looking for
- if (baseType === this._type) {
- for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
- var subType = _a[_i];
- if (subType.type === type) {
- return subType.node;
- }
- }
- var node = new ClassTreeInfo(this, type, this._classContentFactory);
- var info = { type: type, node: node };
- this._subClasses.push(info);
- return info.node;
- }
- // Recurse down to keep looking for the node corresponding to the baseTypeName
- for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
- var subType = _c[_b];
- var info = subType.node.getOrAddType(baseType, type);
- if (info) {
- return info;
- }
- }
- return null;
- };
- ClassTreeInfo.get = function (type) {
- var dic = type["__classTreeInfo"];
- if (!dic) {
- return null;
- }
- return dic.getLevelOf(type);
- };
- ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
- var dic = type["__classTreeInfo"];
- if (!dic) {
- dic = new ClassTreeInfo(null, type, classContentFactory);
- type["__classTreeInfo"] = dic;
- }
- return dic;
- };
- return ClassTreeInfo;
- }());
- BABYLON.ClassTreeInfo = ClassTreeInfo;
- var DataBinding = DataBinding_1 = (function () {
- function DataBinding() {
- this._converter = null;
- this._mode = DataBinding_1.MODE_DEFAULT;
- this._uiElementId = null;
- this._dataSource = null;
- this._currentDataSource = null;
- this._propertyPathName = null;
- this._stringFormat = null;
- this._updateSourceTrigger = DataBinding_1.UPDATESOURCETRIGGER_PROPERTYCHANGED;
- this._boundTo = null;
- this._owner = null;
- this._updateCounter = 0;
- }
- Object.defineProperty(DataBinding.prototype, "converter", {
- /**
- * Provide a callback that will convert the value obtained by the Data Binding to the type of the SmartProperty it's bound to.
- * If no value are set, then it's assumed that the sourceValue is of the same type as the SmartProperty's one.
- * 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.
- * @param sourceValue the source object retrieve by the Data Binding mechanism
- * @returns the object of a compatible type with the SmartProperty it's bound to
- */
- get: function () {
- return this._converter;
- },
- set: function (value) {
- if (this._converter === value) {
- return;
- }
- this._converter = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DataBinding.prototype, "mode", {
- /**
- * 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
- */
- get: function () {
- if (this._mode === DataBinding_1.MODE_DEFAULT) {
- return this._boundTo.bindingMode;
- }
- return this._mode;
- },
- set: function (value) {
- if (this._mode === value) {
- return;
- }
- this._mode = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DataBinding.prototype, "uiElementId", {
- /**
- * You can override the Data Source object with this member which is the Id of a uiElement existing in the UI Logical tree.
- * If not set and source no set too, then the dataSource property will be used.
- */
- get: function () {
- return this._uiElementId;
- },
- set: function (value) {
- if (this._uiElementId === value) {
- return;
- }
- this._uiElementId = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DataBinding.prototype, "dataSource", {
- /**
- * You can override the Data Source object with this member which is the source object to use directly.
- * If not set and uiElement no set too, then the dataSource property of the SmartPropertyBase object will be used.
- */
- get: function () {
- return this._dataSource;
- },
- set: function (value) {
- if (this._dataSource === value) {
- return;
- }
- this._dataSource = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DataBinding.prototype, "propertyPathName", {
- /**
- * The path & name of the property to get from the source object.
- * 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.
- * If nothing is set then the source object will be used.
- * 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.
- * 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.
- */
- get: function () {
- return this._propertyPathName;
- },
- set: function (value) {
- if (this._propertyPathName === value) {
- return;
- }
- if (this._owner) {
- //BindingWatcher.unregisterBinding(this, null);
- }
- this._propertyPathName = value;
- if (this._owner) {
- //let watched = BindingWatcher._getDataSource(this._owner.dataSource, this);
- //BindingWatcher.refreshBinding(watched, this._owner, this, true, null, true);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DataBinding.prototype, "stringFormat", {
- /**
- * 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}`
- */
- get: function () {
- return this._stringFormat;
- },
- set: function (value) {
- if (this._stringFormat === value) {
- return;
- }
- this._stringFormat = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DataBinding.prototype, "updateSourceTrigger", {
- /**
- * 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.
- */
- get: function () {
- return this._updateSourceTrigger;
- },
- set: function (value) {
- if (this._updateSourceTrigger === value) {
- return;
- }
- this._updateSourceTrigger = value;
- },
- enumerable: true,
- configurable: true
- });
- DataBinding.prototype.canUpdateTarget = function (resetUpdateCounter) {
- if (resetUpdateCounter) {
- this._updateCounter = 0;
- }
- var mode = this.mode;
- if (mode === DataBinding_1.MODE_ONETIME) {
- return this._updateCounter === 0;
- }
- if (mode === DataBinding_1.MODE_ONEWAYTOSOURCE) {
- return false;
- }
- return true;
- };
- DataBinding.prototype.updateTarget = function () {
- var value = this._getActualDataSource();
- var properties = this.propertyPathName.split(".");
- for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) {
- var propertyName = properties_1[_i];
- value = value[propertyName];
- }
- this._storeBoundValue(this._owner, value);
- };
- DataBinding.prototype._storeBoundValue = function (watcher, value) {
- if ((++this._updateCounter > 1) && (this.mode === DataBinding_1.MODE_ONETIME)) {
- return;
- }
- var newValue = value;
- if (this._converter) {
- newValue = this._converter(value);
- }
- if (this._stringFormat) {
- newValue = this._stringFormat(newValue);
- }
- watcher[this._boundTo.name] = newValue;
- };
- DataBinding.prototype._getActualDataSource = function () {
- if (this.dataSource) {
- return this.dataSource;
- }
- if (this.uiElementId) {
- // TODO Find UIElement
- return null;
- }
- return this._owner.dataSource;
- };
- DataBinding.prototype._registerDataSource = function (updateTarget) {
- var ds = this._getActualDataSource();
- if (ds === this._currentDataSource) {
- return;
- }
- if (this._currentDataSource) {
- BindingHelper.unregisterDataSource(this._currentDataSource, this, 0);
- }
- if (ds) {
- BindingHelper.registerDataSource(ds, this);
- if (updateTarget && this.canUpdateTarget(true)) {
- this.updateTarget();
- }
- }
- this._currentDataSource = ds;
- };
- DataBinding.prototype._unregisterDataSource = function () {
- var ds = this._getActualDataSource();
- if (ds) {
- BindingHelper.unregisterDataSource(ds, this, 0);
- }
- };
- return DataBinding;
- }());
- /**
- * Use the mode specified in the SmartProperty declaration
- */
- DataBinding.MODE_DEFAULT = 1;
- /**
- * Update the binding target only once when the Smart Property's value is first accessed
- */
- DataBinding.MODE_ONETIME = 2;
- /**
- * Update the smart property when the source changes.
- * The source won't be updated if the smart property value is set.
- */
- DataBinding.MODE_ONEWAY = 3;
- /**
- * Only update the source when the target's data is changing.
- */
- DataBinding.MODE_ONEWAYTOSOURCE = 4;
- /**
- * Update the bind target when the source changes and update the source when the Smart Property value is set.
- */
- DataBinding.MODE_TWOWAY = 5;
- /**
- * Use the Update Source Trigger defined in the SmartProperty declaration
- */
- DataBinding.UPDATESOURCETRIGGER_DEFAULT = 1;
- /**
- * Update the source as soon as the Smart Property has a value change
- */
- DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED = 2;
- /**
- * Update the source when the binding target loses focus
- */
- DataBinding.UPDATESOURCETRIGGER_LOSTFOCUS = 3;
- /**
- * Update the source will be made by explicitly calling the UpdateFromDataSource method
- */
- DataBinding.UPDATESOURCETRIGGER_EXPLICIT = 4;
- DataBinding = DataBinding_1 = __decorate([
- BABYLON.className("DataBinding", "BABYLON")
- ], DataBinding);
- BABYLON.DataBinding = DataBinding;
- var SmartPropertyBase = SmartPropertyBase_1 = (function (_super) {
- __extends(SmartPropertyBase, _super);
- function SmartPropertyBase() {
- var _this = _super.call(this) || this;
- _this._dataSource = null;
- _this._dataSourceObserver = null;
- _this._instanceDirtyFlags = 0;
- _this._isDisposed = false;
- _this._bindings = null;
- _this._hasBinding = 0;
- _this._bindingSourceChanged = 0;
- _this._disposeObservable = null;
- return _this;
- }
- Object.defineProperty(SmartPropertyBase.prototype, "disposeObservable", {
- get: function () {
- if (!this._disposeObservable) {
- this._disposeObservable = new BABYLON.Observable();
- }
- return this._disposeObservable;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SmartPropertyBase.prototype, "isDisposed", {
- /**
- * Check if the object is disposed or not.
- * @returns true if the object is dispose, false otherwise.
- */
- get: function () {
- return this._isDisposed;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
- * @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.
- */
- SmartPropertyBase.prototype.dispose = function () {
- if (this.isDisposed) {
- return false;
- }
- if (this._disposeObservable && this._disposeObservable.hasObservers()) {
- this._disposeObservable.notifyObservers(this);
- }
- this._isDisposed = true;
- return true;
- };
- /**
- * Check if a given set of properties are dirty or not.
- * @param flags a ORed combination of Prim2DPropInfo.flagId values
- * @return true if at least one property is dirty, false if none of them are.
- */
- SmartPropertyBase.prototype.checkPropertiesDirty = function (flags) {
- return (this._instanceDirtyFlags & flags) !== 0;
- };
- /**
- * Clear a given set of properties.
- * @param flags a ORed combination of Prim2DPropInfo.flagId values
- * @return the new set of property still marked as dirty
- */
- SmartPropertyBase.prototype.clearPropertiesDirty = function (flags) {
- this._instanceDirtyFlags &= ~flags;
- return this._instanceDirtyFlags;
- };
- SmartPropertyBase.prototype._resetPropertiesDirty = function () {
- this._instanceDirtyFlags = 0;
- };
- /**
- * Add an externally attached data from its key.
- * This method call will fail and return false, if such key already exists.
- * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
- * @param key the unique key that identifies the data
- * @param data the data object to associate to the key for this Engine instance
- * @return true if no such key were already present and the data was added successfully, false otherwise
- */
- SmartPropertyBase.prototype.addExternalData = function (key, data) {
- if (!this._externalData) {
- this._externalData = new BABYLON.StringDictionary();
- }
- return this._externalData.add(key, data);
- };
- /**
- * Get an externally attached data from its key
- * @param key the unique key that identifies the data
- * @return the associated data, if present (can be null), or undefined if not present
- */
- SmartPropertyBase.prototype.getExternalData = function (key) {
- if (!this._externalData) {
- return null;
- }
- return this._externalData.get(key);
- };
- /**
- * Get an externally attached data from its key, create it using a factory if it's not already present
- * @param key the unique key that identifies the data
- * @param factory the factory that will be called to create the instance if and only if it doesn't exists
- * @return the associated data, can be null if the factory returned null.
- */
- SmartPropertyBase.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
- if (!this._externalData) {
- this._externalData = new BABYLON.StringDictionary();
- }
- return this._externalData.getOrAddWithFactory(key, factory);
- };
- /**
- * Remove an externally attached data from the Engine instance
- * @param key the unique key that identifies the data
- * @return true if the data was successfully removed, false if it doesn't exist
- */
- SmartPropertyBase.prototype.removeExternalData = function (key) {
- if (!this._externalData) {
- return false;
- }
- return this._externalData.remove(key);
- };
- SmartPropertyBase._hookProperty = function (propId, piStore, kind, settings) {
- return function (target, propName, descriptor) {
- if (!settings) {
- settings = {};
- }
- var propInfo = SmartPropertyBase_1._createPropInfo(target, propName, propId, kind, settings);
- if (piStore) {
- piStore(propInfo);
- }
- var getter = descriptor.get, setter = descriptor.set;
- var typeLevelCompare = (settings.typeLevelCompare !== undefined) ? settings.typeLevelCompare : false;
- // Overload the property setter implementation to add our own logic
- descriptor.set = function (val) {
- if (!setter) {
- throw Error("Property '" + propInfo.name + "' of type '" + BABYLON.Tools.getFullClassName(this) + "' has no setter defined but was invoked as if it had one.");
- }
- // check for disposed first, do nothing
- if (this.isDisposed) {
- return;
- }
- var curVal = getter.call(this);
- if (SmartPropertyBase_1._checkUnchanged(curVal, val)) {
- return;
- }
- // Cast the object we're working one
- var prim = this;
- // Change the value
- setter.call(this, val);
- // Notify change, dirty flags update
- prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
- };
- };
- };
- SmartPropertyBase._createPropInfo = function (target, propName, propId, kind, settings) {
- var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
- var node = dic.getLevelOf(target);
- var propInfo = node.levelContent.get(propId.toString());
- if (propInfo) {
- throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
- }
- // Create, setup and add the PropInfo object to our prop dictionary
- propInfo = new Prim2DPropInfo();
- propInfo.id = propId;
- propInfo.flagId = Math.pow(2, propId);
- propInfo.kind = kind;
- propInfo.name = propName;
- propInfo.bindingMode = (settings.bindingMode !== undefined) ? settings.bindingMode : DataBinding.MODE_TWOWAY;
- propInfo.bindingUpdateSourceTrigger = (settings.bindingUpdateSourceTrigger !== undefined) ? settings.bindingUpdateSourceTrigger : DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED;
- propInfo.dirtyBoundingInfo = (settings.dirtyBoundingInfo !== undefined) ? settings.dirtyBoundingInfo : false;
- propInfo.dirtyParentBoundingInfo = (settings.dirtyParentBoundingBox !== undefined) ? settings.dirtyParentBoundingBox : false;
- propInfo.typeLevelCompare = (settings.typeLevelCompare !== undefined) ? settings.typeLevelCompare : false;
- node.levelContent.add(propName, propInfo);
- return propInfo;
- };
- Object.defineProperty(SmartPropertyBase.prototype, "propDic", {
- /**
- * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
- * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
- */
- get: function () {
- if (!this._propInfo) {
- var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
- if (!cti) {
- throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
- }
- this._propInfo = cti.fullContent;
- }
- return this._propInfo;
- },
- enumerable: true,
- configurable: true
- });
- SmartPropertyBase._checkUnchanged = function (curValue, newValue) {
- // Nothing to nothing: nothing to do!
- if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
- return true;
- }
- // Check value unchanged
- if ((curValue != null) && (newValue != null)) {
- if (typeof (curValue.equals) == "function") {
- if (curValue.equals(newValue)) {
- return true;
- }
- }
- else {
- if (curValue === newValue) {
- return true;
- }
- }
- }
- return false;
- };
- SmartPropertyBase.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
- // Trigger property changed
- var info = SmartPropertyBase_1.propChangeGuarding ? new BABYLON.PropertyChangedInfo() : SmartPropertyPrim.propChangedInfo;
- info.oldValue = curValue;
- info.newValue = newValue;
- info.propertyName = propName;
- var propMask = propInfo ? propInfo.flagId : -1;
- try {
- SmartPropertyBase_1.propChangeGuarding = true;
- this.propertyChanged.notifyObservers(info, propMask);
- }
- finally {
- SmartPropertyBase_1.propChangeGuarding = false;
- }
- };
- SmartPropertyBase.prototype._triggerPropertyChanged = function (propInfo, newValue) {
- if (this.isDisposed) {
- return;
- }
- if (!propInfo) {
- return;
- }
- this._handlePropChanged(undefined, newValue, propInfo.name, propInfo, propInfo.typeLevelCompare);
- };
- Object.defineProperty(SmartPropertyBase.prototype, "dataSource", {
- /**
- * Set the object from which Smart Properties using Binding will take/update their data from/to.
- * 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.
- */
- get: function () {
- // Don't access to _dataSource directly but via a call to the _getDataSource method which can be overloaded in inherited classes
- return this._getDataSource();
- },
- set: function (value) {
- if (this._dataSource === value) {
- return;
- }
- var oldValue = this._dataSource;
- this._dataSource = value;
- if (this._bindings && value != null) {
- // Register the bindings
- for (var _i = 0, _a = this._bindings; _i < _a.length; _i++) {
- var binding = _a[_i];
- if (binding != null) {
- binding._registerDataSource(true);
- }
- }
- }
- this.onPropertyChanged("dataSource", oldValue, value);
- },
- enumerable: true,
- configurable: true
- });
- // Inheriting classes can overload this method to provides additional logic for dataSource access
- SmartPropertyBase.prototype._getDataSource = function () {
- return this._dataSource;
- };
- SmartPropertyBase.prototype.createSimpleDataBinding = function (propInfo, propertyPathName, mode) {
- if (mode === void 0) { mode = DataBinding.MODE_DEFAULT; }
- var binding = new DataBinding();
- binding.propertyPathName = propertyPathName;
- binding.mode = mode;
- return this.createDataBinding(propInfo, binding);
- };
- SmartPropertyBase.prototype.createDataBinding = function (propInfo, binding) {
- if (!this._bindings) {
- this._bindings = new Array();
- }
- if (!binding || binding._owner != null) {
- throw Error("A valid/unused Binding must be passed.");
- }
- // Unregister a potentially existing binding for this property
- this.removeDataBinding(propInfo);
- // register the binding
- binding._owner = this;
- binding._boundTo = propInfo;
- this._bindings[propInfo.id] = binding;
- this._hasBinding |= propInfo.flagId;
- binding._registerDataSource(true);
- return binding;
- };
- SmartPropertyBase.prototype.removeDataBinding = function (propInfo) {
- if ((this._hasBinding & propInfo.flagId) === 0) {
- return false;
- }
- var curBinding = this._bindings[propInfo.id];
- curBinding._unregisterDataSource();
- this._bindings[propInfo.id] = null;
- this._hasBinding &= ~propInfo.flagId;
- return true;
- };
- SmartPropertyBase.prototype.updateFromDataSource = function () {
- for (var _i = 0, _a = this._bindings; _i < _a.length; _i++) {
- var binding = _a[_i];
- if (binding) {
- //BindingWatcher.updateFromDataSource(this, binding, false);
- }
- }
- };
- return SmartPropertyBase;
- }(BABYLON.PropertyChangedBase));
- SmartPropertyBase.propChangedInfo = new BABYLON.PropertyChangedInfo();
- SmartPropertyBase.propChangeGuarding = false;
- __decorate([
- BABYLON.logProp()
- ], SmartPropertyBase.prototype, "_triggerPropertyChanged", null);
- SmartPropertyBase = SmartPropertyBase_1 = __decorate([
- BABYLON.className("SmartPropertyBase", "BABYLON")
- ], SmartPropertyBase);
- BABYLON.SmartPropertyBase = SmartPropertyBase;
- var BindingInfo = (function () {
- function BindingInfo(binding, level, isLast) {
- this.binding = binding;
- this.level = level;
- this.isLast = isLast;
- }
- return BindingInfo;
- }());
- var MonitoredObjectData = (function () {
- function MonitoredObjectData(monitoredObject) {
- var _this = this;
- this.monitoredObject = monitoredObject;
- this.monitoredIntermediateProperties = new BABYLON.StringDictionary();
- this.observer = this.monitoredObject.propertyChanged.add(function (e, s) { _this.propertyChangedHandler(e.propertyName, e.oldValue, e.newValue); });
- this.boundProperties = new BABYLON.StringDictionary();
- this.monitoredIntermediateMask = 0;
- this.boundPropertiesMask = 0;
- }
- MonitoredObjectData.prototype.propertyChangedHandler = function (propName, oldValue, newValue) {
- var propId = BindingHelper._getPropertyID(this.monitoredObject, propName);
- var propIdStr = propId.toString();
- // Loop through all the registered bindings for this property that had a value change
- if ((this.boundPropertiesMask & propId) !== 0) {
- var bindingInfos = this.boundProperties.get(propIdStr);
- for (var _i = 0, bindingInfos_1 = bindingInfos; _i < bindingInfos_1.length; _i++) {
- var bi = bindingInfos_1[_i];
- if (!bi.isLast) {
- BindingHelper.unregisterDataSource(this.monitoredObject, bi.binding, bi.level);
- BindingHelper.registerDataSource(bi.binding._currentDataSource, bi.binding);
- }
- if (bi.binding.canUpdateTarget(false)) {
- bi.binding.updateTarget();
- }
- }
- }
- };
- return MonitoredObjectData;
- }());
- var BindingHelper = (function () {
- function BindingHelper() {
- }
- BindingHelper.registerDataSource = function (dataSource, binding) {
- var properties = binding.propertyPathName.split(".");
- var ownerMod = null;
- var ownerInterPropId = 0;
- var propertyOwner = dataSource;
- var _loop_1 = function (i) {
- var propName = properties[i];
- var propId = BindingHelper._getPropertyID(propertyOwner, propName);
- var propIdStr = propId.toString();
- var mod = void 0;
- if (ownerMod) {
- var o_1 = ownerMod;
- var po_1 = propertyOwner;
- var oii_1 = ownerInterPropId;
- mod = ownerMod.monitoredIntermediateProperties.getOrAddWithFactory(oii_1.toString(), function (k) {
- o_1.monitoredIntermediateMask |= oii_1;
- return BindingHelper._getMonitoredObjectData(po_1);
- });
- }
- else {
- mod = BindingHelper._getMonitoredObjectData(propertyOwner);
- }
- var m = mod;
- var bindingInfos = mod.boundProperties.getOrAddWithFactory(propIdStr, function (k) {
- m.boundPropertiesMask |= propId;
- return new Array();
- });
- var bi = BABYLON.Tools.first(bindingInfos, function (cbi) { return cbi.binding === binding; });
- if (!bi) {
- bindingInfos.push(new BindingInfo(binding, i, (i + 1) === properties.length));
- }
- ownerMod = mod;
- ownerInterPropId = propId;
- propertyOwner = propertyOwner[propName];
- };
- for (var i = 0; i < properties.length; i++) {
- _loop_1(i);
- }
- };
- BindingHelper.unregisterDataSource = function (dataSource, binding, level) {
- var properties = binding.propertyPathName.split(".");
- var propertyOwner = dataSource;
- var mod = BindingHelper._getMonitoredObjectData(propertyOwner);
- for (var i = 0; i < properties.length; i++) {
- var propName = properties[i];
- var propId = BindingHelper._getPropertyID(propertyOwner, propName);
- var propIdStr = propId.toString();
- if (i >= level) {
- mod = BindingHelper._unregisterBinding(mod, propId, binding);
- }
- else {
- mod = mod.monitoredIntermediateProperties.get(propIdStr);
- }
- propertyOwner = propertyOwner[propName];
- }
- };
- BindingHelper._unregisterBinding = function (mod, propertyID, binding) {
- var propertyIDStr = propertyID.toString();
- var res = null;
- // Check if the property is registered as an intermediate and remove it
- if ((mod.monitoredIntermediateMask & propertyID) !== 0) {
- res = mod.monitoredIntermediateProperties.get(propertyIDStr);
- mod.monitoredIntermediateProperties.remove(propertyIDStr);
- // Update the mask
- mod.monitoredIntermediateMask &= ~propertyID;
- }
- // Check if the property is registered as a final property and remove it
- if ((mod.boundPropertiesMask & propertyID) !== 0) {
- var bindingInfos = mod.boundProperties.get(propertyIDStr);
- // Find the binding and remove it
- var bi = BABYLON.Tools.first(bindingInfos, function (cbi) { return cbi.binding === binding; });
- if (bi) {
- var bii = bindingInfos.indexOf(bi);
- bindingInfos.splice(bii, 1);
- }
- // If the array is empty, update the mask
- if (bindingInfos.length === 0) {
- mod.boundPropertiesMask &= ~propertyID;
- }
- }
- // Check if the MOD is empty and unregister the observer and remove it from the list of MODs
- if (mod.boundPropertiesMask === 0 && mod.monitoredIntermediateMask === 0) {
- // Unregister the observer on Property Change
- mod.monitoredObject.propertyChanged.remove(mod.observer);
- // Remove the MOD from the dic
- var objectId = BindingHelper._getObjectId(mod.monitoredObject);
- BindingHelper._monitoredObjects.remove(objectId);
- }
- return res;
- };
- BindingHelper._getMonitoredObjectData = function (object) {
- var objectId = BindingHelper._getObjectId(object);
- var mod = BindingHelper._monitoredObjects.getOrAddWithFactory(objectId, function (k) { return new MonitoredObjectData(object); });
- return mod;
- };
- BindingHelper._getObjectId = function (obj) {
- var id = obj["__bindingHelperObjectId__"];
- if (id == null) {
- id = BABYLON.Tools.RandomId();
- obj["__bindingHelperObjectId__"] = id;
- return id;
- }
- return id;
- };
- BindingHelper._getObjectTypePropertyIDs = function (obj) {
- var fullName = BABYLON.Tools.getFullClassName(obj);
- if (!fullName) {
- throw Error("Types involved in Data Binding must be decorated with the @className decorator");
- }
- var d = BindingHelper._propertiesID.getOrAddWithFactory(fullName, function () { return new BABYLON.StringDictionary(); });
- return d;
- };
- BindingHelper._getPropertyID = function (object, propName) {
- var otd = BindingHelper._getObjectTypePropertyIDs(object);
- // Make sure we have a WatchedPropertyData for this property of this object type. This will contains the flagIg of the watched property.
- // We use this flagId to flag for each watched instance which properties are watched, as final or intermediate and which directions are used
- var propData = otd.getOrAddWithFactory(propName, function (k) { return 1 << otd.count; });
- return propData;
- };
- return BindingHelper;
- }());
- BindingHelper._propertiesID = new BABYLON.StringDictionary();
- BindingHelper._monitoredObjects = new BABYLON.StringDictionary();
- var SmartPropertyPrim = SmartPropertyPrim_1 = (function (_super) {
- __extends(SmartPropertyPrim, _super);
- function SmartPropertyPrim() {
- var _this = _super.call(this) || this;
- _this._flags = 0;
- _this._uid = null;
- _this._modelKey = null;
- _this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
- _this._boundingInfo = new BABYLON.BoundingInfo2D();
- _this.animations = new Array();
- return _this;
- }
- /**
- * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
- * @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.
- */
- SmartPropertyPrim.prototype.dispose = function () {
- if (this.isDisposed) {
- return false;
- }
- _super.prototype.dispose.call(this);
- // Don't set to null, it may upset somebody...
- this.animations.splice(0);
- return true;
- };
- Object.defineProperty(SmartPropertyPrim.prototype, "uid", {
- /**
- * return a unique identifier for the Canvas2D
- */
- get: function () {
- if (!this._uid) {
- this._uid = BABYLON.Tools.RandomId();
- }
- return this._uid;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
- * Look at Sprite2D for more information
- */
- SmartPropertyPrim.prototype.getAnimatables = function () {
- return new Array();
- };
- Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
- /**
- * Property giving the Model Key associated to the property.
- * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
- * @returns the model key string.
- */
- get: function () {
- var _this = this;
- // No need to compute it?
- if (!this._isFlagSet(SmartPropertyPrim_1.flagModelDirty) && this._modelKey) {
- return this._modelKey;
- }
- var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
- var propDic = this.propDic;
- propDic.forEach(function (k, v) {
- if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
- var propVal = _this[v.name];
- // 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
- if (propVal && propVal.constructor === Array) {
- var firstVal = propVal[0];
- if (!firstVal) {
- propVal = 0;
- }
- else {
- propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
- }
- }
- var value = "[null]";
- if (propVal != null) {
- if (v.typeLevelCompare) {
- value = BABYLON.Tools.getClassName(propVal);
- }
- else {
- // String Dictionaries' content are too complex, with use a Random GUID to make the model unique
- if (propVal instanceof BABYLON.StringDictionary) {
- value = BABYLON.Tools.RandomId();
- }
- else if (propVal instanceof BABYLON.BaseTexture) {
- value = propVal.uid;
- }
- else {
- value = propVal.toString();
- }
- }
- }
- modelKey += v.name + ":" + value + ";";
- }
- });
- this._clearFlags(SmartPropertyPrim_1.flagModelDirty);
- this._modelKey = modelKey;
- return modelKey;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
- /**
- * States if the Primitive is dirty and should be rendered again next time.
- * @returns true is dirty, false otherwise
- */
- get: function () {
- return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim_1.flagModelDirty | SmartPropertyPrim_1.flagModelUpdate | SmartPropertyPrim_1.flagPositioningDirty | SmartPropertyPrim_1.flagLayoutDirty);
- },
- enumerable: true,
- configurable: true
- });
- SmartPropertyPrim.prototype._boundingBoxDirty = function () {
- this._setFlags(SmartPropertyPrim_1.flagLevelBoundingInfoDirty | SmartPropertyPrim_1.flagLayoutBoundingInfoDirty);
- // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
- if (this instanceof BABYLON.Prim2DBase) {
- var curprim = this;
- while (curprim) {
- curprim._setFlags(SmartPropertyPrim_1.flagBoundingInfoDirty | SmartPropertyPrim_1.flagLayoutBoundingInfoDirty);
- if (curprim.isSizeAuto) {
- curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
- if (curprim._isFlagSet(SmartPropertyPrim_1.flagUsePositioning)) {
- curprim._setFlags(SmartPropertyPrim_1.flagPositioningDirty);
- }
- }
- if (curprim instanceof BABYLON.Group2D) {
- if (curprim.isRenderableGroup) {
- break;
- }
- }
- curprim = curprim.parent;
- }
- }
- };
- SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
- _super.prototype._handlePropChanged.call(this, curValue, newValue, propName, propInfo, typeLevelCompare);
- // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
- if (propInfo.dirtyBoundingInfo) {
- this._boundingBoxDirty();
- }
- else if (propInfo.dirtyParentBoundingInfo) {
- var p = this._parent;
- if (p != null) {
- p._boundingBoxDirty();
- }
- }
- // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
- if (this instanceof BABYLON.Group2D && this._renderableData) {
- this.handleGroupChanged(propInfo);
- }
- // Check for parent layout dirty
- if (this instanceof BABYLON.Prim2DBase) {
- var p = this._parent;
- if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
- p._setLayoutDirty();
- }
- var that = this;
- if (that.layoutEngine && (that.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
- this._setLayoutDirty();
- }
- }
- // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
- var instanceDirty = false;
- if (typeLevelCompare && curValue != null && newValue != null) {
- var cvProto = curValue.__proto__;
- var nvProto = newValue.__proto__;
- instanceDirty = (cvProto === nvProto);
- }
- // Set the dirty flags
- if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
- if (!this.isDirty) {
- this.onPrimBecomesDirty();
- this._setFlags(SmartPropertyPrim_1.flagModelDirty);
- }
- }
- else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
- var propMask = propInfo.flagId;
- this.onPrimitivePropertyDirty(propMask);
- }
- };
- SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
- this.onPrimBecomesDirty();
- this._instanceDirtyFlags |= propFlagId;
- };
- SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
- };
- SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
- _super.prototype._resetPropertiesDirty.call(this);
- this._clearFlags(SmartPropertyPrim_1.flagPrimInDirtyList | SmartPropertyPrim_1.flagNeedRefresh);
- };
- Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
- /**
- * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
- */
- get: function () {
- if (this._isFlagSet(SmartPropertyPrim_1.flagLevelBoundingInfoDirty)) {
- if (this.updateLevelBoundingInfo()) {
- this._boundingInfo.dirtyWorldAABB();
- this._clearFlags(SmartPropertyPrim_1.flagLevelBoundingInfoDirty);
- }
- else {
- this._levelBoundingInfo.clear();
- }
- }
- return this._levelBoundingInfo;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * This method must be overridden by a given Primitive implementation to compute its boundingInfo
- */
- SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
- return false;
- };
- /**
- * Property method called when the Primitive becomes dirty
- */
- SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
- };
- /**
- * Check if a given flag is set
- * @param flag the flag value
- * @return true if set, false otherwise
- */
- SmartPropertyPrim.prototype._isFlagSet = function (flag) {
- return (this._flags & flag) !== 0;
- };
- /**
- * Check if all given flags are set
- * @param flags the flags ORed
- * @return true if all the flags are set, false otherwise
- */
- SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
- return (this._flags & flags) === flags;
- };
- /**
- * Check if at least one flag of the given flags is set
- * @param flags the flags ORed
- * @return true if at least one flag is set, false otherwise
- */
- SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
- return (this._flags & flags) !== 0;
- };
- /**
- * Clear the given flags
- * @param flags the flags to clear
- */
- SmartPropertyPrim.prototype._clearFlags = function (flags) {
- this._flags &= ~flags;
- };
- /**
- * Set the given flags to true state
- * @param flags the flags ORed to set
- * @return the flags state before this call
- */
- SmartPropertyPrim.prototype._setFlags = function (flags) {
- var cur = this._flags;
- this._flags |= flags;
- return cur;
- };
- /**
- * Change the state of the given flags
- * @param flags the flags ORed to change
- * @param state true to set them, false to clear them
- */
- SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
- if (state) {
- this._flags |= flags;
- }
- else {
- this._flags &= ~flags;
- }
- };
- SmartPropertyPrim.prototype._getFlagsDebug = function (flags) {
- var res = "";
- if (flags & SmartPropertyPrim_1.flagNoPartOfLayout)
- res += "NoPartOfLayout, ";
- if (flags & SmartPropertyPrim_1.flagLevelBoundingInfoDirty)
- res += "LevelBoundingInfoDirty, ";
- if (flags & SmartPropertyPrim_1.flagModelDirty)
- res += "ModelDirty, ";
- if (flags & SmartPropertyPrim_1.flagLayoutDirty)
- res += "LayoutDirty, ";
- if (flags & SmartPropertyPrim_1.flagLevelVisible)
- res += "LevelVisible, ";
- if (flags & SmartPropertyPrim_1.flagBoundingInfoDirty)
- res += "BoundingInfoDirty, ";
- if (flags & SmartPropertyPrim_1.flagIsPickable)
- res += "IsPickable, ";
- if (flags & SmartPropertyPrim_1.flagIsVisible)
- res += "IsVisible, ";
- if (flags & SmartPropertyPrim_1.flagVisibilityChanged)
- res += "VisibilityChanged, ";
- if (flags & SmartPropertyPrim_1.flagPositioningDirty)
- res += "PositioningDirty, ";
- if (flags & SmartPropertyPrim_1.flagTrackedGroup)
- res += "TrackedGroup, ";
- if (flags & SmartPropertyPrim_1.flagWorldCacheChanged)
- res += "WorldCacheChanged, ";
- if (flags & SmartPropertyPrim_1.flagChildrenFlatZOrder)
- res += "ChildrenFlatZOrder, ";
- if (flags & SmartPropertyPrim_1.flagZOrderDirty)
- res += "ZOrderDirty, ";
- if (flags & SmartPropertyPrim_1.flagActualOpacityDirty)
- res += "ActualOpacityDirty, ";
- if (flags & SmartPropertyPrim_1.flagPrimInDirtyList)
- res += "PrimInDirtyList, ";
- if (flags & SmartPropertyPrim_1.flagIsContainer)
- res += "IsContainer, ";
- if (flags & SmartPropertyPrim_1.flagNeedRefresh)
- res += "NeedRefresh, ";
- if (flags & SmartPropertyPrim_1.flagActualScaleDirty)
- res += "ActualScaleDirty, ";
- if (flags & SmartPropertyPrim_1.flagDontInheritParentScale)
- res += "DontInheritParentScale, ";
- if (flags & SmartPropertyPrim_1.flagGlobalTransformDirty)
- res += "GlobalTransformDirty, ";
- if (flags & SmartPropertyPrim_1.flagLayoutBoundingInfoDirty)
- res += "LayoutBoundingInfoDirty, ";
- if (flags & SmartPropertyPrim_1.flagCollisionActor)
- res += "CollisionActor, ";
- if (flags & SmartPropertyPrim_1.flagModelUpdate)
- res += "ModelUpdate, ";
- if (flags & SmartPropertyPrim_1.flagLocalTransformDirty)
- res += "LocalTransformDirty, ";
- if (flags & SmartPropertyPrim_1.flagUsePositioning)
- res += "UsePositioning, ";
- if (flags & SmartPropertyPrim_1.flagComputingPositioning)
- res += "ComputingPositioning, ";
- return res.slice(0, res.length - 2);
- };
- return SmartPropertyPrim;
- }(SmartPropertyBase));
- SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT = 0;
- SmartPropertyPrim.flagNoPartOfLayout = 0x0000001; // set if the primitive's position/size must not be computed by Layout Engine
- SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
- SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
- SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
- SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
- SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
- SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
- SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
- SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
- SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
- SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
- SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
- SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
- SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
- SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
- SmartPropertyPrim.flagPrimInDirtyList = 0x0008000; // set if the primitive is in the primDirtyList
- SmartPropertyPrim.flagIsContainer = 0x0010000; // set if the primitive is a container
- SmartPropertyPrim.flagNeedRefresh = 0x0020000; // set if the primitive wasn't successful at refresh
- SmartPropertyPrim.flagActualScaleDirty = 0x0040000; // set if the actualScale property needs to be recomputed
- SmartPropertyPrim.flagDontInheritParentScale = 0x0080000; // set if the actualScale must not use its parent's scale to be computed
- SmartPropertyPrim.flagGlobalTransformDirty = 0x0100000; // set if the global transform must be recomputed due to a local transform change
- SmartPropertyPrim.flagLayoutBoundingInfoDirty = 0x0200000; // set if the layout bounding info is dirty
- SmartPropertyPrim.flagCollisionActor = 0x0400000; // set if the primitive is part of the collision engine
- SmartPropertyPrim.flagModelUpdate = 0x0800000; // set if the primitive's model data is to update
- SmartPropertyPrim.flagLocalTransformDirty = 0x1000000; // set if the local transformation matrix must be recomputed
- SmartPropertyPrim.flagUsePositioning = 0x2000000; // set if the primitive rely on the positioning engine (padding or margin is used)
- SmartPropertyPrim.flagComputingPositioning = 0x4000000; // set if the positioning engine is computing the primitive, used to avoid re entrance
- SmartPropertyPrim.flagAlignPrimitive = 0x8000000; // set if the primitive should be pixel aligned to the render target
- __decorate([
- BABYLON.logProp()
- ], SmartPropertyPrim.prototype, "levelBoundingInfo", null);
- SmartPropertyPrim = SmartPropertyPrim_1 = __decorate([
- BABYLON.className("SmartPropertyPrim", "BABYLON")
- /**
- * Base class of the primitives, implementing core crosscutting features
- */
- ], SmartPropertyPrim);
- BABYLON.SmartPropertyPrim = SmartPropertyPrim;
- function dependencyProperty(propId, piStore, mode, updateSourceTrigger) {
- if (mode === void 0) { mode = DataBinding.MODE_TWOWAY; }
- if (updateSourceTrigger === void 0) { updateSourceTrigger = DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED; }
- return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_DYNAMIC, { bindingMode: mode, bindingUpdateSourceTrigger: updateSourceTrigger });
- }
- BABYLON.dependencyProperty = dependencyProperty;
- function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
- if (typeLevelCompare === void 0) { typeLevelCompare = false; }
- if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
- if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
- return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_MODEL, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
- }
- BABYLON.modelLevelProperty = modelLevelProperty;
- function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
- if (typeLevelCompare === void 0) { typeLevelCompare = false; }
- if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
- if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
- return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_INSTANCE, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
- }
- BABYLON.instanceLevelProperty = instanceLevelProperty;
- function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
- if (typeLevelCompare === void 0) { typeLevelCompare = false; }
- if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
- if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
- return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_DYNAMIC, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
- }
- BABYLON.dynamicLevelProperty = dynamicLevelProperty;
- var DataBinding_1, SmartPropertyBase_1, SmartPropertyPrim_1;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.smartPropertyPrim.js.map
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var PrepareRender2DContext = (function () {
- function PrepareRender2DContext() {
- this.forceRefreshPrimitive = false;
- }
- return PrepareRender2DContext;
- }());
- BABYLON.PrepareRender2DContext = PrepareRender2DContext;
- var Render2DContext = (function () {
- function Render2DContext(renderMode) {
- this._renderMode = renderMode;
- this.useInstancing = false;
- this.groupInfoPartData = null;
- this.partDataStartIndex = this.partDataEndIndex = null;
- this.instancedBuffers = null;
- }
- Object.defineProperty(Render2DContext.prototype, "renderMode", {
- /**
- * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
- */
- get: function () {
- return this._renderMode;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Render2DContext, "RenderModeOpaque", {
- /**
- * The set of primitives to render is opaque.
- * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
- */
- get: function () {
- return Render2DContext._renderModeOpaque;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
- /**
- * The set of primitives to render is using Alpha Test (aka masking).
- * 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.
- */
- get: function () {
- return Render2DContext._renderModeAlphaTest;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Render2DContext, "RenderModeTransparent", {
- /**
- * The set of primitives to render is transparent.
- * 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.
- */
- get: function () {
- return Render2DContext._renderModeTransparent;
- },
- enumerable: true,
- configurable: true
- });
- return Render2DContext;
- }());
- Render2DContext._renderModeOpaque = 1;
- Render2DContext._renderModeAlphaTest = 2;
- Render2DContext._renderModeTransparent = 3;
- BABYLON.Render2DContext = Render2DContext;
- /**
- * This class store information for the pointerEventObservable Observable.
- * 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.
- */
- var PrimitivePointerInfo = (function () {
- function PrimitivePointerInfo() {
- this.primitivePointerPos = BABYLON.Vector2.Zero();
- this.tilt = BABYLON.Vector2.Zero();
- this.cancelBubble = false;
- }
- Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
- // 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.
- /**
- * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
- * Bubbles: yes
- */
- get: function () {
- return PrimitivePointerInfo._pointerOver;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
- /**
- * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
- * Bubbles: no
- */
- get: function () {
- return PrimitivePointerInfo._pointerEnter;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
- /**
- * 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.
- * Bubbles: yes
- */
- get: function () {
- return PrimitivePointerInfo._pointerDown;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
- /**
- * This event type is raised when the pointer is a mouse and it's wheel is rolling
- * Bubbles: yes
- */
- get: function () {
- return PrimitivePointerInfo._pointerMouseWheel;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
- /**
- * 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.
- * Bubbles: yes
- */
- get: function () {
- return PrimitivePointerInfo._pointerMove;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
- /**
- * 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.
- * Bubbles: yes
- */
- get: function () {
- return PrimitivePointerInfo._pointerUp;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
- /**
- * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
- * Bubbles: yes
- */
- get: function () {
- return PrimitivePointerInfo._pointerOut;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
- /**
- * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
- * Bubbles: no
- */
- get: function () {
- return PrimitivePointerInfo._pointerLeave;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
- /**
- * 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.
- * Bubbles: yes
- */
- get: function () {
- return PrimitivePointerInfo._pointerGotCapture;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
- /**
- * This event type is raised after pointer capture is released for a pointer.
- * Bubbles: yes
- */
- get: function () {
- return PrimitivePointerInfo._pointerLostCapture;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
- get: function () {
- return PrimitivePointerInfo._mouseWheelPrecision;
- },
- enumerable: true,
- configurable: true
- });
- PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
- this.relatedTarget = prim;
- this.relatedTargetPointerPos = primPointerPos;
- };
- PrimitivePointerInfo.getEventTypeName = function (mask) {
- switch (mask) {
- case PrimitivePointerInfo.PointerOver: return "PointerOver";
- case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
- case PrimitivePointerInfo.PointerDown: return "PointerDown";
- case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
- case PrimitivePointerInfo.PointerMove: return "PointerMove";
- case PrimitivePointerInfo.PointerUp: return "PointerUp";
- case PrimitivePointerInfo.PointerOut: return "PointerOut";
- case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
- case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
- case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
- }
- };
- return PrimitivePointerInfo;
- }());
- PrimitivePointerInfo._pointerOver = 0x0001;
- PrimitivePointerInfo._pointerEnter = 0x0002;
- PrimitivePointerInfo._pointerDown = 0x0004;
- PrimitivePointerInfo._pointerMouseWheel = 0x0008;
- PrimitivePointerInfo._pointerMove = 0x0010;
- PrimitivePointerInfo._pointerUp = 0x0020;
- PrimitivePointerInfo._pointerOut = 0x0040;
- PrimitivePointerInfo._pointerLeave = 0x0080;
- PrimitivePointerInfo._pointerGotCapture = 0x0100;
- PrimitivePointerInfo._pointerLostCapture = 0x0200;
- PrimitivePointerInfo._mouseWheelPrecision = 3.0;
- BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
- /**
- * Defines the horizontal and vertical alignment information for a Primitive.
- */
- var PrimitiveAlignment = PrimitiveAlignment_1 = (function () {
- function PrimitiveAlignment(changeCallback) {
- this._changedCallback = changeCallback;
- this._horizontal = PrimitiveAlignment_1.AlignLeft;
- this._vertical = PrimitiveAlignment_1.AlignBottom;
- }
- Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
- /**
- * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
- */
- get: function () { return PrimitiveAlignment_1._AlignLeft; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveAlignment, "AlignTop", {
- /**
- * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
- */
- get: function () { return PrimitiveAlignment_1._AlignTop; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveAlignment, "AlignRight", {
- /**
- * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
- */
- get: function () { return PrimitiveAlignment_1._AlignRight; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
- /**
- * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
- */
- get: function () { return PrimitiveAlignment_1._AlignBottom; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
- /**
- * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
- */
- get: function () { return PrimitiveAlignment_1._AlignCenter; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
- /**
- * The content is stretched toward the opposite edges of the Primitive
- */
- get: function () { return PrimitiveAlignment_1._AlignStretch; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
- /**
- * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
- */
- get: function () {
- return this._horizontal;
- },
- set: function (value) {
- if (this._horizontal === value) {
- return;
- }
- this._horizontal = value;
- this.onChangeCallback();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
- /**
- * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
- */
- get: function () {
- return this._vertical;
- },
- set: function (value) {
- if (this._vertical === value) {
- return;
- }
- this._vertical = value;
- this.onChangeCallback();
- },
- enumerable: true,
- configurable: true
- });
- PrimitiveAlignment.prototype.onChangeCallback = function () {
- if (this._changedCallback) {
- this._changedCallback();
- }
- };
- /**
- * Set the horizontal alignment from a string value.
- * @param text can be either: 'left','right','center','stretch'
- */
- PrimitiveAlignment.prototype.setHorizontal = function (text) {
- var v = text.trim().toLocaleLowerCase();
- switch (v) {
- case "left":
- this.horizontal = PrimitiveAlignment_1.AlignLeft;
- return;
- case "right":
- this.horizontal = PrimitiveAlignment_1.AlignRight;
- return;
- case "center":
- this.horizontal = PrimitiveAlignment_1.AlignCenter;
- return;
- case "stretch":
- this.horizontal = PrimitiveAlignment_1.AlignStretch;
- return;
- }
- };
- /**
- * Set the vertical alignment from a string value.
- * @param text can be either: 'top','bottom','center','stretch'
- */
- PrimitiveAlignment.prototype.setVertical = function (text) {
- var v = text.trim().toLocaleLowerCase();
- switch (v) {
- case "top":
- this.vertical = PrimitiveAlignment_1.AlignTop;
- return;
- case "bottom":
- this.vertical = PrimitiveAlignment_1.AlignBottom;
- return;
- case "center":
- this.vertical = PrimitiveAlignment_1.AlignCenter;
- return;
- case "stretch":
- this.vertical = PrimitiveAlignment_1.AlignStretch;
- return;
- }
- };
- /**
- * Set the horizontal and or vertical alignments from a string value.
- * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
- */
- PrimitiveAlignment.prototype.fromString = function (value) {
- var m = value.trim().split(",");
- var hset = false;
- var vset = false;
- for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
- var v = m_1[_i];
- v = v.toLocaleLowerCase().trim();
- // Horizontal
- var i = v.indexOf("h:");
- if (i === -1) {
- i = v.indexOf("horizontal:");
- }
- if (i !== -1) {
- v = v.substr(v.indexOf(":") + 1);
- this.setHorizontal(v);
- hset = true;
- continue;
- }
- // Vertical
- i = v.indexOf("v:");
- if (i === -1) {
- i = v.indexOf("vertical:");
- }
- if (i !== -1) {
- v = v.substr(v.indexOf(":") + 1);
- this.setVertical(v);
- vset = true;
- continue;
- }
- }
- if (!hset && !vset && m.length === 1) {
- this.setHorizontal(m[0]);
- this.setVertical(m[0]);
- }
- };
- PrimitiveAlignment.prototype.copyFrom = function (pa) {
- this._horizontal = pa._horizontal;
- this._vertical = pa._vertical;
- this.onChangeCallback();
- };
- PrimitiveAlignment.prototype.clone = function () {
- var pa = new PrimitiveAlignment_1();
- pa._horizontal = this._horizontal;
- pa._vertical = this._vertical;
- return pa;
- };
- Object.defineProperty(PrimitiveAlignment.prototype, "isDefault", {
- get: function () {
- return this.horizontal === PrimitiveAlignment_1.AlignLeft && this.vertical === PrimitiveAlignment_1.AlignBottom;
- },
- enumerable: true,
- configurable: true
- });
- return PrimitiveAlignment;
- }());
- PrimitiveAlignment._AlignLeft = 1;
- PrimitiveAlignment._AlignTop = 1; // Same as left
- PrimitiveAlignment._AlignRight = 2;
- PrimitiveAlignment._AlignBottom = 2; // Same as right
- PrimitiveAlignment._AlignCenter = 3;
- PrimitiveAlignment._AlignStretch = 4;
- PrimitiveAlignment = PrimitiveAlignment_1 = __decorate([
- BABYLON.className("PrimitiveAlignment", "BABYLON")
- ], PrimitiveAlignment);
- BABYLON.PrimitiveAlignment = PrimitiveAlignment;
- /**
- * Stores information about a Primitive that was intersected
- */
- var PrimitiveIntersectedInfo = (function () {
- function PrimitiveIntersectedInfo(prim, intersectionLocation) {
- this.prim = prim;
- this.intersectionLocation = intersectionLocation;
- }
- return PrimitiveIntersectedInfo;
- }());
- BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
- /**
- * Define a thickness toward every edges of a Primitive to allow margin and padding.
- * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
- */
- var PrimitiveThickness = PrimitiveThickness_1 = (function () {
- function PrimitiveThickness(parentAccess, changedCallback) {
- this._parentAccess = parentAccess;
- this._changedCallback = changedCallback;
- this._pixels = new Array(4);
- this._percentages = new Array(4);
- this._setType(0, PrimitiveThickness_1.Auto);
- this._setType(1, PrimitiveThickness_1.Auto);
- this._setType(2, PrimitiveThickness_1.Auto);
- this._setType(3, PrimitiveThickness_1.Auto);
- this._pixels[0] = 0;
- this._pixels[1] = 0;
- this._pixels[2] = 0;
- this._pixels[3] = 0;
- }
- /**
- * Set the thickness from a string value
- * @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.
- * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
- */
- PrimitiveThickness.prototype.fromString = function (thickness) {
- this._clear();
- var m = thickness.trim().split(",");
- // Special case, one value to apply to all edges
- if (m.length === 1 && thickness.indexOf(":") === -1) {
- this._setStringValue(m[0], 0, false);
- this._setStringValue(m[0], 1, false);
- this._setStringValue(m[0], 2, false);
- this._setStringValue(m[0], 3, false);
- this.onChangeCallback();
- return;
- }
- var res = false;
- for (var _i = 0, m_2 = m; _i < m_2.length; _i++) {
- var cm = m_2[_i];
- res = this._extractString(cm, false) || res;
- }
- if (!res) {
- throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
- }
- // Check the margin that weren't set and set them in auto
- if ((this._flags & 0x000F) === 0)
- this._flags |= PrimitiveThickness_1.Pixel << 0;
- if ((this._flags & 0x00F0) === 0)
- this._flags |= PrimitiveThickness_1.Pixel << 4;
- if ((this._flags & 0x0F00) === 0)
- this._flags |= PrimitiveThickness_1.Pixel << 8;
- if ((this._flags & 0xF000) === 0)
- this._flags |= PrimitiveThickness_1.Pixel << 12;
- this.onChangeCallback();
- };
- /**
- * Set the thickness from multiple string
- * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
- * @param top the top thickness to set
- * @param left the left thickness to set
- * @param right the right thickness to set
- * @param bottom the bottom thickness to set
- */
- PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
- this._clear();
- this._setStringValue(top, 0, false);
- this._setStringValue(left, 1, false);
- this._setStringValue(right, 2, false);
- this._setStringValue(bottom, 3, false);
- this.onChangeCallback();
- return this;
- };
- /**
- * Set the thickness from pixel values
- * @param top the top thickness in pixels to set
- * @param left the left thickness in pixels to set
- * @param right the right thickness in pixels to set
- * @param bottom the bottom thickness in pixels to set
- */
- PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
- this._clear();
- this._pixels[0] = top;
- this._pixels[1] = left;
- this._pixels[2] = right;
- this._pixels[3] = bottom;
- this.onChangeCallback();
- return this;
- };
- /**
- * Apply the same pixel value to all edges
- * @param margin the value to set, in pixels.
- */
- PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
- this._clear();
- this._pixels[0] = margin;
- this._pixels[1] = margin;
- this._pixels[2] = margin;
- this._pixels[3] = margin;
- this.onChangeCallback();
- return this;
- };
- PrimitiveThickness.prototype.copyFrom = function (pt) {
- this._clear();
- for (var i = 0; i < 4; i++) {
- this._pixels[i] = pt._pixels[i];
- this._percentages[i] = pt._percentages[i];
- }
- this._flags = pt._flags;
- this.onChangeCallback();
- };
- /**
- * Set all edges in auto
- */
- PrimitiveThickness.prototype.auto = function () {
- this._clear();
- this._flags = (PrimitiveThickness_1.Auto << 0) | (PrimitiveThickness_1.Auto << 4) | (PrimitiveThickness_1.Auto << 8) | (PrimitiveThickness_1.Auto << 12);
- this._pixels[0] = 0;
- this._pixels[1] = 0;
- this._pixels[2] = 0;
- this._pixels[3] = 0;
- this.onChangeCallback();
- return this;
- };
- PrimitiveThickness.prototype._clear = function () {
- this._flags = 0;
- this._pixels[0] = 0;
- this._pixels[1] = 0;
- this._pixels[2] = 0;
- this._pixels[3] = 0;
- this._percentages[0] = null;
- this._percentages[1] = null;
- this._percentages[2] = null;
- this._percentages[3] = null;
- };
- PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
- var v = value.trim().toLocaleLowerCase();
- if (v.indexOf("top:") === 0) {
- v = v.substr(4).trim();
- return this._setStringValue(v, 0, emitChanged);
- }
- if (v.indexOf("left:") === 0) {
- v = v.substr(5).trim();
- return this._setStringValue(v, 1, emitChanged);
- }
- if (v.indexOf("right:") === 0) {
- v = v.substr(6).trim();
- return this._setStringValue(v, 2, emitChanged);
- }
- if (v.indexOf("bottom:") === 0) {
- v = v.substr(7).trim();
- return this._setStringValue(v, 3, emitChanged);
- }
- return false;
- };
- PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
- // Check for auto
- var v = value.trim().toLocaleLowerCase();
- if (v === "auto") {
- if (this._isType(index, PrimitiveThickness_1.Auto)) {
- return true;
- }
- this._setType(index, PrimitiveThickness_1.Auto);
- this._pixels[index] = 0;
- if (emitChanged) {
- this.onChangeCallback();
- }
- }
- else if (v === "inherit") {
- if (this._isType(index, PrimitiveThickness_1.Inherit)) {
- return true;
- }
- this._setType(index, PrimitiveThickness_1.Inherit);
- this._pixels[index] = null;
- if (emitChanged) {
- this.onChangeCallback();
- }
- }
- else {
- var pI = v.indexOf("%");
- // Check for percentage
- if (pI !== -1) {
- var n_1 = v.substr(0, pI);
- var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
- if (this._isType(index, PrimitiveThickness_1.Percentage) && (this._percentages[index] === number_1)) {
- return true;
- }
- this._setType(index, PrimitiveThickness_1.Percentage);
- if (isNaN(number_1)) {
- return false;
- }
- this._percentages[index] = number_1;
- if (emitChanged) {
- this.onChangeCallback();
- }
- return true;
- }
- // Check for pixel
- var n = void 0;
- pI = v.indexOf("px");
- if (pI !== -1) {
- n = v.substr(0, pI).trim();
- }
- else {
- n = v;
- }
- var number = Number(n);
- if (this._isType(index, PrimitiveThickness_1.Pixel) && (this._pixels[index] === number)) {
- return true;
- }
- if (isNaN(number)) {
- return false;
- }
- this._pixels[index] = number;
- this._setType(index, PrimitiveThickness_1.Pixel);
- if (emitChanged) {
- this.onChangeCallback();
- }
- return true;
- }
- };
- PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
- // 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
- value = Math.round(value);
- if (this._isType(index, PrimitiveThickness_1.Pixel) && this._pixels[index] === value) {
- return;
- }
- this._setType(index, PrimitiveThickness_1.Pixel);
- this._pixels[index] = value;
- if (emitChanged) {
- this.onChangeCallback();
- }
- };
- PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
- // Clip Value to bounds
- value = Math.min(1, value);
- value = Math.max(0, value);
- value = Math.round(value * 100) / 100; // 0.01 precision
- if (this._isType(index, PrimitiveThickness_1.Percentage) && this._percentages[index] === value) {
- return;
- }
- this._setType(index, PrimitiveThickness_1.Percentage);
- this._percentages[index] = value;
- if (emitChanged) {
- this.onChangeCallback();
- }
- };
- PrimitiveThickness.prototype._getStringValue = function (index) {
- var f = (this._flags >> (index * 4)) & 0xF;
- switch (f) {
- case PrimitiveThickness_1.Auto:
- return "auto";
- case PrimitiveThickness_1.Pixel:
- return this._pixels[index] + "px";
- case PrimitiveThickness_1.Percentage:
- return this._percentages[index] * 100 + "%";
- case PrimitiveThickness_1.Inherit:
- return "inherit";
- }
- return "";
- };
- PrimitiveThickness.prototype._isType = function (index, type) {
- var f = (this._flags >> (index * 4)) & 0xF;
- return f === type;
- };
- PrimitiveThickness.prototype._getType = function (index, processInherit) {
- var t = (this._flags >> (index * 4)) & 0xF;
- if (processInherit && (t === PrimitiveThickness_1.Inherit)) {
- var p = this._parentAccess();
- if (p) {
- return p._getType(index, true);
- }
- return PrimitiveThickness_1.Auto;
- }
- return t;
- };
- PrimitiveThickness.prototype._setType = function (index, type) {
- this._flags &= ~(0xF << (index * 4));
- this._flags |= type << (index * 4);
- };
- PrimitiveThickness.prototype.setTop = function (value) {
- if (typeof value === "string") {
- this._setStringValue(value, 0, true);
- }
- else {
- this.topPixels = value;
- }
- };
- PrimitiveThickness.prototype.setLeft = function (value) {
- if (typeof value === "string") {
- this._setStringValue(value, 1, true);
- }
- else {
- this.leftPixels = value;
- }
- };
- PrimitiveThickness.prototype.setRight = function (value) {
- if (typeof value === "string") {
- this._setStringValue(value, 2, true);
- }
- else {
- this.rightPixels = value;
- }
- };
- PrimitiveThickness.prototype.setBottom = function (value) {
- if (typeof value === "string") {
- this._setStringValue(value, 3, true);
- }
- else {
- this.bottomPixels = value;
- }
- };
- Object.defineProperty(PrimitiveThickness.prototype, "top", {
- /**
- * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
- */
- get: function () {
- return this._getStringValue(0);
- },
- set: function (value) {
- this._setStringValue(value, 0, true);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveThickness.prototype, "left", {
- /**
- * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
- */
- get: function () {
- return this._getStringValue(1);
- },
- set: function (value) {
- this._setStringValue(value, 1, true);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveThickness.prototype, "right", {
- /**
- * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
- */
- get: function () {
- return this._getStringValue(2);
- },
- set: function (value) {
- this._setStringValue(value, 2, true);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
- /**
- * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
- */
- get: function () {
- return this._getStringValue(3);
- },
- set: function (value) {
- this._setStringValue(value, 3, true);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
- /**
- * Get/set the top thickness in pixel.
- */
- get: function () {
- return this._pixels[0];
- },
- set: function (value) {
- this._setPixels(value, 0, true);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
- /**
- * Get/set the left thickness in pixel.
- */
- get: function () {
- return this._pixels[1];
- },
- set: function (value) {
- this._setPixels(value, 1, true);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
- /**
- * Get/set the right thickness in pixel.
- */
- get: function () {
- return this._pixels[2];
- },
- set: function (value) {
- this._setPixels(value, 2, true);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
- /**
- * Get/set the bottom thickness in pixel.
- */
- get: function () {
- return this._pixels[3];
- },
- set: function (value) {
- this._setPixels(value, 3, true);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
- /**
- * Get/set the top thickness in percentage.
- * The get will return a valid value only if the edge type is percentage.
- * The Set will change the edge mode if needed
- */
- get: function () {
- return this._percentages[0];
- },
- set: function (value) {
- this._setPercentage(value, 0, true);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
- /**
- * Get/set the left thickness in percentage.
- * The get will return a valid value only if the edge mode is percentage.
- * The Set will change the edge mode if needed
- */
- get: function () {
- return this._percentages[1];
- },
- set: function (value) {
- this._setPercentage(value, 1, true);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
- /**
- * Get/set the right thickness in percentage.
- * The get will return a valid value only if the edge mode is percentage.
- * The Set will change the edge mode if needed
- */
- get: function () {
- return this._percentages[2];
- },
- set: function (value) {
- this._setPercentage(value, 2, true);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
- /**
- * Get/set the bottom thickness in percentage.
- * The get will return a valid value only if the edge mode is percentage.
- * The Set will change the edge mode if needed
- */
- get: function () {
- return this._percentages[3];
- },
- set: function (value) {
- this._setPercentage(value, 3, true);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
- /**
- * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
- */
- get: function () {
- return this._getType(0, false);
- },
- set: function (mode) {
- this._setType(0, mode);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
- /**
- * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
- */
- get: function () {
- return this._getType(1, false);
- },
- set: function (mode) {
- this._setType(1, mode);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
- /**
- * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
- */
- get: function () {
- return this._getType(2, false);
- },
- set: function (mode) {
- this._setType(2, mode);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
- /**
- * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
- */
- get: function () {
- return this._getType(3, false);
- },
- set: function (mode) {
- this._setType(3, mode);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PrimitiveThickness.prototype, "isDefault", {
- get: function () {
- return this._flags === 0x1111;
- },
- enumerable: true,
- configurable: true
- });
- PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
- var type = this._getType(index, false);
- if (type === PrimitiveThickness_1.Inherit) {
- this._parentAccess()._computePixels(index, sourceArea, emitChanged);
- return;
- }
- if (type !== PrimitiveThickness_1.Percentage) {
- return;
- }
- var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
- this._pixels[index] = pixels;
- if (emitChanged) {
- this.onChangeCallback();
- }
- };
- PrimitiveThickness.prototype.onChangeCallback = function () {
- if (this._changedCallback) {
- this._changedCallback();
- }
- };
- /**
- * Compute the positioning/size of an area considering the thickness of this object and a given alignment
- * @param sourceArea the source area where the content must be sized/positioned
- * @param contentSize the content size to position/resize
- * @param alignment the alignment setting
- * @param dstOffset the position of the content, x, y, z, w are left, bottom, right, top
- * @param dstArea the new size of the content
- */
- PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, contentScale, dstOffset, dstArea, computeLayoutArea, computeAxis) {
- if (computeLayoutArea === void 0) { computeLayoutArea = false; }
- if (computeAxis === void 0) { computeAxis = PrimitiveThickness_1.ComputeAll; }
- // Fetch some data
- var topType = this._getType(0, true);
- var leftType = this._getType(1, true);
- var rightType = this._getType(2, true);
- var bottomType = this._getType(3, true);
- var hasWidth = contentSize && (contentSize.width != null);
- var hasHeight = contentSize && (contentSize.height != null);
- var sx = contentScale.x;
- var sy = contentScale.y;
- var isx = 1 / sx;
- var isy = 1 / sy;
- var width = hasWidth ? contentSize.width : 0;
- var height = hasHeight ? contentSize.height : 0;
- var isTopAuto = topType === PrimitiveThickness_1.Auto;
- var isLeftAuto = leftType === PrimitiveThickness_1.Auto;
- var isRightAuto = rightType === PrimitiveThickness_1.Auto;
- var isBottomAuto = bottomType === PrimitiveThickness_1.Auto;
- if (computeAxis & PrimitiveThickness_1.ComputeH) {
- switch (alignment.horizontal) {
- case PrimitiveAlignment.AlignLeft:
- {
- var leftPixels = 0;
- if (!isLeftAuto) {
- this._computePixels(1, sourceArea, true);
- leftPixels = this.leftPixels;
- }
- dstOffset.x = leftPixels;
- dstArea.width = width * isx;
- dstOffset.z = sourceArea.width - (width * sx + leftPixels);
- if (computeLayoutArea) {
- var rightPixels = 0;
- if (!isRightAuto) {
- this._computePixels(2, sourceArea, true);
- rightPixels = this.rightPixels;
- }
- dstArea.width += (leftPixels + rightPixels) * isx;
- }
- break;
- }
- case PrimitiveAlignment.AlignRight:
- {
- var rightPixels = 0;
- if (!isRightAuto) {
- this._computePixels(2, sourceArea, true);
- rightPixels = this.rightPixels;
- }
- dstOffset.x = sourceArea.width - (width * sx + rightPixels);
- dstArea.width = width * isx;
- dstOffset.z = rightPixels;
- if (computeLayoutArea) {
- var leftPixels = 0;
- if (!isLeftAuto) {
- this._computePixels(1, sourceArea, true);
- leftPixels = this.leftPixels;
- }
- dstArea.width += (leftPixels + rightPixels) * isx;
- }
- break;
- }
- case PrimitiveAlignment.AlignStretch:
- {
- if (isLeftAuto) {
- dstOffset.x = 0;
- }
- else {
- this._computePixels(1, sourceArea, true);
- dstOffset.x = this.leftPixels;
- }
- var rightPixels = 0;
- if (!isRightAuto) {
- this._computePixels(2, sourceArea, true);
- rightPixels = this.rightPixels;
- }
- if (computeLayoutArea) {
- dstArea.width = sourceArea.width * isx;
- }
- else {
- dstArea.width = (sourceArea.width * isx) - (dstOffset.x + rightPixels) * isx;
- }
- dstOffset.z = this.rightPixels;
- break;
- }
- case PrimitiveAlignment.AlignCenter:
- {
- var leftPixels = 0;
- if (!isLeftAuto) {
- this._computePixels(1, sourceArea, true);
- leftPixels = this.leftPixels;
- }
- var rightPixels = 0;
- if (!isRightAuto) {
- this._computePixels(2, sourceArea, true);
- rightPixels = this.rightPixels;
- }
- var center = ((sourceArea.width - (width * sx)) / 2);
- dstOffset.x = center + (leftPixels - rightPixels);
- if (computeLayoutArea) {
- dstArea.width = (width * isx) + (this.leftPixels + this.rightPixels) * isx;
- }
- else {
- dstArea.width = (width * isx);
- }
- dstOffset.z = rightPixels + center;
- break;
- }
- }
- }
- if (computeAxis & PrimitiveThickness_1.ComputeV) {
- switch (alignment.vertical) {
- case PrimitiveAlignment.AlignBottom:
- {
- var bottomPixels = 0;
- if (!isBottomAuto) {
- this._computePixels(3, sourceArea, true);
- bottomPixels = this.bottomPixels;
- }
- dstOffset.y = bottomPixels;
- dstArea.height = height * isy;
- dstOffset.w = sourceArea.height - (height * sy + bottomPixels);
- if (computeLayoutArea) {
- var topPixels = 0;
- if (!isTopAuto) {
- this._computePixels(0, sourceArea, true);
- topPixels = this.topPixels;
- }
- dstArea.height += (bottomPixels + topPixels) * isy;
- }
- break;
- }
- case PrimitiveAlignment.AlignTop:
- {
- var topPixels = 0;
- if (!isTopAuto) {
- this._computePixels(0, sourceArea, true);
- topPixels = this.topPixels;
- }
- dstOffset.y = sourceArea.height - ((height * sy) + topPixels);
- dstArea.height = height * isy;
- dstOffset.w = topPixels;
- if (computeLayoutArea) {
- var bottomPixels = 0;
- if (!isBottomAuto) {
- this._computePixels(3, sourceArea, true);
- bottomPixels = this.bottomPixels;
- }
- dstArea.height += (bottomPixels + topPixels) * isy;
- }
- break;
- }
- case PrimitiveAlignment.AlignStretch:
- {
- var bottom = 0;
- if (!isBottomAuto) {
- this._computePixels(3, sourceArea, true);
- bottom = this.bottomPixels;
- }
- dstOffset.y = bottom;
- var top_1 = 0;
- if (!isTopAuto) {
- this._computePixels(0, sourceArea, true);
- top_1 = this.topPixels;
- }
- dstOffset.w = top_1;
- if (computeLayoutArea) {
- dstArea.height = sourceArea.height * isy;
- }
- else {
- dstArea.height = (sourceArea.height * isy) - (top_1 + bottom) * isy;
- }
- break;
- }
- case PrimitiveAlignment.AlignCenter:
- {
- var bottomPixels = 0;
- if (!isBottomAuto) {
- this._computePixels(3, sourceArea, true);
- bottomPixels = this.bottomPixels;
- }
- var topPixels = 0;
- if (!isTopAuto) {
- this._computePixels(0, sourceArea, true);
- topPixels = this.topPixels;
- }
- var center = ((sourceArea.height - (height * sy)) / 2);
- dstOffset.y = center + (bottomPixels - topPixels);
- if (computeLayoutArea) {
- dstArea.height = (height * isy) + (bottomPixels + topPixels) * isy;
- }
- else {
- dstArea.height = (height * isy);
- }
- dstOffset.w = topPixels + center;
- break;
- }
- }
- }
- };
- /**
- * Compute an area and its position considering this thickness properties based on a given source area
- * @param sourceArea the source area
- * @param dstOffset the position of the resulting area
- * @param dstArea the size of the resulting area
- */
- PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea, computeLayoutArea) {
- if (computeLayoutArea === void 0) { computeLayoutArea = false; }
- this._computePixels(0, sourceArea, true);
- this._computePixels(1, sourceArea, true);
- this._computePixels(2, sourceArea, true);
- this._computePixels(3, sourceArea, true);
- dstOffset.x = this.leftPixels;
- if (computeLayoutArea) {
- dstArea.width = (sourceArea.width) + (dstOffset.x + this.rightPixels);
- }
- else {
- dstArea.width = (sourceArea.width) - (dstOffset.x + this.rightPixels);
- }
- dstOffset.y = this.bottomPixels;
- if (computeLayoutArea) {
- dstArea.height = (sourceArea.height) + (dstOffset.y + this.topPixels);
- }
- else {
- dstArea.height = (sourceArea.height) - (dstOffset.y + this.topPixels);
- }
- dstOffset.z = this.rightPixels;
- dstOffset.w = this.topPixels;
- };
- /**
- * Compute an area considering this thickness properties based on a given source area
- * @param sourceArea the source area
- * @param result the resulting area
- */
- PrimitiveThickness.prototype.computeArea = function (sourceArea, sourceScale, result) {
- this._computePixels(0, sourceArea, true);
- this._computePixels(1, sourceArea, true);
- this._computePixels(2, sourceArea, true);
- this._computePixels(3, sourceArea, true);
- result.width = this.leftPixels + (sourceArea.width * sourceScale.x) + this.rightPixels;
- result.height = this.bottomPixels + (sourceArea.height * sourceScale.y) + this.topPixels;
- };
- PrimitiveThickness.prototype.enlarge = function (sourceArea, sourceScale, dstOffset, enlargedArea) {
- this._computePixels(0, sourceArea, true);
- this._computePixels(1, sourceArea, true);
- this._computePixels(2, sourceArea, true);
- this._computePixels(3, sourceArea, true);
- dstOffset.x = this.leftPixels;
- enlargedArea.width = (sourceArea.width * sourceScale.x) + (dstOffset.x + this.rightPixels);
- dstOffset.y = this.bottomPixels;
- enlargedArea.height = (sourceArea.height * sourceScale.y) + (dstOffset.y + this.topPixels);
- dstOffset.z = this.rightPixels;
- dstOffset.w = this.topPixels;
- };
- return PrimitiveThickness;
- }());
- PrimitiveThickness.Auto = 0x1;
- PrimitiveThickness.Inherit = 0x2;
- PrimitiveThickness.Percentage = 0x4;
- PrimitiveThickness.Pixel = 0x8;
- PrimitiveThickness.ComputeH = 0x1;
- PrimitiveThickness.ComputeV = 0x2;
- PrimitiveThickness.ComputeAll = 0x03;
- PrimitiveThickness = PrimitiveThickness_1 = __decorate([
- BABYLON.className("PrimitiveThickness", "BABYLON")
- ], PrimitiveThickness);
- BABYLON.PrimitiveThickness = PrimitiveThickness;
- /**
- * Main class used for the Primitive Intersection API
- */
- var IntersectInfo2D = (function () {
- function IntersectInfo2D() {
- this.findFirstOnly = false;
- this.intersectHidden = false;
- this.pickPosition = BABYLON.Vector2.Zero();
- }
- Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
- /**
- * true if at least one primitive intersected during the test
- */
- get: function () {
- return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
- },
- enumerable: true,
- configurable: true
- });
- IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
- for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
- var cur = _a[_i];
- if (cur.prim === prim) {
- return cur.intersectionLocation;
- }
- }
- return null;
- };
- // Internals, don't use
- IntersectInfo2D.prototype._exit = function (firstLevel) {
- if (firstLevel) {
- this._globalPickPosition = null;
- }
- };
- return IntersectInfo2D;
- }());
- BABYLON.IntersectInfo2D = IntersectInfo2D;
- var Prim2DBase = Prim2DBase_1 = (function (_super) {
- __extends(Prim2DBase, _super);
- function Prim2DBase(settings) {
- var _this = this;
- // Avoid checking every time if the object exists
- if (settings == null) {
- settings = {};
- }
- // BASE CLASS CALL
- _this = _super.call(this) || this;
- // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
- var owner;
- var parent;
- if (Prim2DBase_1._isCanvasInit) {
- owner = _this;
- parent = null;
- _this._canvasPreInit(settings);
- }
- else {
- if (settings.parent != null) {
- parent = settings.parent;
- owner = settings.parent.owner;
- if (!owner) {
- throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
- }
- 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)) {
- 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");
- }
- }
- }
- // Fields initialization
- _this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
- _this._size = null; //Size.Zero();
- _this._scale = new BABYLON.Vector2(1, 1);
- _this._postScale = new BABYLON.Vector2(1, 1);
- _this._actualSize = null;
- _this._internalSize = BABYLON.Size.Zero();
- _this._layoutArea = null;
- _this._layoutAreaPos = null;
- _this._layoutBoundingInfo = null;
- _this._marginOffset = BABYLON.Vector4.Zero();
- _this._paddingOffset = BABYLON.Vector4.Zero();
- _this._parentPaddingOffset = BABYLON.Vector2.Zero();
- _this._parentContentArea = BABYLON.Size.Zero();
- _this._lastAutoSizeArea = BABYLON.Size.Zero();
- _this._contentArea = BABYLON.Size.Zero();
- _this._pointerEventObservable = new BABYLON.Observable();
- _this._owner = owner;
- _this._parent = null;
- _this._margin = null;
- _this._padding = null;
- _this._marginAlignment = null;
- _this._id = settings.id;
- _this._children = new Array();
- _this._localTransform = new BABYLON.Matrix2D();
- _this._localLayoutTransform = new BABYLON.Matrix2D();
- _this._globalTransform = null;
- _this._invGlobalTransform = null;
- _this._globalTransformProcessStep = 0;
- _this._globalTransformStep = 0;
- _this._prepareProcessStep = 0;
- _this._updateCachesProcessStep = 0;
- _this._renderGroup = null;
- _this._primLinearPosition = 0;
- _this._manualZOrder = null;
- _this._zOrder = 0;
- _this._zMax = 0;
- _this._firstZDirtyIndex = Prim2DBase_1._bigInt;
- _this._actualOpacity = 0;
- _this._actualScale = BABYLON.Vector2.Zero();
- _this._displayDebugAreas = false;
- _this._debugAreaGroup = null;
- _this._primTriArray = null;
- _this._primTriArrayDirty = true;
- if (owner) {
- _this.onSetOwner();
- }
- _this._levelBoundingInfo.worldMatrixAccess = function () { return _this.globalTransform; };
- _this._boundingInfo.worldMatrixAccess = function () { return _this.globalTransform; };
- var isPickable = true;
- var isContainer = true;
- if (settings.isPickable !== undefined) {
- isPickable = settings.isPickable;
- }
- if (settings.isContainer !== undefined) {
- isContainer = settings.isContainer;
- }
- if (settings.dontInheritParentScale) {
- _this._setFlags(BABYLON.SmartPropertyPrim.flagDontInheritParentScale);
- }
- if (settings.alignToPixel) {
- _this.alignToPixel = true;
- }
- _this._setFlags((isPickable ? BABYLON.SmartPropertyPrim.flagIsPickable : 0) | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty | (isContainer ? BABYLON.SmartPropertyPrim.flagIsContainer : 0) | BABYLON.SmartPropertyPrim.flagActualScaleDirty | BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
- if (settings.opacity != null) {
- _this._opacity = settings.opacity;
- }
- else {
- _this._opacity = 1;
- }
- _this._updateRenderMode();
- if (settings.childrenFlatZOrder) {
- _this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
- }
- // If the parent is given, initialize the hierarchy/owner related data
- if (parent != null) {
- parent.addChild(_this);
- _this._hierarchyDepth = parent._hierarchyDepth + 1;
- _this._patchHierarchy(parent.owner);
- }
- // If it's a group, detect its own states
- if (_this.owner && _this instanceof BABYLON.Group2D) {
- var group = _this;
- group.detectGroupStates();
- }
- // Time to insert children if some are specified
- if (settings.children != null) {
- for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
- var child = _a[_i];
- _this.addChild(child);
- // Good time to patch the hierarchy, it won't go very far if there's no need to
- if (_this.owner != null && _this._hierarchyDepth != null) {
- child._patchHierarchy(_this.owner);
- }
- }
- }
- if (settings.zOrder != null) {
- _this.zOrder = settings.zOrder;
- }
- // Set the model related properties
- if (settings.position != null) {
- _this.position = settings.position;
- }
- else if (settings.x != null || settings.y != null) {
- _this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
- }
- else {
- _this._position = null;
- }
- _this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
- if (settings.scale != null) {
- _this.scale = settings.scale;
- }
- else {
- if (settings.scaleX != null) {
- _this.scaleX = settings.scaleX;
- }
- if (settings.scaleY != null) {
- _this.scaleY = settings.scaleY;
- }
- }
- _this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
- _this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
- // Layout Engine
- if (settings.layoutEngine != null) {
- if (typeof settings.layoutEngine === "string") {
- var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
- if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
- _this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
- }
- else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
- _this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
- }
- else if (name_1.indexOf("verticalstackpanel") === 0) {
- _this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
- }
- }
- else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
- _this.layoutEngine = settings.layoutEngine;
- }
- }
- // Set the layout/margin stuffs
- if (settings.marginTop) {
- _this.margin.setTop(settings.marginTop);
- }
- if (settings.marginLeft) {
- _this.margin.setLeft(settings.marginLeft);
- }
- if (settings.marginRight) {
- _this.margin.setRight(settings.marginRight);
- }
- if (settings.marginBottom) {
- _this.margin.setBottom(settings.marginBottom);
- }
- if (settings.margin) {
- if (typeof settings.margin === "string") {
- _this.margin.fromString(settings.margin);
- }
- else {
- _this.margin.fromUniformPixels(settings.margin);
- }
- }
- if (settings.marginHAlignment) {
- _this.marginAlignment.horizontal = settings.marginHAlignment;
- }
- if (settings.marginVAlignment) {
- _this.marginAlignment.vertical = settings.marginVAlignment;
- }
- if (settings.marginAlignment) {
- _this.marginAlignment.fromString(settings.marginAlignment);
- }
- if (settings.paddingTop) {
- _this.padding.setTop(settings.paddingTop);
- }
- if (settings.paddingLeft) {
- _this.padding.setLeft(settings.paddingLeft);
- }
- if (settings.paddingRight) {
- _this.padding.setRight(settings.paddingRight);
- }
- if (settings.paddingBottom) {
- _this.padding.setBottom(settings.paddingBottom);
- }
- if (settings.padding) {
- if (typeof settings.padding === "string") {
- _this.padding.fromString(settings.padding);
- }
- else {
- _this.padding.fromUniformPixels(settings.padding);
- }
- }
- if (settings.layoutData) {
- _this.layoutData = settings.layoutData;
- }
- _this._updatePositioningState();
- // Dirty layout and positioning
- _this._parentLayoutDirty();
- _this._positioningDirty();
- // Add in the PCM
- if (settings.levelCollision || settings.deepCollision) {
- _this._actorInfo = _this.owner._primitiveCollisionManager._addActor(_this, settings.deepCollision === true);
- _this._setFlags(BABYLON.SmartPropertyPrim.flagCollisionActor);
- }
- else {
- _this._actorInfo = null;
- }
- return _this;
- }
- Object.defineProperty(Prim2DBase.prototype, "intersectWithObservable", {
- /**
- * Return the ChangedDictionary observable of the StringDictionary containing the primitives intersecting with this one
- */
- get: function () {
- if (!this._actorInfo) {
- return null;
- }
- return this._actorInfo.intersectWith.dictionaryChanged;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "intersectWith", {
- /**
- * Return the ObservableStringDictionary containing all the primitives intersecting with this one.
- * The key is the primitive uid, the value is the ActorInfo object
- * @returns {}
- */
- get: function () {
- if (!this._actorInfo) {
- return null;
- }
- return this._actorInfo.intersectWith;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "actionManager", {
- get: function () {
- if (!this._actionManager) {
- this._actionManager = new BABYLON.ActionManager(this.owner.scene);
- }
- return this._actionManager;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
- * @param predicate the predicate to test on each parent
- * @return the first primitive where the predicate was successful
- */
- Prim2DBase.prototype.traverseUp = function (predicate) {
- var p = this;
- while (p != null) {
- if (predicate(p)) {
- return p;
- }
- p = p._parent;
- }
- return null;
- };
- Object.defineProperty(Prim2DBase.prototype, "owner", {
- /**
- * Retrieve the owner Canvas2D
- */
- get: function () {
- return this._owner;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "parent", {
- /**
- * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
- */
- get: function () {
- return this._parent;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "children", {
- /**
- * The array of direct children primitives
- */
- get: function () {
- return this._children;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "id", {
- /**
- * The identifier of this primitive, may not be unique, it's for information purpose only
- */
- get: function () {
- return this._id;
- },
- set: function (value) {
- if (this._id === value) {
- return;
- }
- var oldValue = this._id;
- this.onPropertyChanged("id", oldValue, this._id);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
- get: function () {
- // If we don't use positioning engine the actual position is the position
- if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
- return this.position;
- }
- // We use the positioning engine, if the variable is fetched, it's up to date, return it
- if (this._actualPosition != null) {
- return this._actualPosition;
- }
- this._updatePositioning();
- return this._actualPosition;
- },
- /**
- * DO NOT INVOKE for internal purpose only
- */
- set: function (val) {
- if (!this._actualPosition) {
- this._actualPosition = val.clone();
- }
- else {
- this._actualPosition.copyFrom(val);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "actualX", {
- /**
- * Shortcut to actualPosition.x
- */
- get: function () {
- return this.actualPosition.x;
- },
- /**
- * DO NOT INVOKE for internal purpose only
- */
- set: function (val) {
- this._actualPosition.x = val;
- this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualPosition);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "actualY", {
- /**
- * Shortcut to actualPosition.y
- */
- get: function () {
- return this.actualPosition.y;
- },
- /**
- * DO NOT INVOKE for internal purpose only
- */
- set: function (val) {
- this._actualPosition.y = val;
- this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualPosition);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "position", {
- /**
- * Position of the primitive, relative to its parent.
- * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
- * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
- * Setting this property may have no effect is specific alignment are in effect.
- */
- get: function () {
- if (!this._position) {
- this._position = BABYLON.Vector2.Zero();
- }
- return this._position;
- },
- set: function (value) {
- //if (!this._checkPositionChange()) {
- // return;
- //}
- if (this._checkUseMargin()) {
- switch (this.marginAlignment.horizontal) {
- case PrimitiveAlignment.AlignLeft:
- case PrimitiveAlignment.AlignStretch:
- case PrimitiveAlignment.AlignCenter:
- this.margin.leftPixels = value.x;
- break;
- case PrimitiveAlignment.AlignRight:
- this.margin.rightPixels = value.x;
- break;
- }
- switch (this.marginAlignment.vertical) {
- case PrimitiveAlignment.AlignBottom:
- case PrimitiveAlignment.AlignStretch:
- case PrimitiveAlignment.AlignCenter:
- this.margin.bottomPixels = value.y;
- break;
- case PrimitiveAlignment.AlignTop:
- this.margin.topPixels = value.y;
- break;
- }
- return;
- }
- else {
- if (!value) {
- this._position = null;
- }
- else {
- if (!this._position) {
- this._position = value.clone();
- }
- else {
- this._position.copyFrom(value);
- }
- }
- this._actualPosition = null;
- this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "x", {
- /**
- * Direct access to the position.x value of the primitive
- * Use this property when you only want to change one component of the position property
- */
- get: function () {
- if (!this._position) {
- return null;
- }
- return this._position.x;
- },
- set: function (value) {
- //if (!this._checkPositionChange()) {
- // return;
- //}
- if (value == null) {
- throw new Error("Can't set a null x in primitive " + this.id + ", only the position can be turned to null");
- }
- if (this._checkUseMargin()) {
- switch (this.marginAlignment.horizontal) {
- case PrimitiveAlignment.AlignLeft:
- case PrimitiveAlignment.AlignStretch:
- case PrimitiveAlignment.AlignCenter:
- this.margin.leftPixels = value;
- break;
- case PrimitiveAlignment.AlignRight:
- this.margin.rightPixels = value;
- break;
- }
- return;
- }
- else {
- if (!this._position) {
- this._position = BABYLON.Vector2.Zero();
- }
- if (this._position.x === value) {
- return;
- }
- this._position.x = value;
- this._actualPosition = null;
- this._triggerPropertyChanged(Prim2DBase_1.positionProperty, value);
- this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "y", {
- /**
- * Direct access to the position.y value of the primitive
- * Use this property when you only want to change one component of the position property
- */
- get: function () {
- if (!this._position) {
- return null;
- }
- return this._position.y;
- },
- set: function (value) {
- //if (!this._checkPositionChange()) {
- // return;
- //}
- if (value == null) {
- throw new Error("Can't set a null y in primitive " + this.id + ", only the position can be turned to null");
- }
- if (this._checkUseMargin()) {
- switch (this.marginAlignment.vertical) {
- case PrimitiveAlignment.AlignBottom:
- case PrimitiveAlignment.AlignStretch:
- case PrimitiveAlignment.AlignCenter:
- this.margin.bottomPixels = value;
- break;
- case PrimitiveAlignment.AlignTop:
- this.margin.topPixels = value;
- break;
- }
- return;
- }
- else {
- if (!this._position) {
- this._position = BABYLON.Vector2.Zero();
- }
- if (this._position.y === value) {
- return;
- }
- this._position.y = value;
- this._actualPosition = null;
- this._triggerPropertyChanged(Prim2DBase_1.positionProperty, value);
- this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "size", {
- get: function () {
- return this.internalGetSize();
- },
- set: function (value) {
- this.internalSetSize(value);
- },
- enumerable: true,
- configurable: true
- });
- Prim2DBase.prototype.internalGetSize = function () {
- if (!this._size || this._size.width == null || this._size.height == null) {
- var bbr = Prim2DBase_1.boundinbBoxReentrency;
- if (bbr !== -1 && bbr <= (this.hierarchyDepth || 0)) {
- BABYLON.C2DLogging.setPostMessage(function () { return "re entrancy detected"; });
- return Prim2DBase_1.nullSize;
- }
- if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty)) {
- BABYLON.C2DLogging.setPostMessage(function () { return "cache hit"; });
- return this._internalSize;
- }
- BABYLON.C2DLogging.setPostMessage(function () { return "cache miss"; });
- Prim2DBase_1.boundinbBoxReentrency = this.hierarchyDepth || 0;
- var b = this.boundingInfo;
- Prim2DBase_1.boundinbBoxReentrency = -1;
- Prim2DBase_1._size.copyFrom(this._internalSize);
- b.sizeToRef(this._internalSize);
- if (!this._internalSize.equals(Prim2DBase_1._size)) {
- this._triggerPropertyChanged(Prim2DBase_1.sizeProperty, this._internalSize);
- this._positioningDirty();
- }
- return this._internalSize || Prim2DBase_1._nullSize;
- }
- else {
- BABYLON.C2DLogging.setPostMessage(function () { return "user set size"; });
- }
- return this._size || Prim2DBase_1._nullSize;
- };
- Prim2DBase.prototype.internalSetSize = function (value) {
- if (!value) {
- this._size = null;
- }
- else {
- if (!this._size) {
- this._size = value.clone();
- }
- else {
- this._size.copyFrom(value);
- }
- }
- this._actualSize = null;
- this._updatePositioningState();
- this._positioningDirty();
- };
- Object.defineProperty(Prim2DBase.prototype, "width", {
- get: function () {
- if (!this.size) {
- return null;
- }
- return this.size.width;
- },
- set: function (value) {
- if (this.size && this.size.width === value) {
- return;
- }
- if (!this.size) {
- this.size = new BABYLON.Size(value, 0);
- }
- else {
- this.size.width = value;
- }
- this._actualSize = null;
- this._triggerPropertyChanged(Prim2DBase_1.sizeProperty, value);
- this._positioningDirty();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "height", {
- get: function () {
- if (!this.size) {
- return null;
- }
- return this.size.height;
- },
- set: function (value) {
- if (this.size && this.size.height === value) {
- return;
- }
- if (!this.size) {
- this.size = new BABYLON.Size(0, value);
- }
- else {
- this.size.height = value;
- }
- this._actualSize = null;
- this._triggerPropertyChanged(Prim2DBase_1.sizeProperty, value);
- this._positioningDirty();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "rotation", {
- get: function () {
- return this._rotation;
- },
- set: function (value) {
- this._rotation = value;
- if (this._hasMargin) {
- this._positioningDirty();
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "scale", {
- get: function () {
- return this._scale.x;
- },
- set: function (value) {
- if (value <= 0) {
- throw new Error("You can't set the scale to less or equal to 0");
- }
- this._scale.x = this._scale.y = value;
- this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
- this._spreadActualScaleDirty();
- this._positioningDirty();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "actualSize", {
- get: function () {
- // If we don't use positioning engine the actual size is the size
- if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
- return this.size;
- }
- // We use the positioning engine, if the variable is fetched, it's up to date, return it
- if (this._actualSize) {
- return this._actualSize;
- }
- this._updatePositioning();
- return this._actualSize;
- },
- set: function (value) {
- if (this._actualSize && this._actualSize.equals(value)) {
- return;
- }
- if (!this._actualSize) {
- this._actualSize = value.clone();
- }
- else {
- this._actualSize.copyFrom(value);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "actualWidth", {
- get: function () {
- return this.actualSize.width;
- },
- set: function (val) {
- this._actualSize.width = val;
- this._triggerPropertyChanged(Prim2DBase_1.actualSizeProperty, this._actualSize);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "actualHeight", {
- get: function () {
- return this.actualSize.height;
- },
- set: function (val) {
- this._actualSize.height = val;
- this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualSize);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
- get: function () {
- if (this._manualZOrder != null) {
- return this._manualZOrder;
- }
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
- this._updateZOrder();
- }
- return (1 - this._zOrder);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "minSize", {
- /**
- * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
- * The Primitive's size won't be less than specified.
- * The default value depends of the Primitive type
- */
- get: function () {
- return this._minSize;
- },
- set: function (value) {
- if (this._minSize && value && this._minSize.equals(value)) {
- return;
- }
- if (!this._minSize) {
- this._minSize = value.clone();
- }
- else {
- this._minSize.copyFrom(value);
- }
- this._parentLayoutDirty();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "maxSize", {
- /**
- * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
- * The Primitive's size won't be more than specified.
- * The default value depends of the Primitive type
- */
- get: function () {
- return this._maxSize;
- },
- set: function (value) {
- if (this._maxSize && value && this._maxSize.equals(value)) {
- return;
- }
- if (!this._maxSize) {
- this._maxSize = value.clone();
- }
- else {
- this._maxSize.copyFrom(value);
- }
- this._parentLayoutDirty();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "origin", {
- /**
- * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
- * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
- * For instance:
- * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
- * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
- * 0,1 means the center is top/left
- * @returns The normalized center.
- */
- get: function () {
- return this._origin;
- },
- set: function (value) {
- if (!this._origin) {
- this._origin = value.clone();
- }
- else {
- this._origin.copyFrom(value);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
- get: function () {
- return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
- },
- set: function (value) {
- this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "isVisible", {
- get: function () {
- return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
- },
- set: function (value) {
- this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "zOrder", {
- get: function () {
- return this._manualZOrder;
- },
- set: function (value) {
- if (this._manualZOrder === value) {
- return;
- }
- this._manualZOrder = value;
- this.onZOrderChanged();
- if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
- this._actualZOrderChangedObservable.notifyObservers(value);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
- get: function () {
- return this._manualZOrder != null;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "margin", {
- get: function () {
- var _this = this;
- if (!this._margin) {
- this._margin = new PrimitiveThickness(function () {
- if (!_this.parent) {
- return null;
- }
- return _this.parent.margin;
- }, function () {
- _this._positioningDirty();
- _this._updatePositioningState();
- });
- this._updatePositioningState();
- }
- return this._margin;
- },
- set: function (value) {
- if (!value) {
- this._margin = null;
- }
- else {
- this.margin.copyFrom(value);
- }
- this._updatePositioningState();
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Set the margin from a string value
- * @param value 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.
- * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
- */
- Prim2DBase.prototype.setMargin = function (value) {
- this.margin.fromString(value);
- this._updatePositioningState();
- };
- Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
- /**
- * Check for both margin and marginAlignment, return true if at least one of them is specified with a non default value
- */
- get: function () {
- return (this._margin !== null && !this._margin.isDefault) || (this._marginAlignment !== null && !this._marginAlignment.isDefault);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "padding", {
- get: function () {
- var _this = this;
- if (!this._padding) {
- this._padding = new PrimitiveThickness(function () {
- if (!_this.parent) {
- return null;
- }
- return _this.parent.padding;
- }, function () { return _this._positioningDirty(); });
- this._updatePositioningState();
- }
- return this._padding;
- },
- set: function (value) {
- if (!value) {
- this._padding = null;
- }
- else {
- this.padding.copyFrom(value);
- }
- this._updatePositioningState();
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Set the padding from a string value
- * @param value 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.
- * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels. */
- Prim2DBase.prototype.setPadding = function (value) {
- this.padding.fromString(value);
- this._updatePositioningState();
- };
- Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
- get: function () {
- return this._padding !== null && !this._padding.isDefault;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
- get: function () {
- var _this = this;
- if (!this._marginAlignment) {
- this._marginAlignment = new PrimitiveAlignment(function () {
- _this._positioningDirty();
- _this._updatePositioningState();
- });
- this._updatePositioningState();
- }
- return this._marginAlignment;
- },
- set: function (value) {
- if (!value) {
- this._marginAlignment = null;
- }
- else {
- this.marginAlignment.copyFrom(value);
- }
- this._updatePositioningState();
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Set the margin's horizontal and or vertical alignments from a string value.
- * @param value can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
- */
- Prim2DBase.prototype.setMarginalignment = function (value) {
- this.marginAlignment.fromString(value);
- this._updatePositioningState();
- };
- Object.defineProperty(Prim2DBase.prototype, "_hasMarginAlignment", {
- /**
- * Check if there a marginAlignment specified (non null and not default)
- */
- get: function () {
- return (this._marginAlignment !== null && !this._marginAlignment.isDefault);
- },
- enumerable: true,
- configurable: true
- });
- Prim2DBase.prototype._updatePositioningState = function () {
- var value = this._hasMargin || this._hasPadding || this.isSizeAuto;
- // console.log(`${this.id} with parent ${this._parent ? this._parent.id : "[none]"} state: ${value} `);
- this._changeFlags(BABYLON.SmartPropertyPrim.flagUsePositioning, value);
- };
- Object.defineProperty(Prim2DBase.prototype, "opacity", {
- get: function () {
- return this._opacity;
- },
- set: function (value) {
- if (value < 0) {
- value = 0;
- }
- else if (value > 1) {
- value = 1;
- }
- if (this._opacity === value) {
- return;
- }
- this._opacity = value;
- this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
- this._spreadActualOpacityChanged();
- this._updateRenderMode();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "scaleX", {
- get: function () {
- return this._scale.x;
- },
- set: function (value) {
- if (value <= 0) {
- throw new Error("You can't set the scaleX to less or equal to 0");
- }
- this._scale.x = value;
- this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
- this._spreadActualScaleDirty();
- this._positioningDirty();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "scaleY", {
- get: function () {
- return this._scale.y;
- },
- set: function (value) {
- if (value <= 0) {
- throw new Error("You can't set the scaleY to less or equal to 0");
- }
- this._scale.y = value;
- this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
- this._spreadActualScaleDirty();
- this._positioningDirty();
- },
- enumerable: true,
- configurable: true
- });
- Prim2DBase.prototype._spreadActualScaleDirty = function () {
- for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
- var child = _a[_i];
- child._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
- child._spreadActualScaleDirty();
- }
- };
- Object.defineProperty(Prim2DBase.prototype, "actualScale", {
- /**
- * 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
- */
- get: function () {
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualScaleDirty)) {
- var cur = this._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : this.parent;
- var sx = this.scaleX;
- var sy = this.scaleY;
- while (cur) {
- sx *= cur.scaleX;
- sy *= cur.scaleY;
- cur = cur._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : cur.parent;
- }
- this._actualScale.copyFromFloats(sx, sy);
- this._clearFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
- }
- return this._actualScale;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "actualScaleX", {
- /**
- * Get the actual Scale of the X axis, shortcut for this.actualScale.x
- */
- get: function () {
- return this.actualScale.x;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * This method stores the actual global scale (including DesignMode and DPR related scales) in the given Vector2
- * @param res the object that will receive the actual global scale: this is actualScale * DPRScale * DesignModeScale
- */
- Prim2DBase.prototype.getActualGlobalScaleToRef = function (res) {
- var as = this.actualScale;
- var cls = this.owner._canvasLevelScale || Prim2DBase_1._iv2;
- res.x = as.x * cls.x;
- res.y = as.y * cls.y;
- };
- Object.defineProperty(Prim2DBase.prototype, "actualScaleY", {
- /**
- * Get the actual Scale of the Y axis, shortcut for this.actualScale.y
- */
- get: function () {
- return this.actualScale.y;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
- /**
- * Get the actual opacity level, this property is computed from the opacity property, multiplied by the actualOpacity of its parent (if any)
- */
- get: function () {
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
- var cur = this.parent;
- var op = this.opacity;
- while (cur) {
- op *= cur.opacity;
- cur = cur.parent;
- }
- this._actualOpacity = op;
- this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
- }
- return this._actualOpacity;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
- /**
- * Get/set the layout engine to use for this primitive.
- * The default layout engine is the CanvasLayoutEngine.
- */
- get: function () {
- if (!this._layoutEngine) {
- this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
- }
- return this._layoutEngine;
- },
- set: function (value) {
- if (this._layoutEngine === value) {
- return;
- }
- this._changeLayoutEngine(value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
- /**
- * Get/set the layout are of this primitive.
- * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
- * The setter should only be called by a Layout Engine class.
- */
- get: function () {
- return this._layoutArea;
- },
- set: function (val) {
- if (this._layoutArea && this._layoutArea.equals(val)) {
- return;
- }
- this._positioningDirty();
- this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
- if (this.parent) {
- this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
- }
- if (!this._layoutArea) {
- this._layoutArea = val.clone();
- }
- else {
- this._layoutArea.copyFrom(val);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
- /**
- * Get/set the layout area position (relative to the parent primitive).
- * The setter should only be called by a Layout Engine class.
- */
- get: function () {
- return this._layoutAreaPos;
- },
- set: function (val) {
- if (this._layoutAreaPos && this._layoutAreaPos.equals(val)) {
- return;
- }
- if (this.parent) {
- this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
- }
- this._positioningDirty();
- if (!this._layoutAreaPos) {
- this._layoutAreaPos = val.clone();
- }
- else {
- this._layoutAreaPos.copyFrom(val);
- }
- this._setFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "isPickable", {
- /**
- * Define if the Primitive can be subject to intersection test or not (default is true)
- */
- get: function () {
- return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
- },
- set: function (value) {
- this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "isContainer", {
- /**
- * Define if the Primitive acts as a container or not
- * A container will encapsulate its children for interaction event.
- * If it's not a container events will be process down to children if the primitive is not pickable.
- * Default value is true
- */
- get: function () {
- return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsContainer);
- },
- set: function (value) {
- this._changeFlags(BABYLON.SmartPropertyPrim.flagIsContainer, value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
- /**
- * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
- */
- get: function () {
- return this._hierarchyDepth;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
- /**
- * Retrieve the Group that is responsible to render this primitive
- */
- get: function () {
- return this._renderGroup;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
- /**
- * Get the global transformation matrix of the primitive
- */
- get: function () {
- if (!this._globalTransform || (this._globalTransformProcessStep !== this.owner._globalTransformProcessStep)) {
- this.updateCachedStates(false);
- }
- return this._globalTransform;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * return the global position of the primitive, relative to its canvas
- */
- Prim2DBase.prototype.getGlobalPosition = function () {
- var v = new BABYLON.Vector2(0, 0);
- this.getGlobalPositionByRef(v);
- return v;
- };
- /**
- * return the global position of the primitive, relative to its canvas
- * @param v the valid Vector2 object where the global position will be stored
- */
- Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
- v.x = this.globalTransform.m[4];
- v.y = this.globalTransform.m[5];
- };
- Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
- /**
- * Get invert of the global transformation matrix of the primitive
- */
- get: function () {
- this._updateLocalTransform();
- return this._invGlobalTransform;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "localTransform", {
- /**
- * Get the local transformation of the primitive
- */
- get: function () {
- this._updateLocalTransform();
- return this._localTransform;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "localLayoutTransform", {
- get: function () {
- this._updateLocalTransform();
- return this._localLayoutTransform;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "alignToPixel", {
- /**
- * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
- */
- get: function () {
- return this._isFlagSet(BABYLON.SmartPropertyPrim.flagAlignPrimitive);
- },
- set: function (value) {
- this._changeFlags(BABYLON.SmartPropertyPrim.flagAlignPrimitive, value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
- /**
- * Get the boundingInfo associated to the primitive and its children.
- */
- get: function () {
- // Check if we must update the boundingInfo
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
- if (this.owner) {
- this.owner.boundingInfoRecomputeCounter.addCount(1, false);
- }
- BABYLON.C2DLogging.setPostMessage(function () { return "cache miss"; });
- var sizedByContent = this.isSizedByContent;
- if (sizedByContent) {
- this._boundingInfo.clear();
- }
- else {
- this._boundingInfo.copyFrom(this.levelBoundingInfo);
- }
- if (this._children.length > 0) {
- var contentBI = new BABYLON.BoundingInfo2D();
- var tps = Prim2DBase_1._tpsBB2;
- for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
- var curChild = _a[_i];
- if (curChild._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
- continue;
- }
- var bb = curChild.layoutBoundingInfo;
- bb.transformToRef(curChild.localLayoutTransform, tps);
- contentBI.unionToRef(tps, contentBI);
- }
- // Apply padding
- if (this._hasPadding) {
- var padding = this.padding;
- var minmax = Prim2DBase_1._bMinMax;
- contentBI.minMaxToRef(minmax);
- this._paddingOffset.copyFromFloats(padding.leftPixels, padding.bottomPixels, padding.rightPixels, padding.topPixels);
- var size = Prim2DBase_1._size2;
- contentBI.sizeToRef(size);
- this._getActualSizeFromContentToRef(size, this._paddingOffset, size);
- minmax.z += this._paddingOffset.z + this._paddingOffset.x;
- minmax.w += this._paddingOffset.w + this._paddingOffset.y;
- BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(minmax.x, minmax.z, minmax.y, minmax.w, contentBI);
- }
- else {
- this._paddingOffset.copyFromFloats(0, 0, 0, 0);
- }
- this._boundingInfo.unionToRef(contentBI, this._boundingInfo);
- }
- if (sizedByContent || !this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
- this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
- }
- }
- else {
- BABYLON.C2DLogging.setPostMessage(function () { return "cache hit"; });
- }
- return this._boundingInfo;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "layoutBoundingInfo", {
- /**
- * Get the boundingInfo of the primitive's content arranged by a layout Engine
- * If a particular child is not arranged by layout, it's boundingInfo is used instead to produce something as accurate as possible
- */
- get: function () {
- var usePositioning = this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning);
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty)) {
- BABYLON.C2DLogging.setPostMessage(function () { return "cache miss"; });
- if (this._owner) {
- this._owner.addLayoutBoundingInfoUpdateCounter(1);
- }
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
- if (this._owner) {
- this._owner.addUpdateLayoutCounter(1);
- }
- this._layoutEngine.updateLayout(this);
- this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
- }
- if (usePositioning) {
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
- this._updatePositioning();
- }
- // Safety check, code re entrance is a PITA in this part of the code
- if (!this._layoutBoundingInfo) {
- BABYLON.C2DLogging.setPostMessage(function () { return "re entrance detected, boundingInfo returned"; });
- return this.boundingInfo;
- }
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
- BABYLON.C2DLogging.setPostMessage(function () { return "couldn't compute positioning, boundingInfo returned"; });
- return this.boundingInfo;
- }
- }
- if (!usePositioning) {
- var bi = this.boundingInfo;
- if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
- this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
- }
- return bi;
- }
- this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
- }
- else {
- BABYLON.C2DLogging.setPostMessage(function () { return "cache hit"; });
- }
- return usePositioning ? this._layoutBoundingInfo : this.boundingInfo;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
- /**
- * Determine if the size is automatically computed or fixed because manually specified.
- * Use the actualSize property to get the final/real size of the primitive
- * @returns true if the size is automatically computed, false if it were manually specified.
- */
- get: function () {
- var size = this._size;
- return size == null || (size.width == null && size.height == null);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "isHorizontalSizeAuto", {
- /**
- * Determine if the horizontal size is automatically computed or fixed because manually specified.
- * Use the actualSize property to get the final/real size of the primitive
- * @returns true if the horizontal size is automatically computed, false if it were manually specified.
- */
- get: function () {
- var size = this._size;
- return size == null || size.width == null;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "isVerticalSizeAuto", {
- /**
- * Determine if the vertical size is automatically computed or fixed because manually specified.
- * Use the actualSize property to get the final/real size of the primitive
- * @returns true if the vertical size is automatically computed, false if it were manually specified.
- */
- get: function () {
- var size = this._size;
- return size == null || size.height == null;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
- /**
- * Return true if this prim has an auto size which is set by the children's global bounding box
- */
- get: function () {
- return (this._size == null) && (this._children.length > 0);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
- /**
- * Determine if the position is automatically computed or fixed because manually specified.
- * Use the actualPosition property to get the final/real position of the primitive
- * @returns true if the position is automatically computed, false if it were manually specified.
- */
- get: function () {
- return this._position == null;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
- /**
- * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
- */
- get: function () {
- return this._pointerEventObservable;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
- get: function () {
- if (!this._actualZOrderChangedObservable) {
- this._actualZOrderChangedObservable = new BABYLON.Observable();
- }
- return this._actualZOrderChangedObservable;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Prim2DBase.prototype, "displayDebugAreas", {
- get: function () {
- return this._displayDebugAreas;
- },
- set: function (value) {
- if (this._displayDebugAreas === value) {
- return;
- }
- if (value === false) {
- this._debugAreaGroup.dispose();
- this._debugAreaGroup = null;
- }
- else {
- var layoutFill = "#F0808040"; // Red - Layout area
- var layoutBorder = "#F08080FF";
- var marginFill = "#F0F04040"; // Yellow - Margin area
- var marginBorder = "#F0F040FF";
- var paddingFill = "#F040F040"; // Magenta - Padding Area
- var paddingBorder = "#F040F0FF";
- var contentFill = "#40F0F040"; // Cyan - Content area
- var contentBorder = "#40F0F0FF";
- var s = new BABYLON.Size(10, 10);
- var p = BABYLON.Vector2.Zero();
- this._debugAreaGroup = new BABYLON.Group2D({
- parent: (this.parent != null) ? this.parent : this, id: "###DEBUG AREA GROUP###", children: [
- new BABYLON.Group2D({
- id: "###Layout Area###", position: p, size: s, children: [
- new BABYLON.Rectangle2D({ id: "###Layout Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: layoutBorder }),
- new BABYLON.Rectangle2D({ id: "###Layout Top###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
- new BABYLON.Rectangle2D({ id: "###Layout Left###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
- new BABYLON.Rectangle2D({ id: "###Layout Right###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
- new BABYLON.Rectangle2D({ id: "###Layout Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill })
- ]
- }),
- new BABYLON.Group2D({
- id: "###Margin Area###", position: p, size: s, children: [
- new BABYLON.Rectangle2D({ id: "###Margin Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: marginBorder }),
- new BABYLON.Rectangle2D({ id: "###Margin Top###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
- new BABYLON.Rectangle2D({ id: "###Margin Left###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
- new BABYLON.Rectangle2D({ id: "###Margin Right###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
- new BABYLON.Rectangle2D({ id: "###Margin Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill })
- ]
- }),
- new BABYLON.Group2D({
- id: "###Padding Area###", position: p, size: s, children: [
- new BABYLON.Rectangle2D({ id: "###Padding Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: paddingBorder }),
- new BABYLON.Rectangle2D({ id: "###Padding Top###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
- new BABYLON.Rectangle2D({ id: "###Padding Left###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
- new BABYLON.Rectangle2D({ id: "###Padding Right###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
- new BABYLON.Rectangle2D({ id: "###Padding Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill })
- ]
- }),
- new BABYLON.Group2D({
- id: "###Content Area###", position: p, size: s, children: [
- new BABYLON.Rectangle2D({ id: "###Content Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: contentBorder }),
- new BABYLON.Rectangle2D({ id: "###Content Top###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
- new BABYLON.Rectangle2D({ id: "###Content Left###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
- new BABYLON.Rectangle2D({ id: "###Content Right###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
- new BABYLON.Rectangle2D({ id: "###Content Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill })
- ]
- })
- ]
- });
- this._debugAreaGroup._setFlags(BABYLON.SmartPropertyPrim.flagNoPartOfLayout);
- this._updateDebugArea();
- }
- this._displayDebugAreas = value;
- },
- enumerable: true,
- configurable: true
- });
- Prim2DBase.prototype._updateDebugArea = function () {
- if (Prim2DBase_1._updatingDebugArea === true) {
- return;
- }
- Prim2DBase_1._updatingDebugArea = true;
- var areaNames = ["Layout", "Margin", "Padding", "Content"];
- var areaZones = ["Area", "Frame", "Top", "Left", "Right", "Bottom"];
- var prims = new Array(4);
- // Get all the primitives used to display the areas
- for (var i = 0; i < 4; i++) {
- prims[i] = new Array(6);
- for (var j = 0; j < 6; j++) {
- prims[i][j] = this._debugAreaGroup.findById("###" + areaNames[i] + " " + areaZones[j] + "###");
- if (j > 1) {
- prims[i][j].levelVisible = false;
- }
- }
- }
- // Update the visibility status of layout/margin/padding
- var hasLayout = this._layoutAreaPos != null;
- var hasPos = (this.actualPosition.x !== 0) || (this.actualPosition.y !== 0);
- var hasMargin = this._hasMargin;
- var hasPadding = this._hasPadding;
- prims[0][0].levelVisible = hasLayout;
- prims[1][0].levelVisible = hasMargin;
- prims[2][0].levelVisible = hasPadding;
- prims[3][0].levelVisible = true;
- // Current offset
- var curOffset = BABYLON.Vector2.Zero();
- // Store the area info of the layout area
- var curAreaIndex = 0;
- // Store data about each area
- var areaInfo = new Array(4);
- var storeAreaInfo = function (pos, size) {
- var min = pos.clone();
- var max = pos.clone();
- if (size.width > 0) {
- max.x += size.width;
- }
- if (size.height > 0) {
- max.y += size.height;
- }
- areaInfo[curAreaIndex++] = { off: pos, size: size, min: min, max: max };
- };
- var isCanvas = this instanceof BABYLON.Canvas2D;
- var marginH = this._marginOffset.x + this._marginOffset.z;
- var marginV = this._marginOffset.y + this._marginOffset.w;
- var actualSize = this.actualSize.multiplyByFloats(isCanvas ? 1 : this.scaleX, isCanvas ? 1 : this.scaleY);
- var w = hasLayout ? (this.layoutAreaPos.x + this.layoutArea.width) : (marginH + actualSize.width);
- var h = hasLayout ? (this.layoutAreaPos.y + this.layoutArea.height) : (marginV + actualSize.height);
- var pos = (!hasLayout && !hasMargin && !hasPadding && hasPos) ? this.actualPosition : BABYLON.Vector2.Zero();
- storeAreaInfo(pos, new BABYLON.Size(w, h));
- // Compute the layout related data
- if (hasLayout) {
- var layoutOffset = this.layoutAreaPos.clone();
- storeAreaInfo(layoutOffset, (hasMargin || hasPadding) ? this.layoutArea.clone() : actualSize.clone());
- curOffset = layoutOffset.clone();
- }
- // Compute margin data
- if (hasMargin) {
- var marginOffset = curOffset.clone();
- marginOffset.x += this._marginOffset.x;
- marginOffset.y += this._marginOffset.y;
- var marginArea = actualSize;
- storeAreaInfo(marginOffset, marginArea);
- curOffset = marginOffset.clone();
- }
- if (hasPadding) {
- var contentOffset = curOffset.clone();
- contentOffset.x += this._paddingOffset.x;
- contentOffset.y += this._paddingOffset.y;
- var contentArea = this.contentArea;
- storeAreaInfo(contentOffset, contentArea);
- curOffset = curOffset.add(contentOffset);
- }
- // Helper function that set the pos and size of a given prim
- var setArea = function (i, j, pos, size) {
- prims[i][j].position = pos;
- prims[i][j].size = size;
- };
- var setFullRect = function (i, pos, size) {
- var plist = prims[i];
- plist[2].levelVisible = true;
- plist[3].levelVisible = false;
- plist[4].levelVisible = false;
- plist[5].levelVisible = false;
- setArea(i, 1, pos, size);
- setArea(i, 2, pos, size);
- };
- var setQuadRect = function (i, areaIndex) {
- var plist = prims[i];
- plist[2].levelVisible = true;
- plist[3].levelVisible = true;
- plist[4].levelVisible = true;
- plist[5].levelVisible = true;
- var ca = areaInfo[areaIndex];
- var na = areaInfo[areaIndex + 1];
- var tp = new BABYLON.Vector2(ca.min.x, na.max.y);
- var ts = new BABYLON.Size(ca.size.width, ca.max.y - tp.y);
- var lp = new BABYLON.Vector2(ca.min.x, na.min.y);
- var ls = new BABYLON.Size(na.min.x - ca.min.x, na.max.y - na.min.y);
- var rp = new BABYLON.Vector2(na.max.x, na.min.y);
- var rs = new BABYLON.Size(ca.max.x - na.max.x, na.max.y - na.min.y);
- var bp = new BABYLON.Vector2(ca.min.x, ca.min.y);
- var bs = new BABYLON.Size(ca.size.width, na.min.y - ca.min.y);
- // Frame
- plist[1].position = ca.off;
- plist[1].size = ca.size;
- // Top rect
- plist[2].position = tp;
- plist[2].size = ts;
- // Left rect
- plist[3].position = lp;
- plist[3].size = ls;
- // Right rect
- plist[4].position = rp;
- plist[4].size = rs;
- // Bottom rect
- plist[5].position = bp;
- plist[5].size = bs;
- };
- var areaCount = curAreaIndex;
- curAreaIndex = 0;
- // Available zones
- var availableZones = [false, hasLayout, hasMargin, hasPadding, true];
- for (var k = 1; k < 5; k++) {
- if (availableZones[k]) {
- var ai = areaInfo[curAreaIndex];
- setArea(k - 1, 0, BABYLON.Vector2.Zero(), ai.size);
- // setArea(k-1, 1, Vector2.Zero(), ai.size);
- if (k === 4) {
- setFullRect(k - 1, ai.off, ai.size);
- }
- else {
- setQuadRect(k - 1, curAreaIndex);
- }
- ++curAreaIndex;
- }
- }
- Prim2DBase_1._updatingDebugArea = false;
- };
- Prim2DBase.prototype.findById = function (id) {
- if (this._id === id) {
- return this;
- }
- for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
- var child = _a[_i];
- var r = child.findById(id);
- if (r != null) {
- return r;
- }
- }
- };
- Prim2DBase.prototype.onZOrderChanged = function () {
- };
- Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
- return false;
- };
- /**
- * Capture all the Events of the given PointerId for this primitive.
- * Don't forget to call releasePointerEventsCapture when done.
- * @param pointerId the Id of the pointer to capture the events from.
- */
- Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
- return this.owner._setPointerCapture(pointerId, this);
- };
- /**
- * Release a captured pointer made with setPointerEventCapture.
- * @param pointerId the Id of the pointer to release the capture from.
- */
- Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
- return this.owner._releasePointerCapture(pointerId, this);
- };
- /**
- * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
- * @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.
- */
- Prim2DBase.prototype.intersect = function (intersectInfo) {
- if (!intersectInfo) {
- return false;
- }
- // If this is null it means this method is call for the first level, initialize stuffs
- var firstLevel = !intersectInfo._globalPickPosition;
- if (firstLevel) {
- // 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).
- intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
- this.globalTransform.transformPointToRef(intersectInfo.pickPosition, intersectInfo._globalPickPosition);
- intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
- intersectInfo.intersectedPrimitives = new Array();
- intersectInfo.topMostIntersectedPrimitive = null;
- }
- if (!Prim2DBase_1._bypassGroup2DExclusion && this instanceof BABYLON.Group2D && this.isCachedGroup && !this.isRenderableGroup) {
- // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
- intersectInfo._exit(firstLevel);
- return false;
- }
- if (!intersectInfo.intersectHidden && !this.isVisible) {
- // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
- intersectInfo._exit(firstLevel);
- return false;
- }
- var id = this.id;
- if (id != null && id.indexOf("__cachedSpriteOfGroup__") === 0) {
- try {
- Prim2DBase_1._bypassGroup2DExclusion = true;
- var ownerGroup = this.getExternalData("__cachedGroup__");
- if (!ownerGroup) {
- return false;
- }
- return ownerGroup.intersect(intersectInfo);
- }
- finally {
- Prim2DBase_1._bypassGroup2DExclusion = false;
- }
- }
- // 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).
- var isIntersectionTest = false;
- if (this instanceof BABYLON.Group2D) {
- var g = this;
- isIntersectionTest = g.isCachedGroup;
- }
- if (isIntersectionTest && !this.levelBoundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
- // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
- intersectInfo._exit(firstLevel);
- return false;
- }
- // Fast rejection test with boundingInfo
- var boundingIntersected = true;
- if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
- if (this.isContainer) {
- // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
- intersectInfo._exit(firstLevel);
- return false;
- }
- boundingIntersected = false;
- }
- // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
- var levelIntersectRes = false;
- if (this.isPickable) {
- levelIntersectRes = boundingIntersected && this.levelIntersect(intersectInfo);
- if (levelIntersectRes) {
- var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
- intersectInfo.intersectedPrimitives.push(pii);
- if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
- intersectInfo.topMostIntersectedPrimitive = pii;
- }
- // If we must stop at the first intersection, we're done, quit!
- if (intersectInfo.findFirstOnly) {
- intersectInfo._exit(firstLevel);
- return true;
- }
- }
- }
- // Recurse to children if needed
- if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
- for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
- var curChild = _a[_i];
- // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
- if ((!curChild.isPickable && curChild.isContainer) || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
- continue;
- }
- // Must compute the localPickLocation for the children level
- curChild.invGlobalTransform.transformPointToRef(intersectInfo._globalPickPosition, intersectInfo._localPickPosition);
- // If we got an intersection with the child and we only need to find the first one, quit!
- if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
- intersectInfo._exit(firstLevel);
- return true;
- }
- }
- }
- intersectInfo._exit(firstLevel);
- return intersectInfo.isIntersected;
- };
- Prim2DBase.prototype.intersectOtherPrim = function (other) {
- var setA = this.triList;
- var setB = other.triList;
- return BABYLON.Tri2DArray.doesIntersect(setA, setB, other.globalTransform.multiply(this.globalTransform.clone().invert()));
- };
- Object.defineProperty(Prim2DBase.prototype, "triList", {
- get: function () {
- if (this._primTriArrayDirty) {
- this.updateTriArray();
- this._primTriArrayDirty = false;
- }
- return this._primTriArray;
- },
- enumerable: true,
- configurable: true
- });
- // 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
- Prim2DBase.prototype.updateTriArray = function () {
- if (this._primTriArray == null) {
- this._primTriArray = new BABYLON.Tri2DArray(2);
- }
- else {
- this._primTriArray.clear(2);
- }
- var size = this.actualSize;
- var lb = new BABYLON.Vector2(0, 0);
- var rt = new BABYLON.Vector2(size.width, size.height);
- var lt = new BABYLON.Vector2(0, size.height);
- var rb = new BABYLON.Vector2(size.width, 0);
- this._primTriArray.storeTriangle(0, lb, lt, rt);
- this._primTriArray.storeTriangle(1, lb, rt, rb);
- };
- /**
- * Move a child object into a new position regarding its siblings to change its rendering order.
- * You can also use the shortcut methods to move top/bottom: moveChildToTop, moveChildToBottom, moveToTop, moveToBottom.
- * @param child the object to move
- * @param previous the object which will be before "child", if child has to be the first among sibling, set "previous" to null.
- */
- Prim2DBase.prototype.moveChild = function (child, previous) {
- if (child.parent !== this) {
- return false;
- }
- var childIndex = this._children.indexOf(child);
- var prevIndex = previous ? this._children.indexOf(previous) : -1;
- if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
- this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
- this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
- }
- this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
- return true;
- };
- /**
- * Move the given child so it's displayed on the top of all its siblings
- * @param child the primitive to move to the top
- */
- Prim2DBase.prototype.moveChildToTop = function (child) {
- return this.moveChild(child, this._children[this._children.length - 1]);
- };
- /**
- * Move the given child so it's displayed on the bottom of all its siblings
- * @param child the primitive to move to the top
- */
- Prim2DBase.prototype.moveChildToBottom = function (child) {
- return this.moveChild(child, null);
- };
- /**
- * Move this primitive to be at the top among all its sibling
- */
- Prim2DBase.prototype.moveToTop = function () {
- if (this.parent == null) {
- return false;
- }
- return this.parent.moveChildToTop(this);
- };
- /**
- * Move this primitive to be at the bottom among all its sibling
- */
- Prim2DBase.prototype.moveToBottom = function () {
- if (this.parent == null) {
- return false;
- }
- return this.parent.moveChildToBottom(this);
- };
- Prim2DBase.prototype.addChild = function (child) {
- child._parent = this;
- this._boundingBoxDirty();
- var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
- if (flat) {
- child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
- child._setZOrder(this._zOrder, true);
- child._zMax = this._zOrder;
- }
- else {
- this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
- }
- var length = this._children.push(child);
- this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
- child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
- };
- /**
- * Dispose the primitive, remove it from its parent.
- */
- Prim2DBase.prototype.dispose = function () {
- if (!_super.prototype.dispose.call(this)) {
- return false;
- }
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagCollisionActor)) {
- this.owner._primitiveCollisionManager._removeActor(this);
- this._actorInfo = null;
- }
- if (this._pointerEventObservable) {
- this._pointerEventObservable.clear();
- this._pointerEventObservable = null;
- }
- if (this._actionManager) {
- this._actionManager.dispose();
- this._actionManager = null;
- }
- this.owner.scene.stopAnimation(this);
- // If there's a parent, remove this object from its parent list
- if (this._parent) {
- if (this instanceof BABYLON.Group2D) {
- var g = this;
- if (g.isRenderableGroup) {
- var parentRenderable = this.parent.traverseUp(function (p) { return (p instanceof BABYLON.Group2D && p.isRenderableGroup); });
- if (parentRenderable != null) {
- var l = parentRenderable._renderableData._childrenRenderableGroups;
- var i_1 = l.indexOf(g);
- if (i_1 !== -1) {
- l.splice(i_1, 1);
- }
- }
- }
- }
- var i = this._parent._children.indexOf(this);
- if (i !== undefined) {
- this._parent._children.splice(i, 1);
- }
- this._parent = null;
- }
- // Recurse dispose to children
- if (this._children) {
- while (this._children.length > 0) {
- this._children[this._children.length - 1].dispose();
- }
- }
- return true;
- };
- Prim2DBase.prototype.onPrimBecomesDirty = function () {
- if (this._renderGroup && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
- this._renderGroup._addPrimToDirtyList(this);
- this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
- }
- };
- Prim2DBase.prototype._needPrepare = function () {
- return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty | BABYLON.SmartPropertyPrim.flagModelUpdate | BABYLON.SmartPropertyPrim.flagNeedRefresh) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
- };
- Prim2DBase.prototype._prepareRender = function (context) {
- var globalTransformStep = this.owner._globalTransformStep;
- if (this._prepareProcessStep < globalTransformStep) {
- this._prepareRenderPre(context);
- this._prepareRenderPost(context);
- this._prepareProcessStep = globalTransformStep;
- }
- };
- Prim2DBase.prototype._prepareRenderPre = function (context) {
- };
- Prim2DBase.prototype._prepareRenderPost = function (context) {
- // Don't recurse if it's a renderable group, the content will be processed by the group itself
- if (this instanceof BABYLON.Group2D) {
- var self = this;
- if (self.isRenderableGroup) {
- return;
- }
- }
- // Check if we need to recurse the prepare to children primitives
- // - must have children
- // - the global transform of this level have changed, or
- // - the visible state of primitive has changed
- if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
- this.checkPropertiesDirty(Prim2DBase_1.isVisibleProperty.flagId))) {
- this._children.forEach(function (c) {
- // As usual stop the recursion if we meet a renderable group
- if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
- c._prepareRender(context);
- }
- });
- }
- // Finally reset the dirty flags as we've processed everything
- this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
- this._instanceDirtyFlags = 0;
- };
- Prim2DBase.prototype._canvasPreInit = function (settings) {
- };
- Prim2DBase.CheckParent = function (parent) {
- //if (!Prim2DBase._isCanvasInit && !parent) {
- // 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)");
- //}
- };
- Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
- for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
- var cur = list_1[_i];
- cur.updateCachedStates(recurse);
- }
- };
- Prim2DBase.prototype._parentLayoutDirty = function () {
- if (!this._parent || this._parent.isDisposed) {
- return;
- }
- this._parent._setLayoutDirty();
- };
- Prim2DBase.prototype._setLayoutDirty = function () {
- this.onPrimBecomesDirty();
- this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
- };
- //private _checkPositionChange(): boolean {
- // if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
- // console.log(`Can't manually set the position of ${this.id}, the Layout Engine of its parent doesn't allow it`);
- // return false;
- // }
- // if (this._isFlagSet(SmartPropertyPrim.flagUsePositioning)) {
- // if (<any>this instanceof Group2D && (<Group2D><any>this).trackedNode == null) {
- // console.log(`You can't set the position/x/y of ${this.id} properties while positioning engine is used (margin, margin alignment and/or padding are set`);
- // return false;
- // }
- // }
- // return true;
- //}
- Prim2DBase.prototype._checkUseMargin = function () {
- // Special cae: tracked node
- if (this instanceof BABYLON.Group2D && this.trackedNode != null) {
- return false;
- }
- return this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning);
- };
- Prim2DBase.prototype._positioningDirty = function () {
- if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
- return;
- }
- this.onPrimBecomesDirty();
- this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
- };
- Prim2DBase.prototype._spreadActualOpacityChanged = function () {
- for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
- var child = _a[_i];
- child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
- child._updateRenderMode();
- child.onPrimBecomesDirty();
- child._spreadActualOpacityChanged();
- }
- };
- Prim2DBase.prototype._changeLayoutEngine = function (engine) {
- this._layoutEngine = engine;
- };
- Prim2DBase.prototype._updateLocalTransform = function () {
- 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;
- if (this.checkPropertiesDirty(tflags) || this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLocalTransformDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
- if (this.owner) {
- this.owner.addupdateLocalTransformCounter(1);
- }
- // Check for positioning update
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
- this._updatePositioning();
- }
- var rot = this._rotation;
- var local;
- var pos = this._position ? this.position : (this.layoutAreaPos || Prim2DBase_1._v0);
- var postScale = this._postScale;
- var canvasScale = Prim2DBase_1._iv2;
- //let hasCanvasScale = false;
- //if (this._parent instanceof Canvas2D) {
- // hasCanvasScale = true;
- // canvasScale = (this._parent as Canvas2D)._canvasLevelScale || Prim2DBase._iv2;
- //}
- var globalScale = this._scale.multiplyByFloats(/*postScale.x**/ canvasScale.x, /*postScale.y**/ canvasScale.y);
- if ((this._origin.x === 0 && this._origin.y === 0) || this._hasMargin) {
- local = BABYLON.Matrix2D.Compose(globalScale, rot, new BABYLON.Vector2(pos.x + this._marginOffset.x, pos.y + this._marginOffset.y));
- this._localTransform = local;
- this._localLayoutTransform = BABYLON.Matrix2D.Compose(globalScale, rot, new BABYLON.Vector2(pos.x, pos.y));
- }
- else {
- // -Origin offset
- var t0 = Prim2DBase_1._t0;
- var t1 = Prim2DBase_1._t1;
- var t2 = Prim2DBase_1._t2;
- var as = Prim2DBase_1._ts0;
- as.copyFrom(this.actualSize);
- //as.width /= postScale.x;
- //as.height /= postScale.y;
- BABYLON.Matrix2D.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), t0);
- // -Origin * rotation
- BABYLON.Matrix2D.RotationToRef(rot, t1);
- t0.multiplyToRef(t1, t2);
- BABYLON.Matrix2D.ScalingToRef(this._scale.x, this._scale.y, t0);
- t2.multiplyToRef(t0, t1);
- BABYLON.Matrix2D.TranslationToRef((as.width * this._origin.x), (as.height * this._origin.y), t2);
- t1.multiplyToRef(t2, t0);
- BABYLON.Matrix2D.ScalingToRef(postScale.x, postScale.y, t1);
- t0.multiplyToRef(t1, t2);
- BABYLON.Matrix2D.TranslationToRef(pos.x + this._marginOffset.x, pos.y + this._marginOffset.y, t0);
- t2.multiplyToRef(t0, this._localTransform);
- //if (hasCanvasScale) {
- // Matrix2D.ScalingToRef(canvasScale.x, canvasScale.y, Prim2DBase._t1);
- // this._localTransform.multiplyToRef(Prim2DBase._t1, this._localTransform);
- //}
- this._localLayoutTransform = BABYLON.Matrix2D.Compose(globalScale, rot, pos);
- }
- this.clearPropertiesDirty(tflags);
- this._setFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
- this._clearFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty);
- return true;
- }
- return false;
- };
- Prim2DBase.prototype.updateCachedStates = function (recurse) {
- if (this.isDisposed) {
- BABYLON.C2DLogging.setPostMessage(function () { return "disposed"; });
- return;
- }
- var ownerProcessStep = this.owner._globalTransformProcessStep;
- if (this._updateCachesProcessStep === ownerProcessStep) {
- return;
- }
- this._updateCachesProcessStep = ownerProcessStep;
- this.owner.addUpdateCachedStateCounter(1);
- // Check if the parent is synced
- if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
- this._parent.updateCachedStates(false);
- }
- // Update Z-Order if needed
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
- this._updateZOrder();
- }
- // Update actualSize only if there' not positioning to recompute and the size changed
- // Otherwise positioning will take care of it.
- var sizeDirty = this.checkPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
- if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
- var size = this.size;
- this.onPropertyChanged("actualSize", size, size, Prim2DBase_1.actualSizeProperty.flagId);
- this.clearPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
- }
- var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
- var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
- // Check for layout update
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
- this.owner.addUpdateLayoutCounter(1);
- this._layoutEngine.updateLayout(this);
- this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
- }
- var autoContentChanged = false;
- if (this.isSizeAuto) {
- if (!this._lastAutoSizeArea) {
- autoContentChanged = this.actualSize !== null;
- }
- else {
- autoContentChanged = (!this._lastAutoSizeArea.equals(this.actualSize));
- }
- }
- // Check for positioning update
- if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
- this._updatePositioning();
- if (sizeDirty) {
- this.clearPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
- }
- positioningComputed = true;
- }
- if (positioningComputed && this._parent) {
- this._parentContentArea.copyFrom(this._parent.contentArea);
- }
- // Check if we must update this prim
- if (!this._globalTransform || (this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || (this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty))) {
- this.owner.addUpdateGlobalTransformCounter(1);
- var curVisibleState = this.isVisible;
- this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
- // Detect a change of visibility
- this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
- // Get/compute the localTransform
- var localDirty = this._updateLocalTransform();
- var parentPaddingChanged = false;
- var parentPaddingOffset = Prim2DBase_1._v0;
- if (this._parent) {
- parentPaddingOffset = new BABYLON.Vector2(this._parent._paddingOffset.x, this._parent._paddingOffset.y);
- parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
- }
- // Check if there are changes in the parent that will force us to update the global matrix
- var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
- // Check if we have to update the globalTransform
- if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged || this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty)) {
- var globalTransform = this._parent ? this._parent._globalTransform : null;
- var localTransform = void 0;
- Prim2DBase_1._transMtx.copyFrom(this._localTransform);
- Prim2DBase_1._transMtx.m[4] += parentPaddingOffset.x;
- Prim2DBase_1._transMtx.m[5] += parentPaddingOffset.y;
- localTransform = Prim2DBase_1._transMtx;
- this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
- this._invGlobalTransform = BABYLON.Matrix2D.Invert(this._globalTransform);
- this._levelBoundingInfo.dirtyWorldAABB();
- this._boundingInfo.dirtyWorldAABB();
- this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
- this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
- this._clearFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
- }
- this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
- }
- if (recurse) {
- for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
- var child = _a[_i];
- // Stop the recursion if we meet a renderable group
- child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
- }
- }
- };
- Prim2DBase.prototype._updatePositioning = function () {
- if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
- BABYLON.C2DLogging.setPostMessage(function () { return "Not using positioning engine"; });
- // Just in case, if may happen and if we don't clear some computation will keep going on forever
- this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
- return;
- }
- var success = true;
- // Check if re-entrance is occurring
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagComputingPositioning) /* || (hasMargin && !this._layoutArea)*/) {
- if (!this._actualSize) {
- this._actualSize = this.size.clone() || BABYLON.Size.Zero();
- this._contentArea.copyFrom(this._actualSize);
- }
- if (!this._actualPosition) {
- this._actualPosition = BABYLON.Vector2.Zero();
- }
- BABYLON.C2DLogging.setPostMessage(function () { return "Re entrance detected"; });
- return;
- }
- if (this.owner) {
- this.owner.addUpdatePositioningCounter(1);
- }
- // Set the flag to avoid re-entrance
- this._setFlags(BABYLON.SmartPropertyPrim.flagComputingPositioning);
- try {
- var isSizeAuto = this.isSizeAuto;
- var isVSizeAuto = this.isVerticalSizeAuto;
- var isHSizeAuto = this.isHorizontalSizeAuto;
- var ma = this._marginAlignment ? this._marginAlignment.clone() : new PrimitiveAlignment();
- var levelScale = this._scale;
- var primSize = this.size;
- // If the primitive has no size and is autoSized without margin, then set a Stretch/Stretch margin alignment for the primitive to take all the available space
- if (!this._hasMarginAlignment && (isSizeAuto && (primSize === Prim2DBase_1.nullSize || (primSize === this._internalSize && primSize.width === 0 && primSize.height === 0)))) {
- if (isSizeAuto || this.actualSize.width == null) {
- ma.horizontal = PrimitiveAlignment.AlignStretch;
- }
- if (isSizeAuto || this.actualSize.height == null) {
- ma.vertical = PrimitiveAlignment.AlignStretch;
- }
- }
- var transformedBSize = Prim2DBase_1._size3;
- var bSize = Prim2DBase_1._size4;
- var bi = this.boundingInfo;
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
- success = false;
- }
- var tbi = Prim2DBase_1._tbi;
- bi.transformToRef(BABYLON.Matrix2D.Rotation(this.rotation), tbi);
- tbi.sizeToRef(transformedBSize);
- bi.sizeToRef(bSize);
- bi.extent.subtractToRef(bi.center, Prim2DBase_1._pv1);
- tbi.center.subtractToRef(tbi.extent, Prim2DBase_1._pv2);
- var transbi = Prim2DBase_1._pv2.add(Prim2DBase_1._pv1);
- var setSize = false;
- var hasMargin = (this._margin !== null && !this._margin.isDefault) || (ma !== null && !ma.isDefault);
- var primNewSize = Prim2DBase_1._size;
- var hasH = false;
- var hasV = false;
- //let paddingApplied = false;
- var hasPadding = this._hasPadding;
- // Compute the size
- // The size is the size of the prim or the computed one if there's a marginAlignment of Stretch
- if (hasMargin) {
- var layoutArea = this.layoutArea;
- if (layoutArea /*&& layoutArea.width >= size.width */ && ma.horizontal === PrimitiveAlignment.AlignStretch) {
- this.margin.computeWithAlignment(layoutArea, primSize, ma, levelScale, this._marginOffset, primNewSize, false, PrimitiveThickness.ComputeH);
- hasH = true;
- setSize = true;
- }
- if (layoutArea /*&& layoutArea.height >= size.height */ && ma.vertical === PrimitiveAlignment.AlignStretch) {
- this.margin.computeWithAlignment(layoutArea, primSize, ma, levelScale, this._marginOffset, primNewSize, false, PrimitiveThickness.ComputeV);
- hasV = true;
- setSize = true;
- }
- }
- if (!hasH) {
- // If the Horizontal size is Auto, we have to compute it from its content and padding
- if (isHSizeAuto) {
- primNewSize.width = bSize.width;
- setSize = true;
- }
- else {
- primNewSize.width = primSize.width;
- }
- }
- if (!hasV) {
- // If the Vertical size is Auto, we have to compute it from its content and padding
- if (isVSizeAuto) {
- primNewSize.height = bSize.height;
- setSize = true;
- }
- else {
- primNewSize.height = primSize.height;
- }
- }
- Prim2DBase_1._curContentArea.copyFrom(this._contentArea);
- if (hasPadding) {
- var area = Prim2DBase_1._icArea;
- var zone = Prim2DBase_1._icZone;
- this._getInitialContentAreaToRef(primNewSize, zone, area);
- area.width = Math.max(0, area.width);
- area.height = Math.max(0, area.height);
- this.padding.compute(area, this._paddingOffset, Prim2DBase_1._size2);
- if (!isHSizeAuto) {
- this._paddingOffset.x += zone.x;
- this._paddingOffset.z -= zone.z;
- this._contentArea.width = Prim2DBase_1._size2.width;
- }
- if (!isVSizeAuto) {
- this._paddingOffset.y += zone.y;
- this._paddingOffset.w -= zone.w;
- this._contentArea.height = Prim2DBase_1._size2.height;
- }
- }
- else {
- this._contentArea.copyFrom(primNewSize);
- }
- if (!Prim2DBase_1._curContentArea.equals(this._contentArea)) {
- this._setLayoutDirty();
- }
- // Finally we apply margin to determine the position
- if (hasMargin) {
- var layoutArea = this.layoutArea;
- var mo = this._marginOffset;
- var margin = this.margin;
- // We compute margin only if the layoutArea is "real": a valid object with dimensions greater than 0
- // otherwise sometimes this code would be triggered with and invalid layoutArea, resulting to an invalid positioning
- // So we make sure with compute alignment only if the layoutArea is good
- if (layoutArea && layoutArea.width > 0 && layoutArea.height > 0) {
- margin.computeWithAlignment(layoutArea, transformedBSize, ma, levelScale, mo, Prim2DBase_1._size2);
- }
- else {
- mo.copyFromFloats(0, 0, 0, 0);
- }
- var tbi_1 = Prim2DBase_1._tpsBB;
- tbi_1.copyFrom(bi);
- var minmax = Prim2DBase_1._bMinMax;
- tbi_1.minMaxToRef(minmax);
- minmax.z += margin.leftPixels + margin.rightPixels;
- minmax.w += margin.topPixels + margin.bottomPixels;
- BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(minmax.x, minmax.z, minmax.y, minmax.w, tbi_1);
- // Check if the layoutBoundingInfo changed
- var changed = false;
- if (!this._layoutBoundingInfo) {
- this._layoutBoundingInfo = tbi_1.clone();
- changed = true;
- }
- else if (!this._layoutBoundingInfo.equals(tbi_1)) {
- this._layoutBoundingInfo.copyFrom(tbi_1);
- changed = true;
- }
- if (changed) {
- var p = this._parent;
- while (p) {
- if (p.isSizedByContent) {
- p._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
- p.onPrimitivePropertyDirty(Prim2DBase_1.actualSizeProperty.flagId);
- }
- else {
- break;
- }
- p = p._parent;
- }
- this.onPrimitivePropertyDirty(Prim2DBase_1.actualSizeProperty.flagId);
- }
- this._marginOffset.x -= transbi.x * levelScale.x;
- this._marginOffset.y -= transbi.y * levelScale.y;
- }
- var lap = this.layoutAreaPos;
- this.actualPosition = new BABYLON.Vector2(this._marginOffset.x + (lap ? lap.x : 0), this._marginOffset.y + (lap ? lap.y : 0));
- // if (setSize) {
- this.actualSize = primNewSize.clone();
- // }
- this._setFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty);
- if (isSizeAuto) {
- this._lastAutoSizeArea = this.actualSize;
- }
- if (this.displayDebugAreas) {
- this._updateDebugArea();
- }
- }
- finally {
- BABYLON.C2DLogging.setPostMessage(function () { return "Succeeded"; });
- this._clearFlags(BABYLON.SmartPropertyPrim.flagComputingPositioning);
- // Remove dirty flag
- if (success) {
- this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
- }
- }
- };
- Object.defineProperty(Prim2DBase.prototype, "contentArea", {
- /**
- * Get the content are of this primitive, this area is computed the primitive size and using the padding property.
- * Children of this primitive will be positioned relative to the bottom/left corner of this area.
- */
- get: function () {
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
- this._updatePositioning();
- }
- return this._contentArea;
- }
- else {
- return this.size;
- }
- },
- enumerable: true,
- configurable: true
- });
- Prim2DBase.prototype._patchHierarchy = function (owner) {
- if (this._owner == null) {
- this._owner = owner;
- this.onSetOwner();
- this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
- }
- // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
- if (this._renderGroup != null) {
- return;
- }
- if (this instanceof BABYLON.Group2D) {
- var group = this;
- group.detectGroupStates();
- if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
- group.owner._registerTrackedNode(this);
- }
- }
- this._renderGroup = this.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
- if (this._parent) {
- this._parentLayoutDirty();
- }
- // Make sure the prim is in the dirtyList if it should be
- if (this._renderGroup && this.isDirty) {
- var list = this._renderGroup._renderableData._primDirtyList;
- var i = list.indexOf(this);
- if (i === -1) {
- this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
- list.push(this);
- }
- }
- // Recurse
- for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
- var child = _a[_i];
- child._hierarchyDepth = this._hierarchyDepth + 1;
- child._patchHierarchy(owner);
- }
- };
- Prim2DBase.prototype.onSetOwner = function () {
- };
- Prim2DBase.prototype._updateZOrder = function () {
- var prevLinPos = this._primLinearPosition;
- var startI = 0;
- var startZ = this._zOrder;
- // 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
- var childrenCount = this._children.length;
- if (this._firstZDirtyIndex > 0) {
- if ((this._firstZDirtyIndex - 1) < childrenCount) {
- var prevPrim = this._children[this._firstZDirtyIndex - 1];
- prevLinPos = prevPrim._primLinearPosition;
- startI = this._firstZDirtyIndex - 1;
- startZ = prevPrim._zOrder;
- }
- }
- var startPos = prevLinPos;
- // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
- Prim2DBase_1._totalCount = 0;
- for (var i = startI; i < childrenCount; i++) {
- var child = this._children[i];
- prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
- }
- // Compute the new Z-Order for all the primitives
- // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
- var zDelta = (this._zMax - startZ) / (Prim2DBase_1._totalCount * (Prim2DBase_1._zRebuildReentrency ? 1 : 1.2));
- // 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.
- if (zDelta < BABYLON.Canvas2D._zMinDelta) {
- // 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...
- if (Prim2DBase_1._zRebuildReentrency) {
- var p = this._parent;
- if (p == null) {
- // 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...)
- console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
- Prim2DBase_1._zRebuildReentrency = false;
- return;
- }
- p._firstZDirtyIndex = 0;
- return p._updateZOrder();
- }
- Prim2DBase_1._zRebuildReentrency = true;
- this._firstZDirtyIndex = 0;
- this._updateZOrder();
- Prim2DBase_1._zRebuildReentrency = false;
- }
- for (var i = startI; i < childrenCount; i++) {
- var child = this._children[i];
- child._updatePrimitiveZOrder(startPos, startZ, zDelta);
- }
- // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
- for (var _i = 0, _a = Prim2DBase_1._zOrderChangedNotifList; _i < _a.length; _i++) {
- var p = _a[_i];
- p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
- }
- Prim2DBase_1._zOrderChangedNotifList.splice(0);
- this._firstZDirtyIndex = Prim2DBase_1._bigInt;
- this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
- };
- Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
- if (this.isManualZOrder) {
- return prevLinPos;
- }
- this._primLinearPosition = ++prevLinPos;
- Prim2DBase_1._totalCount++;
- // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
- if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
- for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
- var child = _a[_i];
- prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
- }
- }
- return prevLinPos;
- };
- Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
- if (this.isManualZOrder) {
- return null;
- }
- var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
- var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
- this._setZOrder(newZ, false);
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
- this._firstZDirtyIndex = Prim2DBase_1._bigInt;
- this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
- }
- var curZ = newZ;
- // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
- if (isFlat) {
- if (this._children.length > 0) {
- //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
- for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
- var child = _a[_i];
- child._updatePrimitiveFlatZOrder(this._zOrder);
- }
- }
- }
- else {
- for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
- var child = _c[_b];
- var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
- if (r != null) {
- curZ = r;
- }
- }
- }
- this._zMax = isFlat ? newZ : (curZ + deltaZ);
- return curZ;
- };
- Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
- if (this.isManualZOrder) {
- return;
- }
- this._setZOrder(newZ, false);
- this._zMax = newZ;
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
- this._firstZDirtyIndex = Prim2DBase_1._bigInt;
- this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
- }
- for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
- var child = _a[_i];
- child._updatePrimitiveFlatZOrder(newZ);
- }
- };
- Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
- if (newZ !== this._zOrder) {
- this._zOrder = newZ;
- this.onPrimBecomesDirty();
- this.onZOrderChanged();
- if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
- if (directEmit) {
- this._actualZOrderChangedObservable.notifyObservers(newZ);
- }
- else {
- Prim2DBase_1._zOrderChangedNotifList.push(this);
- }
- }
- }
- };
- Prim2DBase.prototype._updateRenderMode = function () {
- };
- /**
- * This method is used to alter the contentArea of the Primitive before margin is applied.
- * 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.
- * @param primSize the current size of the primitive
- * @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
- * @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!
- */
- Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
- initialContentArea.copyFrom(primSize);
- initialContentPosition.x = initialContentPosition.y = initialContentPosition.z = initialContentPosition.w = 0;
- };
- /**
- * This method is used to calculate the new size of the primitive based on the content which must stay the same
- * Check the Rectangle2D implementation for a concrete application.
- * @param primSize the current size of the primitive
- * @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!
- */
- Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, paddingOffset, newPrimSize) {
- newPrimSize.copyFrom(primSize);
- };
- Object.defineProperty(Prim2DBase.prototype, "layoutData", {
- /**
- * Get/set the layout data to use for this primitive.
- */
- get: function () {
- return this._layoutData;
- },
- set: function (value) {
- if (this._layoutData === value) {
- return;
- }
- this._layoutData = value;
- },
- enumerable: true,
- configurable: true
- });
- return Prim2DBase;
- }(BABYLON.SmartPropertyPrim));
- Prim2DBase.PRIM2DBASE_PROPCOUNT = 25;
- Prim2DBase._bigInt = Math.pow(2, 30);
- Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
- Prim2DBase._nullSize = BABYLON.Size.Zero();
- Prim2DBase.boundinbBoxReentrency = -1;
- Prim2DBase.nullSize = BABYLON.Size.Zero();
- Prim2DBase._bMinMax = BABYLON.Vector4.Zero();
- Prim2DBase._bMax = BABYLON.Vector2.Zero();
- Prim2DBase._bSize = BABYLON.Size.Zero();
- Prim2DBase._tpsBB = new BABYLON.BoundingInfo2D();
- Prim2DBase._tpsBB2 = new BABYLON.BoundingInfo2D();
- Prim2DBase._updatingDebugArea = false;
- Prim2DBase._bypassGroup2DExclusion = false;
- Prim2DBase._isCanvasInit = false;
- Prim2DBase._t0 = new BABYLON.Matrix2D();
- Prim2DBase._t1 = new BABYLON.Matrix2D();
- Prim2DBase._t2 = new BABYLON.Matrix2D();
- Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
- Prim2DBase._v30 = BABYLON.Vector3.Zero(); // Must stay with the value 0,0,0
- Prim2DBase._iv2 = new BABYLON.Vector2(1, 1); // Must stay identity vector
- Prim2DBase._ts0 = BABYLON.Size.Zero();
- Prim2DBase._transMtx = BABYLON.Matrix2D.Zero();
- Prim2DBase._icPos = BABYLON.Vector2.Zero();
- Prim2DBase._icZone = BABYLON.Vector4.Zero();
- Prim2DBase._icArea = BABYLON.Size.Zero();
- Prim2DBase._size = BABYLON.Size.Zero();
- Prim2DBase._size2 = BABYLON.Size.Zero();
- Prim2DBase._size3 = BABYLON.Size.Zero();
- Prim2DBase._size4 = BABYLON.Size.Zero();
- Prim2DBase._pv0 = BABYLON.Vector2.Zero();
- Prim2DBase._curContentArea = BABYLON.Size.Zero();
- Prim2DBase._piv = new BABYLON.Vector2(1, 1);
- Prim2DBase._tbi = new BABYLON.BoundingInfo2D();
- Prim2DBase._pv1 = BABYLON.Vector2.Zero();
- Prim2DBase._pv2 = BABYLON.Vector2.Zero();
- Prim2DBase._zOrderChangedNotifList = new Array();
- Prim2DBase._zRebuildReentrency = false;
- Prim2DBase._totalCount = 0;
- __decorate([
- BABYLON.logProp(null, false, false, false),
- BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase_1.actualPositionProperty = pi; }, false, false, true)
- /**
- * Return the position where the primitive is rendered in the Canvas, this position may be different than the one returned by the position property due to layout/alignment/margin/padding computing.
- * BEWARE: don't change this value, it's read-only!
- */
- ], Prim2DBase.prototype, "actualPosition", null);
- __decorate([
- BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 1, function (pi) { return Prim2DBase_1.actualXProperty = pi; }, false, false, true)
- ], Prim2DBase.prototype, "actualX", null);
- __decorate([
- BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 2, function (pi) { return Prim2DBase_1.actualYProperty = pi; }, false, false, true)
- ], Prim2DBase.prototype, "actualY", null);
- __decorate([
- BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 3, function (pi) { return Prim2DBase_1.positionProperty = pi; }, false, false, true)
- ], Prim2DBase.prototype, "position", null);
- __decorate([
- BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 4, function (pi) { return Prim2DBase_1.xProperty = pi; }, false, false, true)
- ], Prim2DBase.prototype, "x", null);
- __decorate([
- BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 5, function (pi) { return Prim2DBase_1.yProperty = pi; }, false, false, true)
- ], Prim2DBase.prototype, "y", null);
- __decorate([
- BABYLON.logProp(),
- BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 6, function (pi) { return Prim2DBase_1.sizeProperty = pi; }, false, true)
- /**
- * Size of the primitive or its bounding area
- * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
- * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
- */
- ], Prim2DBase.prototype, "size", null);
- __decorate([
- BABYLON.logMethod()
- ], Prim2DBase.prototype, "internalGetSize", null);
- __decorate([
- BABYLON.logMethod()
- ], Prim2DBase.prototype, "internalSetSize", null);
- __decorate([
- BABYLON.logProp(),
- BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 7, function (pi) { return Prim2DBase_1.widthProperty = pi; }, false, true)
- /**
- * Direct access to the size.width value of the primitive
- * Use this property when you only want to change one component of the size property
- */
- ], Prim2DBase.prototype, "width", null);
- __decorate([
- BABYLON.logProp(),
- BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 8, function (pi) { return Prim2DBase_1.heightProperty = pi; }, false, true)
- /**
- * Direct access to the size.height value of the primitive
- * Use this property when you only want to change one component of the size property
- */
- ], Prim2DBase.prototype, "height", null);
- __decorate([
- BABYLON.logProp(),
- BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 9, function (pi) { return Prim2DBase_1.rotationProperty = pi; }, false, true)
- /**
- * Rotation of the primitive, in radian, along the Z axis
- */
- ], Prim2DBase.prototype, "rotation", null);
- __decorate([
- BABYLON.logProp(),
- BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 10, function (pi) { return Prim2DBase_1.scaleProperty = pi; }, false, true)
- /**
- * Uniform scale applied on the primitive. If a non-uniform scale is applied through scaleX/scaleY property the getter of this property will return scaleX.
- */
- ], Prim2DBase.prototype, "scale", null);
- __decorate([
- BABYLON.logProp(),
- BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 11, function (pi) { return Prim2DBase_1.actualSizeProperty = pi; }, false, true)
- /**
- * Return the size of the primitive as it's being rendered into the target.
- * 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.
- * BEWARE: don't use the setter, it's for internal purpose only
- * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
- */
- ], Prim2DBase.prototype, "actualSize", null);
- __decorate([
- BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 12, function (pi) { return Prim2DBase_1.actualWidthProperty = pi; }, false, true)
- /**
- * Shortcut to actualSize.width
- */
- ], Prim2DBase.prototype, "actualWidth", null);
- __decorate([
- BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 13, function (pi) { return Prim2DBase_1.actualHeightProperty = pi; }, false, true)
- /**
- * Shortcut to actualPosition.height
- */
- ], Prim2DBase.prototype, "actualHeight", null);
- __decorate([
- BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 14, function (pi) { return Prim2DBase_1.originProperty = pi; }, false, true)
- ], Prim2DBase.prototype, "origin", null);
- __decorate([
- BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 15, function (pi) { return Prim2DBase_1.levelVisibleProperty = pi; })
- /**
- * Let the user defines if the Primitive is hidden or not at its level. As Primitives inherit the hidden status from their parent, only the isVisible property give properly the real visible state.
- * Default is true, setting to false will hide this primitive and its children.
- */
- ], Prim2DBase.prototype, "levelVisible", null);
- __decorate([
- BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 16, function (pi) { return Prim2DBase_1.isVisibleProperty = pi; })
- /**
- * Use ONLY THE GETTER to determine if the primitive is visible or not.
- * The Setter is for internal purpose only!
- */
- ], Prim2DBase.prototype, "isVisible", null);
- __decorate([
- BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 17, function (pi) { return Prim2DBase_1.zOrderProperty = pi; })
- /**
- * You can override the default Z Order through this property, but most of the time the default behavior is acceptable
- */
- ], Prim2DBase.prototype, "zOrder", null);
- __decorate([
- BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 18, function (pi) { return Prim2DBase_1.marginProperty = pi; })
- /**
- * You can get/set a margin on the primitive through this property
- * @returns the margin object, if there was none, a default one is created and returned
- */
- ], Prim2DBase.prototype, "margin", null);
- __decorate([
- BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 19, function (pi) { return Prim2DBase_1.paddingProperty = pi; })
- /**
- * You can get/set a margin on the primitive through this property
- * @returns the margin object, if there was none, a default one is created and returned
- */
- ], Prim2DBase.prototype, "padding", null);
- __decorate([
- BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 20, function (pi) { return Prim2DBase_1.marginAlignmentProperty = pi; })
- /**
- * You can get/set the margin alignment through this property
- */
- ], Prim2DBase.prototype, "marginAlignment", null);
- __decorate([
- BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 21, function (pi) { return Prim2DBase_1.opacityProperty = pi; })
- /**
- * Get/set the opacity of the whole primitive
- */
- ], Prim2DBase.prototype, "opacity", null);
- __decorate([
- BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 22, function (pi) { return Prim2DBase_1.scaleXProperty = pi; }, false, true)
- /**
- * Scale applied on the X axis of the primitive
- */
- ], Prim2DBase.prototype, "scaleX", null);
- __decorate([
- BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 23, function (pi) { return Prim2DBase_1.scaleYProperty = pi; }, false, true)
- /**
- * Scale applied on the Y axis of the primitive
- */
- ], Prim2DBase.prototype, "scaleY", null);
- __decorate([
- BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 24, function (pi) { return Prim2DBase_1.actualScaleProperty = pi; }, false, true)
- ], Prim2DBase.prototype, "actualScale", null);
- __decorate([
- BABYLON.logProp("", true)
- ], Prim2DBase.prototype, "boundingInfo", null);
- __decorate([
- BABYLON.logProp("", true)
- ], Prim2DBase.prototype, "layoutBoundingInfo", null);
- __decorate([
- BABYLON.logMethod("", true)
- ], Prim2DBase.prototype, "_setLayoutDirty", null);
- __decorate([
- BABYLON.logMethod("", true)
- ], Prim2DBase.prototype, "_positioningDirty", null);
- __decorate([
- BABYLON.logMethod()
- ], Prim2DBase.prototype, "updateCachedStates", null);
- __decorate([
- BABYLON.logMethod()
- ], Prim2DBase.prototype, "_updatePositioning", null);
- Prim2DBase = Prim2DBase_1 = __decorate([
- BABYLON.className("Prim2DBase", "BABYLON")
- /**
- * Base class for a Primitive of the Canvas2D feature
- */
- ], Prim2DBase);
- BABYLON.Prim2DBase = Prim2DBase;
- var PrimitiveAlignment_1, PrimitiveThickness_1, Prim2DBase_1;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.prim2dBase.js.map
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var BABYLON;
- (function (BABYLON) {
- var GroupInstanceInfo = (function () {
- function GroupInstanceInfo(owner, mrc, partCount) {
- this._partCount = partCount;
- this._primCount = 0;
- this.owner = owner;
- this.modelRenderCache = mrc;
- this.modelRenderCache.addRef();
- this.partIndexFromId = new BABYLON.StringDictionary();
- this._usedShaderCategories = new Array(partCount);
- this._strides = new Array(partCount);
- this._opaqueData = null;
- this._alphaTestData = null;
- this._transparentData = null;
- this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
- }
- GroupInstanceInfo.prototype.incPrimCount = function () {
- ++this._primCount;
- };
- GroupInstanceInfo.prototype.dispose = function () {
- if (this._isDisposed) {
- return false;
- }
- // Disposed is called when a primitive instance is disposed, so we decrement the counter
- --this._primCount;
- // If the counter is still greater than 0 there's still other primitives using this GII
- if (this._primCount > 0) {
- return false;
- }
- // We're going to dispose this GII, first remove it from the dictionary
- this.owner._renderableData._renderGroupInstancesInfo.remove(this.modelRenderCache.modelKey);
- if (this.modelRenderCache) {
- this.modelRenderCache.dispose();
- this.modelRenderCache = null;
- }
- var engine = this.owner.owner.engine;
- if (this._opaqueData) {
- this._opaqueData.forEach(function (d) { return d.dispose(engine); });
- this._opaqueData = null;
- }
- if (this._alphaTestData) {
- this._alphaTestData.forEach(function (d) { return d.dispose(engine); });
- this._alphaTestData = null;
- }
- if (this._transparentData) {
- this._transparentData.forEach(function (d) { return d.dispose(engine); });
- this._transparentData = null;
- }
- this.partIndexFromId = null;
- this._isDisposed = true;
- return true;
- };
- Object.defineProperty(GroupInstanceInfo.prototype, "isDisposed", {
- get: function () {
- return this._isDisposed;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
- get: function () {
- return this._opaqueData != null;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
- get: function () {
- return this._alphaTestData != null;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
- get: function () {
- return this._transparentData != null;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
- get: function () {
- if (!this._opaqueData) {
- this._opaqueData = new Array(this._partCount);
- for (var i = 0; i < this._partCount; i++) {
- this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
- }
- }
- return this._opaqueData;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
- get: function () {
- if (!this._alphaTestData) {
- this._alphaTestData = new Array(this._partCount);
- for (var i = 0; i < this._partCount; i++) {
- this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
- }
- }
- return this._alphaTestData;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
- get: function () {
- if (!this._transparentData) {
- this._transparentData = new Array(this._partCount);
- for (var i = 0; i < this._partCount; i++) {
- var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
- this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
- }
- }
- return this._transparentData;
- },
- enumerable: true,
- configurable: true
- });
- GroupInstanceInfo.prototype.sortTransparentData = function () {
- if (!this.transparentOrderDirty) {
- return;
- }
- for (var i = 0; i < this._transparentData.length; i++) {
- var td = this._transparentData[i];
- td._partData.sort();
- }
- this.transparentOrderDirty = false;
- };
- Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
- get: function () {
- return this._usedShaderCategories;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
- get: function () {
- return this._strides;
- },
- enumerable: true,
- configurable: true
- });
- return GroupInstanceInfo;
- }());
- BABYLON.GroupInstanceInfo = GroupInstanceInfo;
- var TransparentSegment = (function () {
- function TransparentSegment() {
- this.groupInsanceInfo = null;
- this.startZ = 0;
- this.endZ = 0;
- this.startDataIndex = BABYLON.Prim2DBase._bigInt;
- this.endDataIndex = 0;
- this.partBuffers = null;
- }
- TransparentSegment.prototype.dispose = function (engine) {
- if (this.partBuffers) {
- this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
- this.partBuffers.splice(0);
- this.partBuffers = null;
- }
- };
- return TransparentSegment;
- }());
- BABYLON.TransparentSegment = TransparentSegment;
- var GroupInfoPartData = (function () {
- function GroupInfoPartData(stride) {
- this._partData = null;
- this._partBuffer = null;
- this._partBufferSize = 0;
- this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
- this._isDisposed = false;
- }
- GroupInfoPartData.prototype.dispose = function (engine) {
- if (this._isDisposed) {
- return false;
- }
- if (this._partBuffer) {
- engine._releaseBuffer(this._partBuffer);
- this._partBuffer = null;
- }
- this._partData = null;
- this._isDisposed = true;
- };
- return GroupInfoPartData;
- }());
- BABYLON.GroupInfoPartData = GroupInfoPartData;
- var TransparentGroupInfoPartData = (function (_super) {
- __extends(TransparentGroupInfoPartData, _super);
- function TransparentGroupInfoPartData(stride, zoff) {
- var _this = _super.call(this, stride) || this;
- _this._partData.compareValueOffset = zoff;
- _this._partData.sortingAscending = false;
- return _this;
- }
- return TransparentGroupInfoPartData;
- }(GroupInfoPartData));
- BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
- var ModelRenderCache = (function () {
- function ModelRenderCache(engine, modelKey) {
- this._engine = engine;
- this._modelKey = modelKey;
- this._nextKey = 1;
- this._refCounter = 1;
- this._partData = null;
- }
- ModelRenderCache.prototype.dispose = function () {
- if (--this._refCounter !== 0) {
- return false;
- }
- // Remove the Model Render Cache from the global dictionary
- var edata = this._engine.getExternalData("__BJSCANVAS2D__");
- if (edata) {
- edata.DisposeModelRenderCache(this);
- }
- return true;
- };
- Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
- get: function () {
- return this._refCounter <= 0;
- },
- enumerable: true,
- configurable: true
- });
- ModelRenderCache.prototype.addRef = function () {
- return ++this._refCounter;
- };
- Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
- get: function () {
- return this._modelKey;
- },
- enumerable: true,
- configurable: true
- });
- ModelRenderCache.prototype.updateModelRenderCache = function (prim) {
- return false;
- };
- /**
- * Render the model instances
- * @param instanceInfo
- * @param context
- * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
- */
- ModelRenderCache.prototype.render = function (instanceInfo, context) {
- return true;
- };
- ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
- for (var i = 0; i < this._partData.length; i++) {
- if (this._partData[i]._partId === partId) {
- return i;
- }
- }
- return null;
- };
- ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
- var i = this.getPartIndexFromId(partId);
- if (i === null) {
- return null;
- }
- var ci = this._partsClassInfo[i];
- var categories = this._partData[i]._partUsedCategories;
- var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
- return res;
- };
- ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
- var pd = this._partData[partIndex];
- var offset = (pd._partDataStride / 4) * elementCount;
- var pci = this._partsClassInfo[partIndex];
- var self = this;
- pci.fullContent.forEach(function (k, v) {
- if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
- switch (v.dataType) {
- case 3 /* float */:
- {
- var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
- effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
- break;
- }
- case 0 /* Vector2 */:
- {
- var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
- ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
- ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
- effect.setVector2(v.attributeName, ModelRenderCache.v2);
- break;
- }
- case 4 /* Color3 */:
- case 1 /* Vector3 */:
- {
- var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
- ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
- ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
- ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
- effect.setVector3(v.attributeName, ModelRenderCache.v3);
- break;
- }
- case 5 /* Color4 */:
- case 2 /* Vector4 */:
- {
- var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
- ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
- ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
- ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
- ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
- effect.setVector4(v.attributeName, ModelRenderCache.v4);
- break;
- }
- default:
- }
- }
- });
- };
- return ModelRenderCache;
- }());
- //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
- // let i = this.getPartIndexFromId(partId);
- // if (i === null) {
- // return null;
- // }
- // let pci = this._partsClassInfo[i];
- // pci.fullContent.forEach((k, v) => {
- // if (uniforms.indexOf(v.attributeName) !== -1) {
- // v.uniformLocation = effect.getUniform(v.attributeName);
- // }
- // });
- //}
- ModelRenderCache.v2 = BABYLON.Vector2.Zero();
- ModelRenderCache.v3 = BABYLON.Vector3.Zero();
- ModelRenderCache.v4 = BABYLON.Vector4.Zero();
- BABYLON.ModelRenderCache = ModelRenderCache;
- var ModelRenderCachePartData = (function () {
- function ModelRenderCachePartData() {
- }
- return ModelRenderCachePartData;
- }());
- BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.modelRenderCache.js.map
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var InstanceClassInfo = (function () {
- function InstanceClassInfo(base) {
- this._baseInfo = base;
- this._nextOffset = new BABYLON.StringDictionary();
- this._attributes = new Array();
- }
- InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
- var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
- propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
- //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
- this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
- if (push) {
- this._attributes.push(propInfo);
- }
- };
- InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
- var catInline = ";" + categories.join(";") + ";";
- var res = new Array();
- var curInfo = this;
- while (curInfo) {
- for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
- var attrib = _a[_i];
- // 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
- if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
- var index = effect.getAttributeLocationByName(attrib.attributeName);
- if (index === -1) {
- throw new Error("Attribute " + attrib.attributeName + " was not found in Effect: " + effect.name + ". It's certainly no longer used in the Effect's Shaders");
- }
- var iai = new BABYLON.InstancingAttributeInfo();
- iai.index = index;
- 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)
- iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
- iai.attributeName = attrib.attributeName;
- res.push(iai);
- }
- }
- curInfo = curInfo._baseInfo;
- }
- return res;
- };
- InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
- var res = new Array();
- var curInfo = this;
- while (curInfo) {
- for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
- var attrib = _a[_i];
- // 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
- if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
- res.push(attrib.attributeName);
- }
- }
- curInfo = curInfo._baseInfo;
- }
- return res;
- };
- InstanceClassInfo.prototype._getBaseOffset = function (categories) {
- var curOffset = 0;
- var curBase = this._baseInfo;
- while (curBase) {
- curOffset += curBase._nextOffset.getOrAdd(categories, 0);
- curBase = curBase._baseInfo;
- }
- return curOffset;
- };
- return InstanceClassInfo;
- }());
- BABYLON.InstanceClassInfo = InstanceClassInfo;
- var InstancePropInfo = (function () {
- function InstancePropInfo() {
- this.attributeName = null;
- this.category = null;
- this.size = null;
- this.instanceOffset = new BABYLON.StringDictionary();
- this.dataType = 0;
- this.curCategory = "";
- this.curCategoryOffset = 0;
- }
- InstancePropInfo.prototype.setSize = function (val) {
- if (val instanceof BABYLON.Vector2) {
- this.size = 8;
- this.dataType = 0 /* Vector2 */;
- return;
- }
- if (val instanceof BABYLON.Vector3) {
- this.size = 12;
- this.dataType = 1 /* Vector3 */;
- return;
- }
- if (val instanceof BABYLON.Vector4) {
- this.size = 16;
- this.dataType = 2 /* Vector4 */;
- return;
- }
- if (val instanceof BABYLON.Matrix2D) {
- throw new Error("Matrix2D type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
- }
- if (typeof (val) === "number") {
- this.size = 4;
- this.dataType = 3 /* float */;
- return;
- }
- if (val instanceof BABYLON.Color3) {
- this.size = 12;
- this.dataType = 4 /* Color3 */;
- return;
- }
- if (val instanceof BABYLON.Color4) {
- this.size = 16;
- this.dataType = 5 /* Color4 */;
- return;
- }
- if (val instanceof BABYLON.Size) {
- this.size = 8;
- this.dataType = 6 /* Size */;
- return;
- }
- return;
- };
- InstancePropInfo.prototype.writeData = function (array, offset, val) {
- switch (this.dataType) {
- case 0 /* Vector2 */:
- {
- var v = val;
- array[offset + 0] = v.x;
- array[offset + 1] = v.y;
- break;
- }
- case 1 /* Vector3 */:
- {
- var v = val;
- array[offset + 0] = v.x;
- array[offset + 1] = v.y;
- array[offset + 2] = v.z;
- break;
- }
- case 2 /* Vector4 */:
- {
- var v = val;
- array[offset + 0] = v.x;
- array[offset + 1] = v.y;
- array[offset + 2] = v.z;
- array[offset + 3] = v.w;
- break;
- }
- case 4 /* Color3 */:
- {
- var v = val;
- array[offset + 0] = v.r;
- array[offset + 1] = v.g;
- array[offset + 2] = v.b;
- break;
- }
- case 5 /* Color4 */:
- {
- var v = val;
- array[offset + 0] = v.r;
- array[offset + 1] = v.g;
- array[offset + 2] = v.b;
- array[offset + 3] = v.a;
- break;
- }
- case 3 /* float */:
- {
- var v = val;
- array[offset] = v;
- break;
- }
- case 6 /* Size */:
- {
- var s = val;
- array[offset + 0] = s.width;
- array[offset + 1] = s.height;
- break;
- }
- }
- };
- return InstancePropInfo;
- }());
- BABYLON.InstancePropInfo = InstancePropInfo;
- function instanceData(category, shaderAttributeName) {
- return function (target, propName, descriptor) {
- var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
- var node = dic.getLevelOf(target);
- var instanceDataName = propName;
- shaderAttributeName = shaderAttributeName || instanceDataName;
- var info = node.levelContent.get(instanceDataName);
- if (info) {
- throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
- }
- info = new InstancePropInfo();
- info.attributeName = shaderAttributeName;
- info.category = category || null;
- if (info.category) {
- info.delimitedCategory = ";" + info.category + ";";
- }
- node.levelContent.add(instanceDataName, info);
- descriptor.get = function () {
- return null;
- };
- descriptor.set = function (val) {
- // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
- // Quit if it's the case, otherwise we could overwrite data somewhere...
- if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
- return;
- }
- var catOffset;
- if (info.curCategory === InstanceClassInfo._CurCategories) {
- catOffset = info.curCategoryOffset;
- }
- else {
- if (!info.size) {
- info.setSize(val);
- node.classContent.mapProperty(info, true);
- }
- else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
- node.classContent.mapProperty(info, false);
- }
- catOffset = info.instanceOffset.get(InstanceClassInfo._CurCategories);
- info.curCategory = InstanceClassInfo._CurCategories;
- info.curCategoryOffset = catOffset;
- }
- var obj = this;
- if (obj.dataBuffer && obj.dataElements) {
- var offset = obj.dataElements[obj.curElement].offset + catOffset;
- info.writeData(obj.dataBuffer.buffer, offset, val);
- }
- };
- };
- }
- BABYLON.instanceData = instanceData;
- var InstanceDataBase = (function () {
- function InstanceDataBase(partId, dataElementCount) {
- this.id = partId;
- this.curElement = 0;
- this._dataElementCount = dataElementCount;
- this.renderMode = 0;
- this.arrayLengthChanged = false;
- }
- Object.defineProperty(InstanceDataBase.prototype, "zBias", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(InstanceDataBase.prototype, "transformX", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(InstanceDataBase.prototype, "transformY", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(InstanceDataBase.prototype, "renderingInfo", {
- // The vector3 is: rendering width, height and 1 if the primitive must be aligned to pixel or 0 otherwise
- get: function () {
- return null;
- },
- set: function (val) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(InstanceDataBase.prototype, "opacity", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- InstanceDataBase.prototype.getClassTreeInfo = function () {
- if (!this.typeInfo) {
- this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
- }
- return this.typeInfo;
- };
- InstanceDataBase.prototype.allocElements = function () {
- if (!this.dataBuffer || this.dataElements) {
- return;
- }
- var res = new Array(this.dataElementCount);
- for (var i = 0; i < this.dataElementCount; i++) {
- res[i] = this.dataBuffer.allocElement();
- }
- this.dataElements = res;
- };
- InstanceDataBase.prototype.freeElements = function () {
- if (!this.dataElements) {
- return;
- }
- for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
- var ei = _a[_i];
- this.dataBuffer.freeElement(ei);
- }
- this.dataElements = null;
- };
- Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
- get: function () {
- return this._dataElementCount;
- },
- set: function (value) {
- if (value === this._dataElementCount) {
- return;
- }
- this.arrayLengthChanged = true;
- this.freeElements();
- this._dataElementCount = value;
- this.allocElements();
- },
- enumerable: true,
- configurable: true
- });
- return InstanceDataBase;
- }());
- __decorate([
- instanceData()
- ], InstanceDataBase.prototype, "zBias", null);
- __decorate([
- instanceData()
- ], InstanceDataBase.prototype, "transformX", null);
- __decorate([
- instanceData()
- ], InstanceDataBase.prototype, "transformY", null);
- __decorate([
- instanceData()
- ], InstanceDataBase.prototype, "renderingInfo", null);
- __decorate([
- instanceData()
- ], InstanceDataBase.prototype, "opacity", null);
- BABYLON.InstanceDataBase = InstanceDataBase;
- var RenderablePrim2D = RenderablePrim2D_1 = (function (_super) {
- __extends(RenderablePrim2D, _super);
- function RenderablePrim2D(settings) {
- var _this = _super.call(this, settings) || this;
- _this._transparentPrimitiveInfo = null;
- return _this;
- }
- Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
- get: function () {
- return this._useTextureAlpha() || this._isPrimAlphaTest();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
- get: function () {
- return (this.actualOpacity < 1) || this._shouldUseAlphaFromTexture() || this._isPrimTransparent();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
- get: function () {
- return this._renderMode;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Dispose the primitive and its resources, remove it from its parent
- */
- RenderablePrim2D.prototype.dispose = function () {
- if (!_super.prototype.dispose.call(this)) {
- return false;
- }
- if (this.renderGroup) {
- this.renderGroup._setCacheGroupDirty();
- }
- if (this._transparentPrimitiveInfo) {
- this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
- this._transparentPrimitiveInfo = null;
- }
- if (this._instanceDataParts) {
- this._cleanupInstanceDataParts();
- }
- if (this._modelRenderCache) {
- this._modelRenderCache.dispose();
- this._modelRenderCache = null;
- }
- if (this._instanceDataParts) {
- this._instanceDataParts.forEach(function (p) {
- p.freeElements();
- });
- this._instanceDataParts = null;
- }
- return true;
- };
- RenderablePrim2D.prototype._cleanupInstanceDataParts = function () {
- var gii = null;
- for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
- var part = _a[_i];
- part.freeElements();
- gii = part.groupInstanceInfo;
- part.groupInstanceInfo = null;
- }
- if (gii) {
- if (gii.hasOpaqueData) {
- gii.opaqueDirty = true;
- }
- if (gii.hasAlphaTestData) {
- gii.alphaTestDirty = true;
- }
- if (gii.hasTransparentData) {
- gii.transparentDirty = true;
- }
- gii.dispose();
- if (this._modelRenderCache) {
- this._modelRenderCache.dispose();
- this._modelRenderCache = null;
- }
- }
- this._instanceDataParts = null;
- };
- RenderablePrim2D.prototype._prepareRenderPre = function (context) {
- _super.prototype._prepareRenderPre.call(this, context);
- // If the model changed and we have already an instance, we must remove this instance from the obsolete model
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._instanceDataParts) {
- this._cleanupInstanceDataParts();
- }
- // Need to create the model?
- var setupModelRenderCache = false;
- if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
- setupModelRenderCache = this._createModelRenderCache();
- }
- var gii = null;
- var newInstance = false;
- // Need to create the instance data parts?
- if (!this._instanceDataParts) {
- // Yes, flag it for later, more processing will have to be done
- newInstance = true;
- gii = this._createModelDataParts();
- }
- // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
- if (setupModelRenderCache) {
- this.setupModelRenderCache(this._modelRenderCache);
- }
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelUpdate)) {
- if (this._modelRenderCache.updateModelRenderCache(this)) {
- this._clearFlags(BABYLON.SmartPropertyPrim.flagModelUpdate);
- }
- }
- // 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.
- // 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.
- if (this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagNeedRefresh) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep) || this._mustUpdateInstance()) {
- this._updateInstanceDataParts(gii);
- }
- };
- RenderablePrim2D.prototype._createModelRenderCache = function () {
- var _this = this;
- var setupModelRenderCache = false;
- if (this._modelRenderCache) {
- this._modelRenderCache.dispose();
- }
- this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
- var mrc = _this.createModelRenderCache(key);
- setupModelRenderCache = true;
- return mrc;
- });
- this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
- // if this is still false it means the MRC already exists, so we add a reference to it
- if (!setupModelRenderCache) {
- this._modelRenderCache.addRef();
- }
- return setupModelRenderCache;
- };
- RenderablePrim2D.prototype._createModelDataParts = function () {
- var _this = this;
- // Create the instance data parts of the primitive and store them
- var parts = this.createInstanceDataParts();
- this._instanceDataParts = parts;
- // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
- if (!this._modelRenderCache._partData) {
- this._setupModelRenderCache(parts);
- }
- // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
- // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
- // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
- var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
- var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
- for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
- var part = _this._instanceDataParts[j];
- res.partIndexFromId.add(part.id.toString(), j);
- res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
- res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
- }
- return res;
- });
- // Get the GroupInfoDataPart corresponding to the render category of the part
- var rm = 0;
- var gipd = null;
- if (this.isTransparent) {
- gipd = gii.transparentData;
- rm = BABYLON.Render2DContext.RenderModeTransparent;
- }
- else if (this.isAlphaTest) {
- gipd = gii.alphaTestData;
- rm = BABYLON.Render2DContext.RenderModeAlphaTest;
- }
- else {
- gipd = gii.opaqueData;
- rm = BABYLON.Render2DContext.RenderModeOpaque;
- }
- // For each instance data part of the primitive, allocate the instanced element it needs for render
- for (var i = 0; i < parts.length; i++) {
- var part = parts[i];
- part.dataBuffer = gipd[i]._partData;
- part.allocElements();
- part.renderMode = rm;
- part.groupInstanceInfo = gii;
- }
- // Increment the primitive count as one more primitive is using this GroupInstanceInfo
- gii.incPrimCount();
- return gii;
- };
- RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
- var ctiArray = new Array();
- this._modelRenderCache._partData = new Array();
- for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
- var dataPart = parts_1[_i];
- var pd = new BABYLON.ModelRenderCachePartData();
- this._modelRenderCache._partData.push(pd);
- var cat = this.getUsedShaderCategories(dataPart);
- var cti = dataPart.getClassTreeInfo();
- // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
- var curVisible = this.isVisible;
- this.isVisible = true;
- // 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.
- //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
- var joinCat = ";" + cat.join(";") + ";";
- pd._partJoinedUsedCategories = joinCat;
- InstanceClassInfo._CurCategories = joinCat;
- var obj = this.beforeRefreshForLayoutConstruction(dataPart);
- if (!this.refreshInstanceDataPart(dataPart)) {
- console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
- }
- this.afterRefreshForLayoutConstruction(dataPart, obj);
- this.isVisible = curVisible;
- var size = 0;
- cti.fullContent.forEach(function (k, v) {
- if (!v.category || cat.indexOf(v.category) !== -1) {
- if (v.attributeName === "zBias") {
- pd._zBiasOffset = v.instanceOffset.get(joinCat);
- }
- if (!v.size) {
- console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
- }
- else {
- size += v.size;
- }
- }
- });
- pd._partDataStride = size;
- pd._partUsedCategories = cat;
- pd._partId = dataPart.id;
- ctiArray.push(cti);
- }
- this._modelRenderCache._partsClassInfo = ctiArray;
- };
- RenderablePrim2D.prototype.onZOrderChanged = function () {
- if (this.isTransparent && this._transparentPrimitiveInfo) {
- this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
- var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
- // Flag the transparentData dirty has will have to sort it again
- gii.transparentOrderDirty = true;
- }
- };
- RenderablePrim2D.prototype._mustUpdateInstance = function () {
- return false;
- };
- RenderablePrim2D.prototype._useTextureAlpha = function () {
- return false;
- };
- RenderablePrim2D.prototype._shouldUseAlphaFromTexture = function () {
- return false;
- };
- RenderablePrim2D.prototype._isPrimAlphaTest = function () {
- return false;
- };
- RenderablePrim2D.prototype._isPrimTransparent = function () {
- return false;
- };
- RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
- // Fetch the GroupInstanceInfo if we don't already have it
- var rd = this.renderGroup._renderableData;
- if (!gii) {
- gii = rd._renderGroupInstancesInfo.get(this.modelKey);
- }
- if (gii.isDisposed) {
- return;
- }
- var isTransparent = this.isTransparent;
- var isAlphaTest = this.isAlphaTest;
- var wereTransparent = false;
- // Check a render mode change
- var rmChanged = false;
- if (this._instanceDataParts.length > 0) {
- var firstPart = this._instanceDataParts[0];
- var partRM = firstPart.renderMode;
- var curRM = this.renderMode;
- if (partRM !== curRM) {
- wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
- rmChanged = true;
- var gipd = void 0;
- switch (curRM) {
- case BABYLON.Render2DContext.RenderModeTransparent:
- gipd = gii.transparentData;
- break;
- case BABYLON.Render2DContext.RenderModeAlphaTest:
- gipd = gii.alphaTestData;
- break;
- default:
- gipd = gii.opaqueData;
- }
- for (var i = 0; i < this._instanceDataParts.length; i++) {
- var part = this._instanceDataParts[i];
- part.freeElements();
- part.dataBuffer = gipd[i]._partData;
- part.renderMode = curRM;
- }
- }
- }
- // Handle changes related to ZOffset
- var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
- if (isTransparent || wereTransparent) {
- // Handle visibility change, which is also triggered when the primitive just got created
- if (visChanged || rmChanged) {
- if (this.isVisible && !wereTransparent) {
- if (!this._transparentPrimitiveInfo) {
- // Add the primitive to the list of transparent ones in the group that render is
- this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
- }
- }
- else {
- if (this._transparentPrimitiveInfo) {
- rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
- this._transparentPrimitiveInfo = null;
- }
- }
- gii.transparentOrderDirty = true;
- }
- }
- var rebuildTrans = false;
- // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
- for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
- var part = _a[_i];
- var justAllocated = false;
- // Check if we need to allocate data elements (hidden prim which becomes visible again)
- if (!part.dataElements && (visChanged || rmChanged || this.isVisible)) {
- part.allocElements();
- justAllocated = true;
- }
- InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
- // Will return false if the instance should not be rendered (not visible or other any reasons)
- part.arrayLengthChanged = false;
- if (!this.refreshInstanceDataPart(part)) {
- // Free the data element
- if (part.dataElements) {
- part.freeElements();
- }
- // The refresh couldn't succeed, push the primitive to be dirty again for the next render
- if (this.isVisible) {
- rd._primNewDirtyList.push(this);
- }
- }
- rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
- }
- this._instanceDirtyFlags = 0;
- // Make the appropriate data dirty
- if (isTransparent) {
- gii.transparentDirty = true;
- if (rebuildTrans) {
- rd._transparentListChanged = true;
- }
- }
- else if (isAlphaTest) {
- gii.alphaTestDirty = true;
- }
- else {
- gii.opaqueDirty = true;
- }
- this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
- };
- RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
- var minOff = BABYLON.Prim2DBase._bigInt;
- var maxOff = 0;
- for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
- var part = _a[_i];
- if (part && part.dataElements) {
- part.dataBuffer.pack();
- for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
- var el = _c[_b];
- minOff = Math.min(minOff, el.offset);
- maxOff = Math.max(maxOff, el.offset);
- }
- ts.startDataIndex = Math.min(ts.startDataIndex, minOff / part.dataBuffer.stride);
- ts.endDataIndex = Math.max(ts.endDataIndex, (maxOff / part.dataBuffer.stride) + 1); // +1 for exclusive
- }
- }
- };
- // This internal method is mainly used for transparency processing
- RenderablePrim2D.prototype._getNextPrimZOrder = function () {
- var length = this._instanceDataParts.length;
- for (var i = 0; i < length; i++) {
- var part = this._instanceDataParts[i];
- if (part) {
- var stride = part.dataBuffer.stride;
- var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
- // check if it's the last in the DFA
- if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
- return null;
- }
- // Return the Z of the next primitive that lies in the DFA
- return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
- }
- }
- return null;
- };
- // This internal method is mainly used for transparency processing
- RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
- var length = this._instanceDataParts.length;
- for (var i = 0; i < length; i++) {
- var part = this._instanceDataParts[i];
- if (part) {
- var stride = part.dataBuffer.stride;
- var firstElementOffset = part.dataElements[0].offset;
- // check if it's the first in the DFA
- if (firstElementOffset === 0) {
- return null;
- }
- // Return the Z of the previous primitive that lies in the DFA
- return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
- }
- }
- return null;
- };
- /**
- * Get the info for a given effect based on the dataPart metadata
- * @param dataPartId partId in part list to get the info
- * @param vertexBufferAttributes vertex buffer attributes to manually add
- * @param uniforms uniforms to manually add
- * @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
- */
- RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, uniforms, useInstanced) {
- if (uniforms === void 0) { uniforms = null; }
- if (useInstanced === void 0) { useInstanced = null; }
- var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
- if (!dataPart) {
- return null;
- }
- var instancedArray = this.owner.supportInstancedArray;
- if (useInstanced != null) {
- // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
- if (useInstanced && instancedArray === false) {
- return null;
- }
- // Use the caller's setting
- instancedArray = useInstanced;
- }
- var cti = dataPart.getClassTreeInfo();
- var categories = this.getUsedShaderCategories(dataPart);
- var att = cti.classContent.getShaderAttributes(categories);
- var defines = "";
- categories.forEach(function (c) { defines += "#define " + c + "\n"; });
- if (instancedArray) {
- defines += "#define Instanced\n";
- }
- return {
- attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes,
- uniforms: instancedArray ? (uniforms != null ? uniforms : []) : ((uniforms != null) ? att.concat(uniforms) : (att != null ? att : [])),
- defines: defines
- };
- };
- Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
- get: function () {
- return this._modelRenderCache;
- },
- enumerable: true,
- configurable: true
- });
- RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
- return null;
- };
- RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
- };
- RenderablePrim2D.prototype.createInstanceDataParts = function () {
- return null;
- };
- RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
- return [];
- };
- RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
- };
- RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
- };
- RenderablePrim2D.prototype.applyActualScaleOnTransform = function () {
- return true;
- };
- RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
- if (!this.isVisible) {
- return false;
- }
- part.isVisible = this.isVisible;
- // 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)
- if (part.dataElementCount === 1) {
- part.curElement = 0;
- this.updateInstanceDataPart(part);
- }
- return true;
- };
- /**
- * Update the instanceDataBase level properties of a part
- * @param part the part to update
- * @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).
- */
- RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
- if (positionOffset === void 0) { positionOffset = null; }
- var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform); // Compute the transformation into the renderGroup's space
- var scl = RenderablePrim2D_1._s;
- var trn = RenderablePrim2D_1._t;
- var rot = t.decompose(scl, trn);
- var pas = this.actualScale;
- //let cachedGroup = (this.getExternalData<Group2D>("__cachedGroup__") !== null);
- var canvasScale = this.owner._canvasLevelScale;
- scl.x = pas.x * canvasScale.x * this._postScale.x;
- scl.y = pas.y * canvasScale.y * this._postScale.y;
- trn.multiplyInPlace(canvasScale);
- t = BABYLON.Matrix2D.Compose(this.applyActualScaleOnTransform() ? scl : RenderablePrim2D_1._iV2, rot, trn);
- //console.log(`Update Instance Data Part: ${this.id}`);
- var size = this.renderGroup.viewportSize;
- var zBias = this.actualZOffset;
- var offX = 0;
- var offY = 0;
- // If there's an offset, apply the global transformation matrix on it to get a global offset
- if (positionOffset) {
- offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[2];
- offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[3];
- }
- // 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
- // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
- // So for X:
- // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
- // - 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].
- // At last we don't forget to apply the actualScale of the Render Group to tx[0] and ty[1] to propagate scaling correctly
- var w = size.width;
- var h = size.height;
- var invZBias = 1 / zBias;
- var tx = new BABYLON.Vector4(t.m[0] * 2 / w, t.m[2] * 2 / w, 0, ((t.m[4] + offX) * 2 / w) - 1);
- var ty = new BABYLON.Vector4(t.m[1] * 2 / h, t.m[3] * 2 / h, 0, ((t.m[5] + offY) * 2 / h) - 1);
- part.renderingInfo = new BABYLON.Vector3(w, h, this.alignToPixel ? 1 : 0);
- part.transformX = tx;
- part.transformY = ty;
- part.opacity = this.actualOpacity;
- // 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)
- part.zBias = new BABYLON.Vector2(zBias, invZBias);
- };
- RenderablePrim2D.prototype._updateRenderMode = function () {
- if (this.isTransparent) {
- this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
- }
- else if (this.isAlphaTest) {
- this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
- }
- else {
- this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
- }
- };
- return RenderablePrim2D;
- }(BABYLON.Prim2DBase));
- RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
- RenderablePrim2D._toz = BABYLON.Size.Zero();
- RenderablePrim2D._uV = new BABYLON.Vector2(1, 1);
- RenderablePrim2D._s = BABYLON.Vector2.Zero();
- RenderablePrim2D._r = BABYLON.Quaternion.Identity();
- RenderablePrim2D._t = BABYLON.Vector2.Zero();
- RenderablePrim2D._iV2 = new BABYLON.Vector2(1, 1); // Must stay identity vector3
- __decorate([
- BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D_1.isAlphaTestProperty = pi; })
- /**
- * Get/set if the Primitive is from the AlphaTest rendering category.
- * The AlphaTest category is the rendering pass with alpha blend, depth compare and write activated.
- * Primitives that render with an alpha mask should be from this category.
- * The setter should be used only by implementers of new primitive type.
- */
- ], RenderablePrim2D.prototype, "isAlphaTest", null);
- __decorate([
- BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D_1.isTransparentProperty = pi; })
- /**
- * Get/set if the Primitive is from the Transparent rendering category.
- * The setter should be used only by implementers of new primitive type.
- */
- ], RenderablePrim2D.prototype, "isTransparent", null);
- RenderablePrim2D = RenderablePrim2D_1 = __decorate([
- BABYLON.className("RenderablePrim2D", "BABYLON")
- /**
- * The abstract class for primitive that render into the Canvas2D
- */
- ], RenderablePrim2D);
- BABYLON.RenderablePrim2D = RenderablePrim2D;
- var RenderablePrim2D_1;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.renderablePrim2d.js.map
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var Shape2D = Shape2D_1 = (function (_super) {
- __extends(Shape2D, _super);
- function Shape2D(settings) {
- var _this = _super.call(this, settings) || this;
- if (!settings) {
- settings = {};
- }
- var borderBrush = null;
- if (settings.border) {
- if (typeof (settings.border) === "string") {
- borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
- }
- else {
- borderBrush = settings.border;
- }
- }
- var fillBrush = null;
- if (settings.fill) {
- if (typeof (settings.fill) === "string") {
- fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
- }
- else {
- fillBrush = settings.fill;
- }
- }
- _this._isTransparent = false;
- _this._oldTransparent = false;
- _this.border = borderBrush;
- _this.fill = fillBrush;
- _this._updateTransparencyStatus();
- _this.borderThickness = settings.borderThickness;
- return _this;
- }
- Object.defineProperty(Shape2D.prototype, "border", {
- get: function () {
- return this._border;
- },
- set: function (value) {
- this._border = value;
- this._updateTransparencyStatus();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Shape2D.prototype, "fill", {
- /**
- * Get/set the brush to render the Fill part of the Primitive
- */
- get: function () {
- return this._fill;
- },
- set: function (value) {
- this._fill = value;
- this._updateTransparencyStatus();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Shape2D.prototype, "borderThickness", {
- get: function () {
- return this._borderThickness;
- },
- set: function (value) {
- this._borderThickness = value;
- },
- enumerable: true,
- configurable: true
- });
- Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
- var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
- // Fill Part
- if (dataPart.id === Shape2D_1.SHAPE2D_FILLPARTID) {
- var fill = this.fill;
- if (fill instanceof BABYLON.SolidColorBrush2D) {
- cat.push(Shape2D_1.SHAPE2D_CATEGORY_FILLSOLID);
- }
- if (fill instanceof BABYLON.GradientColorBrush2D) {
- cat.push(Shape2D_1.SHAPE2D_CATEGORY_FILLGRADIENT);
- }
- }
- // Border Part
- if (dataPart.id === Shape2D_1.SHAPE2D_BORDERPARTID) {
- cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDER);
- var border = this.border;
- if (border instanceof BABYLON.SolidColorBrush2D) {
- cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDERSOLID);
- }
- if (border instanceof BABYLON.GradientColorBrush2D) {
- cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDERGRADIENT);
- }
- }
- return cat;
- };
- //protected applyActualScaleOnTransform(): boolean {
- // return false;
- //}
- Shape2D.prototype.refreshInstanceDataPart = function (part) {
- if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
- return false;
- }
- // Fill Part
- if (part.id === Shape2D_1.SHAPE2D_FILLPARTID) {
- var d = part;
- if (this.fill) {
- var fill = this.fill;
- if (fill instanceof BABYLON.SolidColorBrush2D) {
- d.fillSolidColor = fill.color;
- }
- else if (fill instanceof BABYLON.GradientColorBrush2D) {
- d.fillGradientColor1 = fill.color1;
- d.fillGradientColor2 = fill.color2;
- var t = BABYLON.Matrix2D.Compose(new BABYLON.Vector2(fill.scale, fill.scale), fill.rotation, new BABYLON.Vector2(fill.translation.x, fill.translation.y));
- var ty = new BABYLON.Vector4(t.m[1], t.m[3], 0, t.m[5]);
- d.fillGradientTY = ty;
- }
- }
- }
- else if (part.id === Shape2D_1.SHAPE2D_BORDERPARTID) {
- var d = part;
- if (this.border) {
- d.borderThickness = this.borderThickness;
- var border = this.border;
- if (border instanceof BABYLON.SolidColorBrush2D) {
- d.borderSolidColor = border.color;
- }
- else if (border instanceof BABYLON.GradientColorBrush2D) {
- d.borderGradientColor1 = border.color1;
- d.borderGradientColor2 = border.color2;
- var t = BABYLON.Matrix2D.Compose(new BABYLON.Vector2(border.scale, border.scale), border.rotation, new BABYLON.Vector2(border.translation.x, border.translation.y));
- var ty = new BABYLON.Vector4(t.m[1], t.m[3], 0, t.m[5]);
- d.borderGradientTY = ty;
- }
- }
- }
- return true;
- };
- Shape2D.prototype._updateTransparencyStatus = function () {
- this._isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
- if (this._isTransparent !== this._oldTransparent) {
- this._oldTransparent = this._isTransparent;
- this._updateRenderMode();
- }
- };
- Shape2D.prototype._mustUpdateInstance = function () {
- var res = this._oldTransparent !== this._isTransparent;
- if (res) {
- this._updateRenderMode();
- this._oldTransparent = this._isTransparent;
- }
- return res;
- };
- Shape2D.prototype._isPrimTransparent = function () {
- return this._isTransparent;
- };
- return Shape2D;
- }(BABYLON.RenderablePrim2D));
- Shape2D.SHAPE2D_BORDERPARTID = 1;
- Shape2D.SHAPE2D_FILLPARTID = 2;
- Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
- Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
- Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
- Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
- Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
- Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
- __decorate([
- BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D_1.borderProperty = pi; }, true)
- /**
- * Get/set the brush to render the Border part of the Primitive
- */
- ], Shape2D.prototype, "border", null);
- __decorate([
- BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D_1.fillProperty = pi; }, true)
- ], Shape2D.prototype, "fill", null);
- __decorate([
- BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D_1.borderThicknessProperty = pi; })
- /**
- * Get/set the thickness of the border part.
- */
- ], Shape2D.prototype, "borderThickness", null);
- Shape2D = Shape2D_1 = __decorate([
- BABYLON.className("Shape2D", "BABYLON")
- /**
- * The abstract class for parametric shape based Primitives types.
- * Shape2D based primitives are composed of two parts: fill and border, both are optional but at least one must be specified.
- * The fill part is the primitive 'body', the border is a border around this body. The border has a thickness that can be changed.
- */
- ], Shape2D);
- BABYLON.Shape2D = Shape2D;
- var Shape2DInstanceData = (function (_super) {
- __extends(Shape2DInstanceData, _super);
- function Shape2DInstanceData() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
- // FILL ATTRIBUTES
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
- // BORDER ATTRIBUTES
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- return Shape2DInstanceData;
- }(BABYLON.InstanceDataBase));
- __decorate([
- BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
- ], Shape2DInstanceData.prototype, "fillSolidColor", null);
- __decorate([
- BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
- ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
- __decorate([
- BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
- ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
- __decorate([
- BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
- ], Shape2DInstanceData.prototype, "fillGradientTY", null);
- __decorate([
- BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
- ], Shape2DInstanceData.prototype, "borderThickness", null);
- __decorate([
- BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
- ], Shape2DInstanceData.prototype, "borderSolidColor", null);
- __decorate([
- BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
- ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
- __decorate([
- BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
- ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
- __decorate([
- BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
- ], Shape2DInstanceData.prototype, "borderGradientTY", null);
- BABYLON.Shape2DInstanceData = Shape2DInstanceData;
- var Shape2D_1;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.shape2d.js.map
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var Group2D = Group2D_1 = (function (_super) {
- __extends(Group2D, _super);
- /**
- * Create an Logical or Renderable Group.
- * @param settings a combination of settings, possible ones are
- * - 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)
- * - children: an array of direct children
- * - id a text identifier, for information purpose
- * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
- * - rotation: the initial rotation (in radian) of the primitive. default is 0
- * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
- * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
- * - trackNode: if you want the ScreenSpaceCanvas to track the position of a given Scene Node, use this setting to specify the Node to track
- * - trackNodeOffset: if you use trackNode you may want to specify a 3D Offset to apply to shift the Canvas
- * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
- * - zOrder: override the zOrder with the specified value
- * - origin: define the normalized origin point location, default [0.5;0.5]
- * - 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.
- * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
- * - 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).
- * - isVisible: true if the group must be visible, false for hidden. Default is true.
- * - 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.
- * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersect, 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.
- * - 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!
- * - 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.
- * - 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).
- * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
- * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
- * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
- * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
- * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
- * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
- */
- function Group2D(settings) {
- var _this = this;
- if (settings == null) {
- settings = {};
- }
- if (settings.origin == null) {
- settings.origin = new BABYLON.Vector2(0, 0);
- }
- _this = _super.call(this, settings) || this;
- var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
- if (!(_this instanceof BABYLON.WorldSpaceCanvas2D)) {
- _this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
- _this._trackedNodeOffset = (settings.trackNodeOffset == null) ? null : settings.trackNodeOffset;
- if (_this._trackedNode && _this.owner) {
- _this.owner._registerTrackedNode(_this);
- }
- }
- _this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D_1.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
- var rd = _this._renderableData;
- if (rd) {
- rd._noResizeOnScale = (_this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
- }
- _this.size = size;
- _this._viewportPosition = BABYLON.Vector2.Zero();
- _this._viewportSize = BABYLON.Size.Zero();
- return _this;
- }
- Group2D._createCachedCanvasGroup = function (owner) {
- 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 });
- return g;
- };
- Group2D.prototype.applyCachedTexture = function (vertexData, material) {
- this._bindCacheTarget();
- if (vertexData) {
- var uv = vertexData.uvs;
- var nodeuv = this._renderableData._cacheNodeUVs;
- for (var i = 0; i < 4; i++) {
- uv[i * 2 + 0] = nodeuv[i].x;
- uv[i * 2 + 1] = nodeuv[i].y;
- }
- }
- if (material) {
- material.diffuseTexture = this._renderableData._cacheTexture;
- material.emissiveColor = new BABYLON.Color3(1, 1, 1);
- }
- this._renderableData._cacheTexture.hasAlpha = true;
- this._unbindCacheTarget();
- };
- Object.defineProperty(Group2D.prototype, "cachedRect", {
- /**
- * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
- * 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.
- */
- get: function () {
- if (!this._renderableData) {
- return null;
- }
- return this._renderableData._cacheNode;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Group2D.prototype, "cachedUVs", {
- /**
- * The UVs into the MapTexture that map the cached group
- */
- get: function () {
- if (!this._renderableData) {
- return null;
- }
- return this._renderableData._cacheNodeUVs;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
- get: function () {
- if (!this._renderableData) {
- return null;
- }
- if (!this._renderableData._cacheNodeUVsChangedObservable) {
- this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
- }
- return this._renderableData._cacheNodeUVsChangedObservable;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Group2D.prototype, "cacheTexture", {
- /**
- * Access the texture that maintains a cached version of the Group2D.
- * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
- */
- get: function () {
- if (!this._renderableData) {
- return null;
- }
- return this._renderableData._cacheTexture;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Call this method to remove this Group and its children from the Canvas
- */
- Group2D.prototype.dispose = function () {
- if (!_super.prototype.dispose.call(this)) {
- return false;
- }
- if (this._trackedNode != null) {
- this.owner._unregisterTrackedNode(this);
- this._trackedNode = null;
- }
- if (this._renderableData) {
- this._renderableData.dispose(this.owner);
- this._renderableData = null;
- }
- return true;
- };
- Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
- /**
- * @returns Returns true if the Group render content, false if it's a logical group only
- */
- get: function () {
- return this._isRenderableGroup;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Group2D.prototype, "isCachedGroup", {
- /**
- * @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
- */
- get: function () {
- return this._isCachedGroup;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Group2D.prototype, "size", {
- get: function () {
- return this.internalGetSize();
- },
- /**
- * Get/Set the size of the group. If null the size of the group will be determine from its content.
- * 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.
- */
- set: function (val) {
- this.internalSetSize(val);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Group2D.prototype, "viewportSize", {
- get: function () {
- return this._viewportSize;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Group2D.prototype, "cacheBehavior", {
- /**
- * 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.
- * GROUPCACHEBEHAVIOR_NORESIZEONSCALE can also be set if you set it at creation time.
- * 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.
- */
- get: function () {
- return this._cacheBehavior;
- },
- enumerable: true,
- configurable: true
- });
- Group2D.prototype._addPrimToDirtyList = function (prim) {
- this._renderableData._primDirtyList.push(prim);
- };
- Group2D.prototype._renderCachedCanvas = function () {
- this.owner._addGroupRenderCount(1);
- this.updateCachedStates(true);
- var context = new BABYLON.PrepareRender2DContext();
- this._prepareGroupRender(context);
- this._groupRender();
- };
- Object.defineProperty(Group2D.prototype, "trackedNode", {
- /**
- * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
- */
- get: function () {
- return this._trackedNode;
- },
- set: function (val) {
- if (val != null) {
- if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
- this.owner._registerTrackedNode(this);
- }
- this._trackedNode = val;
- }
- else {
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
- this.owner._unregisterTrackedNode(this);
- }
- this._trackedNode = null;
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Group2D.prototype, "trackedNodeOffset", {
- /**
- * Get/set the offset of the tracked node in the tracked node's local space.
- */
- get: function () {
- return this._trackedNodeOffset;
- },
- set: function (val) {
- if (!this._trackedNodeOffset) {
- this._trackedNodeOffset = val.clone();
- }
- else {
- this._trackedNodeOffset.copyFrom(val);
- }
- },
- enumerable: true,
- configurable: true
- });
- Group2D.prototype.levelIntersect = function (intersectInfo) {
- // 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
- return true;
- };
- Group2D.prototype.updateLevelBoundingInfo = function () {
- var size;
- // If the size is set by the user, the boundingInfo is computed from this value
- if (this.size) {
- size = this.size;
- }
- else {
- size = new BABYLON.Size(0, 0);
- }
- BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
- return true;
- };
- // Method called only on renderable groups to prepare the rendering
- Group2D.prototype._prepareGroupRender = function (context) {
- var sortedDirtyList = null;
- // Update the Global Transformation and visibility status of the changed primitives
- var rd = this._renderableData;
- var curPrimDirtyList = rd._primDirtyList;
- if ((curPrimDirtyList.length > 0) || context.forceRefreshPrimitive) {
- // From now on we use the 'curPrimDirtyList' variable to process the primitives that was marked as dirty
- // But we also allocate a new array in the object's member to get the prim that will be dirty again during the process
- // and that would need another process next time.
- rd._primDirtyList = new Array();
- // Sort the primitives to process them from the highest in the tree to the lowest
- sortedDirtyList = curPrimDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
- this.updateCachedStatesOf(sortedDirtyList, true);
- }
- var s = this.actualSize;
- var a = this.actualScale;
- var ss = this.owner._canvasLevelScale;
- var hwsl = 1 / this.owner.engine.getHardwareScalingLevel();
- //let sw = Math.ceil(s.width * a.x * ss.x/* * hwsl*/);
- //let sh = Math.ceil(s.height * a.y *ss.y/* * hwsl*/);
- var sw = s.width * a.x * ss.x;
- var sh = s.height * a.y * ss.y;
- // 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.
- // So we set the width/height to the rendering's one because that's what we want for the viewport!
- if ((this instanceof BABYLON.Canvas2D || this.id === "__cachedCanvasGroup__") && this.owner.designSize != null) {
- sw = this.owner.engine.getRenderWidth();
- sh = this.owner.engine.getRenderHeight();
- }
- // Setup the size of the rendering viewport
- // 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
- if (!this._isCachedGroup) {
- // Compute the WebGL viewport's location/size
- var t = this._globalTransform.getTranslation();
- var rs = this.owner._renderingSize.multiplyByFloats(hwsl, hwsl);
- sh = Math.min(sh, rs.height - t.y);
- sw = Math.min(sw, rs.width - t.x);
- var x = t.x;
- var y = t.y;
- // 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
- this._viewportPosition.x = x;
- this._viewportPosition.y = y;
- }
- // 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.
- if (this._viewportSize.width !== sw || this._viewportSize.height !== sh) {
- context.forceRefreshPrimitive = true;
- this._viewportSize.width = sw;
- this._viewportSize.height = sh;
- }
- if ((curPrimDirtyList.length > 0) || context.forceRefreshPrimitive) {
- // If the group is cached, set the dirty flag to true because of the incoming changes
- this._cacheGroupDirty = this._isCachedGroup;
- rd._primNewDirtyList.splice(0);
- // If it's a force refresh, prepare all the children
- if (context.forceRefreshPrimitive) {
- for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
- var p = _a[_i];
- if (!p.isDisposed) {
- p._prepareRender(context);
- }
- }
- }
- else {
- // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
- // the hierarchyDepth in order to prepare primitives from top to bottom
- if (!sortedDirtyList) {
- sortedDirtyList = curPrimDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
- }
- sortedDirtyList.forEach(function (p) {
- // 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.
- // 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.
- if (!p.isDisposed && p._needPrepare()) {
- p._prepareRender(context);
- }
- });
- }
- // Everything is updated, clear the dirty list
- curPrimDirtyList.forEach(function (p) {
- if (rd._primNewDirtyList.indexOf(p) === -1) {
- p._resetPropertiesDirty();
- }
- else {
- p._setFlags(BABYLON.SmartPropertyPrim.flagNeedRefresh);
- }
- });
- rd._primDirtyList = curPrimDirtyList.concat(rd._primNewDirtyList);
- }
- // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
- rd._childrenRenderableGroups.forEach(function (g) {
- g._prepareGroupRender(context);
- });
- };
- Group2D.prototype._groupRender = function () {
- var _this = this;
- var engine = this.owner.engine;
- var failedCount = 0;
- // First recurse to children render group to render them (in their cache or on screen)
- for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
- var childGroup = _a[_i];
- childGroup._groupRender();
- }
- // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
- if (!this.isCachedGroup || this._cacheGroupDirty) {
- this.owner._addGroupRenderCount(1);
- if (this.isCachedGroup) {
- this._bindCacheTarget();
- }
- else {
- var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
- }
- var curAlphaTest = engine.getAlphaTesting() === true;
- var curDepthWrite = engine.getDepthWrite() === true;
- // ===================================================================
- // First pass, update the InstancedArray and render Opaque primitives
- // Disable Alpha Testing, Enable Depth Write
- engine.setAlphaTesting(false);
- engine.setDepthWrite(true);
- // For each different model of primitive to render
- var context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
- this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
- // Prepare the context object, update the WebGL Instanced Array buffer if needed
- var renderCount = _this._prepareContext(engine, context_1, v);
- // If null is returned, there's no opaque data to render
- if (renderCount === null) {
- return;
- }
- // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
- if (!_this.owner.supportInstancedArray || renderCount > 0) {
- // render all the instances of this model, if the render method returns true then our instances are no longer dirty
- var renderFailed = !v.modelRenderCache.render(v, context_1);
- // Update dirty flag/related
- v.opaqueDirty = renderFailed;
- failedCount += renderFailed ? 1 : 0;
- }
- });
- // =======================================================================
- // Second pass, update the InstancedArray and render AlphaTest primitives
- // Enable Alpha Testing, Enable Depth Write
- engine.setAlphaTesting(true);
- engine.setDepthWrite(true);
- // For each different model of primitive to render
- context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
- this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
- // Prepare the context object, update the WebGL Instanced Array buffer if needed
- var renderCount = _this._prepareContext(engine, context_1, v);
- // If null is returned, there's no opaque data to render
- if (renderCount === null) {
- return;
- }
- // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
- if (!_this.owner.supportInstancedArray || renderCount > 0) {
- // render all the instances of this model, if the render method returns true then our instances are no longer dirty
- var renderFailed = !v.modelRenderCache.render(v, context_1);
- // Update dirty flag/related
- v.opaqueDirty = renderFailed;
- failedCount += renderFailed ? 1 : 0;
- }
- });
- // =======================================================================
- // Third pass, transparent primitive rendering
- // Enable Alpha Testing, Disable Depth Write
- engine.setAlphaTesting(true);
- engine.setDepthWrite(false);
- // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
- if (this._renderableData._transparentListChanged) {
- this._updateTransparentData();
- }
- // From this point on we have up to date data to render, so let's go
- failedCount += this._renderTransparentData();
- // =======================================================================
- // Unbind target/restore viewport setting, clear dirty flag, and quit
- // The group's content is no longer dirty
- this._cacheGroupDirty = failedCount !== 0;
- if (this.isCachedGroup) {
- this._unbindCacheTarget();
- }
- else {
- if (curVP) {
- engine.setViewport(curVP);
- }
- }
- this._renderableData.resetPrimDirtyList();
- // Restore saved states
- engine.setAlphaTesting(curAlphaTest);
- engine.setDepthWrite(curDepthWrite);
- }
- };
- Group2D.prototype._setCacheGroupDirty = function () {
- this._cacheGroupDirty = true;
- };
- Group2D.prototype._updateTransparentData = function () {
- this.owner._addUpdateTransparentDataCount(1);
- var rd = this._renderableData;
- // Sort all the primitive from their depth, max (bottom) to min (top)
- rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
- var checkAndAddPrimInSegment = function (seg, tpiI) {
- var tpi = rd._transparentPrimitives[tpiI];
- // Fast rejection: if gii are different
- if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
- return false;
- }
- //let tpiZ = tpi._primitive.actualZOffset;
- // We've made it so far, the tpi can be part of the segment, add it
- tpi._transparentSegment = seg;
- tpi._primitive._updateTransparentSegmentIndices(seg);
- return true;
- };
- // Free the existing TransparentSegments
- for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
- var ts = _a[_i];
- ts.dispose(this.owner.engine);
- }
- rd._transparentSegments.splice(0);
- var prevSeg = null;
- for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
- var tpi = rd._transparentPrimitives[tpiI];
- // Check if the Data in which the primitive is stored is not sorted properly
- if (tpi._groupInstanceInfo.transparentOrderDirty) {
- tpi._groupInstanceInfo.sortTransparentData();
- }
- // Reset the segment, we have to create/rebuild it
- tpi._transparentSegment = null;
- // If there's a previous valid segment, check if this prim can be part of it
- if (prevSeg) {
- checkAndAddPrimInSegment(prevSeg, tpiI);
- }
- // If we couldn't insert in the adjacent segments, he have to create one
- if (!tpi._transparentSegment) {
- var ts = new BABYLON.TransparentSegment();
- ts.groupInsanceInfo = tpi._groupInstanceInfo;
- var prim = tpi._primitive;
- ts.startZ = prim.actualZOffset;
- prim._updateTransparentSegmentIndices(ts);
- ts.endZ = ts.startZ;
- tpi._transparentSegment = ts;
- rd._transparentSegments.push(ts);
- }
- // Update prevSeg
- prevSeg = tpi._transparentSegment;
- }
- //rd._firstChangedPrim = null;
- rd._transparentListChanged = false;
- };
- Group2D.prototype._renderTransparentData = function () {
- var failedCount = 0;
- var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
- var rd = this._renderableData;
- var useInstanced = this.owner.supportInstancedArray;
- var length = rd._transparentSegments.length;
- for (var i = 0; i < length; i++) {
- context.instancedBuffers = null;
- var ts = rd._transparentSegments[i];
- var gii = ts.groupInsanceInfo;
- var mrc = gii.modelRenderCache;
- var engine = this.owner.engine;
- var count = ts.endDataIndex - ts.startDataIndex;
- // Use Instanced Array if it's supported and if there's at least minPartCountToUseInstancedArray prims to draw.
- // We don't want to create an Instanced Buffer for less that minPartCountToUseInstancedArray prims
- if (useInstanced && count >= this.owner.minPartCountToUseInstancedArray) {
- if (!ts.partBuffers) {
- var buffers = new Array();
- for (var j = 0; j < gii.transparentData.length; j++) {
- var gitd = gii.transparentData[j];
- var dfa = gitd._partData;
- var data = dfa.pack();
- var stride = dfa.stride;
- var neededSize = count * stride * 4;
- var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
- var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
- engine.updateArrayBuffer(segData);
- buffers.push(buffer);
- }
- ts.partBuffers = buffers;
- }
- else if (gii.transparentDirty) {
- for (var j = 0; j < gii.transparentData.length; j++) {
- var gitd = gii.transparentData[j];
- var dfa = gitd._partData;
- var data = dfa.pack();
- var stride = dfa.stride;
- var buffer = ts.partBuffers[j];
- var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
- engine.bindArrayBuffer(buffer);
- engine.updateArrayBuffer(segData);
- }
- }
- context.useInstancing = true;
- context.instancesCount = count;
- context.instancedBuffers = ts.partBuffers;
- context.groupInfoPartData = gii.transparentData;
- var renderFailed = !mrc.render(gii, context);
- failedCount += renderFailed ? 1 : 0;
- }
- else {
- context.useInstancing = false;
- context.partDataStartIndex = ts.startDataIndex;
- context.partDataEndIndex = ts.endDataIndex;
- context.groupInfoPartData = gii.transparentData;
- var renderFailed = !mrc.render(gii, context);
- failedCount += renderFailed ? 1 : 0;
- }
- }
- return failedCount;
- };
- Group2D.prototype._prepareContext = function (engine, context, gii) {
- var gipd = null;
- var setDirty;
- var getDirty;
- // Render Mode specifics
- switch (context.renderMode) {
- case BABYLON.Render2DContext.RenderModeOpaque:
- {
- if (!gii.hasOpaqueData) {
- return null;
- }
- setDirty = function (dirty) { gii.opaqueDirty = dirty; };
- getDirty = function () { return gii.opaqueDirty; };
- context.groupInfoPartData = gii.opaqueData;
- gipd = gii.opaqueData;
- break;
- }
- case BABYLON.Render2DContext.RenderModeAlphaTest:
- {
- if (!gii.hasAlphaTestData) {
- return null;
- }
- setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
- getDirty = function () { return gii.alphaTestDirty; };
- context.groupInfoPartData = gii.alphaTestData;
- gipd = gii.alphaTestData;
- break;
- }
- default:
- throw new Error("_prepareContext is only for opaque or alphaTest");
- }
- var renderCount = 0;
- // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
- // Skip it if instanced arrays are not supported
- if (this.owner.supportInstancedArray) {
- // Flag for instancing
- context.useInstancing = true;
- // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
- for (var i = 0; i < gipd.length; i++) {
- var pid = gipd[i];
- // If the instances of the model was changed, pack the data
- var array = pid._partData;
- var instanceData_1 = array.pack();
- renderCount += array.usedElementCount;
- // Compute the size the instance buffer should have
- var neededSize = array.usedElementCount * array.stride * 4;
- // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
- if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
- if (pid._partBuffer) {
- engine.deleteInstancesBuffer(pid._partBuffer);
- }
- pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
- pid._partBufferSize = neededSize;
- setDirty(false);
- // Update the WebGL buffer to match the new content of the instances data
- engine.updateArrayBuffer(instanceData_1);
- }
- else if (getDirty()) {
- // Update the WebGL buffer to match the new content of the instances data
- engine.bindArrayBuffer(pid._partBuffer);
- engine.updateArrayBuffer(instanceData_1);
- }
- }
- setDirty(false);
- }
- else {
- context.partDataStartIndex = 0;
- // Find the first valid object to get the count
- if (context.groupInfoPartData.length > 0) {
- var i = 0;
- while (!context.groupInfoPartData[i]) {
- i++;
- }
- context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
- }
- }
- return renderCount;
- };
- Group2D.prototype._setRenderingScale = function (scale) {
- if (this._renderableData._renderingScale === scale) {
- return;
- }
- this._renderableData._renderingScale = scale;
- };
- Group2D.prototype._bindCacheTarget = function () {
- var curWidth;
- var curHeight;
- var rd = this._renderableData;
- var rs = rd._renderingScale;
- var noResizeScale = rd._noResizeOnScale;
- var isCanvas = this.parent == null;
- var scale;
- if (noResizeScale) {
- scale = isCanvas ? Group2D_1._uV : this.parent.actualScale.multiply(this.owner._canvasLevelScale);
- }
- else {
- scale = this.actualScale.multiply(this.owner._canvasLevelScale);
- }
- var actualSize = this.actualSize;
- if (isCanvas && this.owner.cachingStrategy === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS && this.owner.isScreenSpace) {
- if (this.owner.designSize || this.owner.fitRenderingDevice) {
- Group2D_1._s.width = this.owner.engine.getRenderWidth();
- Group2D_1._s.height = this.owner.engine.getRenderHeight();
- }
- else {
- Group2D_1._s.copyFrom(this.owner.size);
- }
- }
- else {
- Group2D_1._s.width = Math.ceil(actualSize.width * scale.x * rs);
- Group2D_1._s.height = Math.ceil(actualSize.height * scale.y * rs);
- }
- var sizeChanged = !Group2D_1._s.equals(rd._cacheSize);
- if (rd._cacheNode) {
- var size = Group2D_1._s2;
- rd._cacheNode.getInnerSizeToRef(size);
- // Check if we have to deallocate because the size is too small
- if ((size.width < Group2D_1._s.width) || (size.height < Group2D_1._s.height)) {
- // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
- // For World space: no over-provisioning
- var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
- curWidth = Math.floor(Group2D_1._s.width * overprovisioning);
- curHeight = Math.floor(Group2D_1._s.height * overprovisioning);
- //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
- rd._cacheTexture.freeRect(rd._cacheNode);
- rd._cacheNode = null;
- }
- }
- if (!rd._cacheNode) {
- // Check if we have to allocate a rendering zone in the global cache texture
- var res = this.owner._allocateGroupCache(this, this.parent && this.parent.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
- rd._cacheNode = res.node;
- rd._cacheTexture = res.texture;
- if (rd._cacheRenderSprite) {
- rd._cacheRenderSprite.dispose();
- }
- rd._cacheRenderSprite = res.sprite;
- sizeChanged = true;
- }
- else if (sizeChanged) {
- var sprite = rd._cacheRenderSprite;
- if (sprite) {
- sprite.size = actualSize;
- sprite.spriteSize = new BABYLON.Size(actualSize.width * scale.x * rs, actualSize.height * scale.y * rs);
- }
- }
- if (sizeChanged) {
- rd._cacheSize.copyFrom(Group2D_1._s);
- rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
- if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
- rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
- }
- this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
- }
- var pos = Group2D_1._v1;
- rd._cacheNode.getInnerPosToRef(pos);
- rd._cacheTexture.bindTextureForPosSize(pos, Group2D_1._s, true);
- };
- Group2D.prototype._unbindCacheTarget = function () {
- if (this._renderableData._cacheTexture) {
- this._renderableData._cacheTexture.unbindTexture();
- }
- };
- Group2D.prototype._spreadActualScaleDirty = function () {
- if (this._renderableData && this._renderableData._cacheRenderSprite) {
- this.handleGroupChanged(BABYLON.Prim2DBase.actualScaleProperty);
- }
- _super.prototype._spreadActualScaleDirty.call(this);
- };
- Group2D.prototype.handleGroupChanged = function (prop) {
- // This method is only for cachedGroup
- var rd = this._renderableData;
- if (!rd) {
- return;
- }
- var cachedSprite = rd._cacheRenderSprite;
- if (!this.isCachedGroup || !cachedSprite) {
- return;
- }
- // For now we only support these property changes
- // TODO: add more! :)
- switch (prop.id) {
- case BABYLON.Prim2DBase.actualPositionProperty.id:
- cachedSprite.actualPosition = this.actualPosition.clone();
- if (cachedSprite.position != null) {
- cachedSprite.position = cachedSprite.actualPosition.clone();
- }
- break;
- case BABYLON.Prim2DBase.rotationProperty.id:
- cachedSprite.rotation = this.rotation;
- break;
- case BABYLON.Prim2DBase.scaleProperty.id:
- cachedSprite.scale = this.scale;
- break;
- case BABYLON.Prim2DBase.originProperty.id:
- cachedSprite.origin = this.origin.clone();
- break;
- case Group2D_1.actualSizeProperty.id:
- cachedSprite.size = this.actualSize.clone();
- break;
- case Group2D_1.xProperty.id:
- cachedSprite.x = this.x;
- break;
- case Group2D_1.yProperty.id:
- cachedSprite.y = this.y;
- }
- };
- Group2D.prototype.detectGroupStates = function () {
- var isCanvas = this instanceof BABYLON.Canvas2D;
- var canvasStrat = this.owner.cachingStrategy;
- // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
- if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
- this._isRenderableGroup = isCanvas;
- this._isCachedGroup = false;
- }
- else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
- if (isCanvas) {
- this._isRenderableGroup = true;
- this._isCachedGroup = true;
- }
- else {
- this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
- this._isCachedGroup = false;
- }
- }
- else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
- if (isCanvas) {
- this._isRenderableGroup = true;
- this._isCachedGroup = false;
- }
- else {
- if (this.hierarchyDepth === 1) {
- this._isRenderableGroup = true;
- this._isCachedGroup = true;
- }
- else {
- this._isRenderableGroup = false;
- this._isCachedGroup = false;
- }
- }
- }
- else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
- if (isCanvas) {
- this._isRenderableGroup = true;
- this._isCachedGroup = false;
- }
- else {
- var gcb = this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_OPTIONMASK;
- if ((gcb === Group2D_1.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D_1.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
- this._isRenderableGroup = gcb === Group2D_1.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
- this._isCachedGroup = false;
- }
- if (gcb === Group2D_1.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
- this._isRenderableGroup = true;
- this._isCachedGroup = true;
- }
- }
- }
- if (this._isRenderableGroup) {
- // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
- if (!this._renderableData) {
- this._renderableData = new RenderableGroupData();
- }
- }
- // If the group is tagged as renderable we add it to the renderable tree
- if (this._isCachedGroup) {
- this._renderableData._noResizeOnScale = (this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
- var cur = this.parent;
- while (cur) {
- if (cur instanceof Group2D_1 && cur._isRenderableGroup) {
- if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
- cur._renderableData._childrenRenderableGroups.push(this);
- }
- break;
- }
- cur = cur.parent;
- }
- }
- };
- Object.defineProperty(Group2D.prototype, "_cachedTexture", {
- get: function () {
- if (this._renderableData) {
- return this._renderableData._cacheTexture;
- }
- return null;
- },
- enumerable: true,
- configurable: true
- });
- return Group2D;
- }(BABYLON.Prim2DBase));
- Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
- /**
- * Default behavior, the group will use the caching strategy defined at the Canvas Level
- */
- Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
- /**
- * When used, this group's content won't be cached, no matter which strategy used.
- * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
- */
- Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
- /**
- * When used, the group's content will be cached in the nearest cached parent group/canvas
- */
- Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
- /**
- * 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
- */
- Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE = 0x100;
- Group2D.GROUPCACHEBEHAVIOR_OPTIONMASK = 0xFF;
- Group2D._uV = new BABYLON.Vector2(1, 1);
- Group2D._s = BABYLON.Size.Zero();
- Group2D._v1 = BABYLON.Vector2.Zero();
- Group2D._s2 = BABYLON.Size.Zero();
- Group2D._unS = new BABYLON.Vector2(1, 1);
- __decorate([
- BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D_1.sizeProperty = pi; }, false, true)
- ], Group2D.prototype, "size", null);
- Group2D = Group2D_1 = __decorate([
- BABYLON.className("Group2D", "BABYLON")
- /**
- * A non renderable primitive that defines a logical group.
- * Can also serve the purpose of caching its content into a bitmap to reduce rendering overhead
- */
- ], Group2D);
- BABYLON.Group2D = Group2D;
- var RenderableGroupData = (function () {
- function RenderableGroupData() {
- this._primDirtyList = new Array();
- this._primNewDirtyList = new Array();
- this._childrenRenderableGroups = new Array();
- this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
- this._transparentPrimitives = new Array();
- this._transparentSegments = new Array();
- this._transparentListChanged = false;
- this._cacheNode = null;
- this._cacheTexture = null;
- this._cacheRenderSprite = null;
- this._renderingScale = 1;
- this._cacheNodeUVs = null;
- this._cacheNodeUVsChangedObservable = null;
- this._cacheSize = BABYLON.Size.Zero();
- this._useMipMap = false;
- this._anisotropicLevel = 1;
- this._noResizeOnScale = false;
- }
- RenderableGroupData.prototype.dispose = function (owner) {
- var engine = owner.engine;
- if (this._cacheRenderSprite) {
- this._cacheRenderSprite.dispose();
- this._cacheRenderSprite = null;
- }
- if (this._cacheTexture && this._cacheNode) {
- this._cacheTexture.freeRect(this._cacheNode);
- this._cacheTexture = null;
- this._cacheNode = null;
- }
- if (this._primDirtyList) {
- this._primDirtyList.splice(0);
- this._primDirtyList = null;
- }
- if (this._renderGroupInstancesInfo) {
- this._renderGroupInstancesInfo.forEach(function (k, v) {
- v.dispose();
- });
- this._renderGroupInstancesInfo = null;
- }
- if (this._cacheNodeUVsChangedObservable) {
- this._cacheNodeUVsChangedObservable.clear();
- this._cacheNodeUVsChangedObservable = null;
- }
- if (this._transparentSegments) {
- for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
- var ts = _a[_i];
- ts.dispose(engine);
- }
- this._transparentSegments.splice(0);
- this._transparentSegments = null;
- }
- };
- RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
- var tpi = new TransparentPrimitiveInfo();
- tpi._primitive = prim;
- tpi._groupInstanceInfo = gii;
- tpi._transparentSegment = null;
- this._transparentPrimitives.push(tpi);
- this._transparentListChanged = true;
- return tpi;
- };
- RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
- var index = this._transparentPrimitives.indexOf(tpi);
- if (index !== -1) {
- this._transparentPrimitives.splice(index, 1);
- this._transparentListChanged = true;
- }
- };
- RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
- this._transparentListChanged = true;
- //this.updateSmallestZChangedPrim(tpi);
- };
- RenderableGroupData.prototype.resetPrimDirtyList = function () {
- var dirtyList = this._primDirtyList;
- var numDirty = dirtyList.length;
- for (var i = 0; i < numDirty; i++) {
- if (dirtyList[i]._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
- dirtyList[i]._resetPropertiesDirty();
- }
- }
- dirtyList.length = 0;
- };
- return RenderableGroupData;
- }());
- BABYLON.RenderableGroupData = RenderableGroupData;
- var TransparentPrimitiveInfo = (function () {
- function TransparentPrimitiveInfo() {
- }
- return TransparentPrimitiveInfo;
- }());
- BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
- var Group2D_1;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.group2d.js.map
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var WireFrame2DRenderCache = (function (_super) {
- __extends(WireFrame2DRenderCache, _super);
- function WireFrame2DRenderCache() {
- var _this = _super !== null && _super.apply(this, arguments) || this;
- _this.effectsReady = false;
- _this.vb = null;
- _this.vtxCount = 0;
- _this.instancingAttributes = null;
- _this.effect = null;
- _this.effectInstanced = null;
- return _this;
- }
- WireFrame2DRenderCache.prototype.render = function (instanceInfo, context) {
- // Do nothing if the shader is still loading/preparing
- if (!this.effectsReady) {
- if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
- return false;
- }
- this.effectsReady = true;
- }
- // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
- var canvas = instanceInfo.owner.owner;
- var engine = canvas.engine;
- var cur = engine.getAlphaMode();
- var effect = context.useInstancing ? this.effectInstanced : this.effect;
- engine.enableEffect(effect);
- engine.bindBuffersDirectly(this.vb, null, [2, 4], 24, effect);
- if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
- engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
- }
- var pid = context.groupInfoPartData[0];
- if (context.useInstancing) {
- if (!this.instancingAttributes) {
- this.instancingAttributes = this.loadInstancingAttributes(WireFrame2D.WIREFRAME2D_MAINPARTID, effect);
- }
- var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
- var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
- canvas._addDrawCallCount(1, context.renderMode);
- engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
- engine.drawUnIndexed(false, 0, this.vtxCount, count);
- // engine.draw(true, 0, 6, count);
- engine.unbindInstanceAttributes();
- }
- else {
- canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
- for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
- this.setupUniforms(effect, 0, pid._partData, i);
- engine.drawUnIndexed(false, 0, this.vtxCount);
- // engine.draw(true, 0, 6);
- }
- }
- engine.setAlphaMode(cur, true);
- return true;
- };
- WireFrame2DRenderCache.prototype.updateModelRenderCache = function (prim) {
- var w = prim;
- w._updateVertexBuffer(this);
- return true;
- };
- WireFrame2DRenderCache.prototype.dispose = function () {
- if (!_super.prototype.dispose.call(this)) {
- return false;
- }
- if (this.vb) {
- this._engine._releaseBuffer(this.vb);
- this.vb = null;
- }
- this.effect = null;
- this.effectInstanced = null;
- return true;
- };
- return WireFrame2DRenderCache;
- }(BABYLON.ModelRenderCache));
- BABYLON.WireFrame2DRenderCache = WireFrame2DRenderCache;
- var WireFrameVertex2D = (function () {
- function WireFrameVertex2D(p, c) {
- if (c === void 0) { c = null; }
- this.fromVector2(p);
- if (c != null) {
- this.fromColor4(c);
- }
- else {
- this.r = this.g = this.b = this.a = 1;
- }
- }
- WireFrameVertex2D.prototype.fromVector2 = function (p) {
- this.x = p.x;
- this.y = p.y;
- };
- WireFrameVertex2D.prototype.fromColor3 = function (c) {
- this.r = c.r;
- this.g = c.g;
- this.b = c.b;
- this.a = 1;
- };
- WireFrameVertex2D.prototype.fromColor4 = function (c) {
- this.r = c.r;
- this.g = c.g;
- this.b = c.b;
- this.a = c.a;
- };
- return WireFrameVertex2D;
- }());
- WireFrameVertex2D = __decorate([
- BABYLON.className("WireFrameVertex2D", "BABYLON")
- ], WireFrameVertex2D);
- BABYLON.WireFrameVertex2D = WireFrameVertex2D;
- var WireFrameGroup2D = (function () {
- /**
- * Construct a WireFrameGroup2D object
- * @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.
- * @param defaultColor specify the default color that will be used when a vertex is pushed, white will be used if not specified.
- */
- function WireFrameGroup2D(id, defaultColor) {
- if (id === void 0) { id = null; }
- if (defaultColor === void 0) { defaultColor = null; }
- this._id = (id == null) ? BABYLON.Tools.RandomId() : id;
- this._uid = BABYLON.Tools.RandomId();
- this._defaultColor = (defaultColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : defaultColor;
- this._buildingStrip = false;
- this._vertices = new Array();
- }
- Object.defineProperty(WireFrameGroup2D.prototype, "uid", {
- get: function () {
- return this._uid;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(WireFrameGroup2D.prototype, "id", {
- /**
- * Retrieve the ID of the group
- */
- get: function () {
- return this._id;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Push a vertex in the array of vertices.
- * 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.
- * @param p Position of the vertex
- * @param c Color of the vertex, if null the default color of the group will be used
- */
- WireFrameGroup2D.prototype.pushVertex = function (p, c) {
- if (c === void 0) { c = null; }
- var v = new WireFrameVertex2D(p, (c == null) ? this._defaultColor : c);
- this._vertices.push(v);
- if (this._buildingStrip) {
- var v2 = new WireFrameVertex2D(p, (c == null) ? this._defaultColor : c);
- this._vertices.push(v2);
- }
- };
- /**
- * 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!!!
- * @param p Position of the vertex
- * @param c Color of the vertex, if null the default color of the group will be used
- */
- WireFrameGroup2D.prototype.startLineStrip = function (p, c) {
- if (c === void 0) { c = null; }
- this.pushVertex(p, (c == null) ? this._defaultColor : c);
- this._buildingStrip = true;
- };
- /**
- * Close the Strip by storing a last vertex
- * @param p Position of the vertex
- * @param c Color of the vertex, if null the default color of the group will be used
- */
- WireFrameGroup2D.prototype.endLineStrip = function (p, c) {
- if (c === void 0) { c = null; }
- this._buildingStrip = false;
- this.pushVertex(p, (c == null) ? this._defaultColor : c);
- };
- Object.defineProperty(WireFrameGroup2D.prototype, "vertices", {
- /**
- * Access to the array of Vertices, you can manipulate its content but BEWARE of what you're doing!
- */
- get: function () {
- return this._vertices;
- },
- enumerable: true,
- configurable: true
- });
- return WireFrameGroup2D;
- }());
- WireFrameGroup2D = __decorate([
- BABYLON.className("WireFrameGroup2D", "BABYLON")
- /**
- * A WireFrameGroup2D has a unique id (among the WireFrame2D primitive) and a collection of WireFrameVertex2D which form a Line list.
- * A Line is defined by two vertices, the storage of vertices doesn't follow the Line Strip convention, so to create consecutive lines the intermediate vertex must be doubled. The best way to build a Line Strip is to use the startLineStrip, pushVertex and endLineStrip methods.
- * You can manually add vertices using the pushVertex method, but mind that the vertices array must be a multiple of 2 as each line are defined with TWO SEPARATED vertices. I hope this is clear enough.
- */
- ], WireFrameGroup2D);
- BABYLON.WireFrameGroup2D = WireFrameGroup2D;
- var WireFrame2D = WireFrame2D_1 = (function (_super) {
- __extends(WireFrame2D, _super);
- /**
- * Create an WireFrame 2D primitive
- * @param wireFrameGroups an array of WireFrameGroup.
- * @param settings a combination of settings, possible ones are
- * - 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)
- * - children: an array of direct children
- * - id a text identifier, for information purpose
- * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
- * - rotation: the initial rotation (in radian) of the primitive. default is 0
- * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
- * - size: the size of the sprite displayed in the canvas, if not specified the spriteSize will be used
- * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
- * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
- * - zOrder: override the zOrder with the specified value
- * - origin: define the normalized origin point location, default [0.5;0.5]
- * - alignToPixel: the rendered lines will be aligned to the rendering device' pixels
- * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
- * - 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.
- * - 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.
- * - 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!
- * - 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.
- * - 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).
- * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
- * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
- * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
- * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
- * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
- * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
- */
- function WireFrame2D(wireFrameGroups, settings) {
- var _this = this;
- if (!settings) {
- settings = {};
- }
- _this = _super.call(this, settings) || this;
- _this._wireFrameGroups = new BABYLON.StringDictionary();
- for (var _i = 0, wireFrameGroups_1 = wireFrameGroups; _i < wireFrameGroups_1.length; _i++) {
- var wfg = wireFrameGroups_1[_i];
- _this._wireFrameGroups.add(wfg.id, wfg);
- }
- _this._vtxTransparent = false;
- if (settings.size != null) {
- _this.size = settings.size;
- }
- _this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
- return _this;
- }
- Object.defineProperty(WireFrame2D.prototype, "wireFrameGroups", {
- get: function () {
- return this._wireFrameGroups;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * If you change the content of the wireFrameGroups you MUST call this method for the changes to be reflected during rendering
- */
- WireFrame2D.prototype.wireFrameGroupsDirty = function () {
- this._setFlags(BABYLON.SmartPropertyPrim.flagModelUpdate);
- this.onPrimBecomesDirty();
- };
- Object.defineProperty(WireFrame2D.prototype, "size", {
- get: function () {
- if (this._size == null) {
- this._computeMinMaxTrans();
- }
- return this._size;
- },
- set: function (value) {
- this.internalSetSize(value);
- },
- enumerable: true,
- configurable: true
- });
- WireFrame2D.prototype.updateLevelBoundingInfo = function () {
- var v = this._computeMinMaxTrans();
- BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(v.x, v.z, v.y, v.w, this._levelBoundingInfo);
- return true;
- };
- WireFrame2D.prototype.levelIntersect = function (intersectInfo) {
- // TODO !
- return true;
- };
- Object.defineProperty(WireFrame2D.prototype, "alignToPixel", {
- /**
- * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
- */
- get: function () {
- return this._alignToPixel;
- },
- set: function (value) {
- this._alignToPixel = value;
- },
- enumerable: true,
- configurable: true
- });
- WireFrame2D.prototype.createModelRenderCache = function (modelKey) {
- var renderCache = new WireFrame2DRenderCache(this.owner.engine, modelKey);
- return renderCache;
- };
- WireFrame2D.prototype.setupModelRenderCache = function (modelRenderCache) {
- var renderCache = modelRenderCache;
- var engine = this.owner.engine;
- // Create the VertexBuffer
- this._updateVertexBuffer(renderCache);
- // 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
- var ei = this.getDataPartEffectInfo(WireFrame2D_1.WIREFRAME2D_MAINPARTID, ["pos", "col"], [], true);
- if (ei) {
- renderCache.effectInstanced = engine.createEffect("wireframe2d", ei.attributes, ei.uniforms, [], ei.defines, null);
- }
- ei = this.getDataPartEffectInfo(WireFrame2D_1.WIREFRAME2D_MAINPARTID, ["pos", "col"], [], false);
- renderCache.effect = engine.createEffect("wireframe2d", ei.attributes, ei.uniforms, [], ei.defines, null);
- return renderCache;
- };
- WireFrame2D.prototype._updateVertexBuffer = function (mrc) {
- var engine = this.owner.engine;
- if (mrc.vb != null) {
- engine._releaseBuffer(mrc.vb);
- }
- var vtxCount = 0;
- this._wireFrameGroups.forEach(function (k, v) { return vtxCount += v.vertices.length; });
- var vb = new Float32Array(vtxCount * 6);
- var i = 0;
- this._wireFrameGroups.forEach(function (k, v) {
- for (var _i = 0, _a = v.vertices; _i < _a.length; _i++) {
- var vtx = _a[_i];
- vb[i++] = vtx.x;
- vb[i++] = vtx.y;
- vb[i++] = vtx.r;
- vb[i++] = vtx.g;
- vb[i++] = vtx.b;
- vb[i++] = vtx.a;
- }
- });
- mrc.vb = engine.createVertexBuffer(vb);
- mrc.vtxCount = vtxCount;
- };
- WireFrame2D.prototype.refreshInstanceDataPart = function (part) {
- if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
- return false;
- }
- return true;
- };
- WireFrame2D.prototype._computeMinMaxTrans = function () {
- var xmin = Number.MAX_VALUE;
- var xmax = Number.MIN_VALUE;
- var ymin = Number.MAX_VALUE;
- var ymax = Number.MIN_VALUE;
- var transparent = false;
- this._wireFrameGroups.forEach(function (k, v) {
- for (var _i = 0, _a = v.vertices; _i < _a.length; _i++) {
- var vtx = _a[_i];
- xmin = Math.min(xmin, vtx.x);
- xmax = Math.max(xmax, vtx.x);
- ymin = Math.min(ymin, vtx.y);
- ymax = Math.max(ymax, vtx.y);
- if (vtx.a < 1) {
- transparent = true;
- }
- }
- });
- this._vtxTransparent = transparent;
- this._size = new BABYLON.Size(xmax - xmin, ymax - ymin);
- return new BABYLON.Vector4(xmin, ymin, xmax, ymax);
- };
- WireFrame2D.prototype.createInstanceDataParts = function () {
- return [new WireFrame2DInstanceData(WireFrame2D_1.WIREFRAME2D_MAINPARTID)];
- };
- return WireFrame2D;
- }(BABYLON.RenderablePrim2D));
- WireFrame2D.WIREFRAME2D_MAINPARTID = 1;
- __decorate([
- BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return WireFrame2D_1.wireFrameGroupsProperty = pi; })
- /**
- * Get/set the texture that contains the sprite to display
- */
- ], WireFrame2D.prototype, "wireFrameGroups", null);
- WireFrame2D = WireFrame2D_1 = __decorate([
- BABYLON.className("WireFrame2D", "BABYLON")
- /**
- * Primitive that displays a WireFrame
- */
- ], WireFrame2D);
- BABYLON.WireFrame2D = WireFrame2D;
- var WireFrame2DInstanceData = (function (_super) {
- __extends(WireFrame2DInstanceData, _super);
- function WireFrame2DInstanceData(partId) {
- return _super.call(this, partId, 1) || this;
- }
- return WireFrame2DInstanceData;
- }(BABYLON.InstanceDataBase));
- BABYLON.WireFrame2DInstanceData = WireFrame2DInstanceData;
- var WireFrame2D_1;
- })(BABYLON || (BABYLON = {}));
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var Rectangle2DRenderCache = (function (_super) {
- __extends(Rectangle2DRenderCache, _super);
- function Rectangle2DRenderCache(engine, modelKey) {
- var _this = _super.call(this, engine, modelKey) || this;
- _this.effectsReady = false;
- _this.fillVB = null;
- _this.fillIB = null;
- _this.fillIndicesCount = 0;
- _this.instancingFillAttributes = null;
- _this.effectFill = null;
- _this.effectFillInstanced = null;
- _this.borderVB = null;
- _this.borderIB = null;
- _this.borderIndicesCount = 0;
- _this.instancingBorderAttributes = null;
- _this.effectBorder = null;
- _this.effectBorderInstanced = null;
- return _this;
- }
- Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
- // Do nothing if the shader is still loading/preparing
- if (!this.effectsReady) {
- if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
- (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
- return false;
- }
- this.effectsReady = true;
- }
- var canvas = instanceInfo.owner.owner;
- var engine = canvas.engine;
- var depthFunction = 0;
- if (this.effectFill && this.effectBorder) {
- depthFunction = engine.getDepthFunction();
- engine.setDepthFunctionToLessOrEqual();
- }
- var curAlphaMode = engine.getAlphaMode();
- if (this.effectFill) {
- var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
- var pid = context.groupInfoPartData[partIndex];
- if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
- engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
- }
- var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
- engine.enableEffect(effect);
- engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
- if (context.useInstancing) {
- if (!this.instancingFillAttributes) {
- this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
- }
- var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
- var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
- canvas._addDrawCallCount(1, context.renderMode);
- engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
- engine.draw(true, 0, this.fillIndicesCount, count);
- engine.unbindInstanceAttributes();
- }
- else {
- canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
- for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
- this.setupUniforms(effect, partIndex, pid._partData, i);
- engine.draw(true, 0, this.fillIndicesCount);
- }
- }
- }
- if (this.effectBorder) {
- var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
- var pid = context.groupInfoPartData[partIndex];
- if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
- engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
- }
- var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
- engine.enableEffect(effect);
- engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
- if (context.useInstancing) {
- if (!this.instancingBorderAttributes) {
- this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
- }
- var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
- var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
- canvas._addDrawCallCount(1, context.renderMode);
- engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
- engine.draw(true, 0, this.borderIndicesCount, count);
- engine.unbindInstanceAttributes();
- }
- else {
- canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
- for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
- this.setupUniforms(effect, partIndex, pid._partData, i);
- engine.draw(true, 0, this.borderIndicesCount);
- }
- }
- }
- engine.setAlphaMode(curAlphaMode, true);
- if (this.effectFill && this.effectBorder) {
- engine.setDepthFunction(depthFunction);
- }
- return true;
- };
- Rectangle2DRenderCache.prototype.dispose = function () {
- if (!_super.prototype.dispose.call(this)) {
- return false;
- }
- if (this.fillVB) {
- this._engine._releaseBuffer(this.fillVB);
- this.fillVB = null;
- }
- if (this.fillIB) {
- this._engine._releaseBuffer(this.fillIB);
- this.fillIB = null;
- }
- this.effectFill = null;
- this.effectFillInstanced = null;
- this.effectBorder = null;
- this.effectBorderInstanced = null;
- if (this.borderVB) {
- this._engine._releaseBuffer(this.borderVB);
- this.borderVB = null;
- }
- if (this.borderIB) {
- this._engine._releaseBuffer(this.borderIB);
- this.borderIB = null;
- }
- return true;
- };
- return Rectangle2DRenderCache;
- }(BABYLON.ModelRenderCache));
- BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
- var Rectangle2DInstanceData = (function (_super) {
- __extends(Rectangle2DInstanceData, _super);
- function Rectangle2DInstanceData(partId) {
- return _super.call(this, partId, 1) || this;
- }
- Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- return Rectangle2DInstanceData;
- }(BABYLON.Shape2DInstanceData));
- __decorate([
- BABYLON.instanceData()
- ], Rectangle2DInstanceData.prototype, "properties", null);
- BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
- var Rectangle2D = Rectangle2D_1 = (function (_super) {
- __extends(Rectangle2D, _super);
- /**
- * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
- * @param settings a combination of settings, possible ones are
- * - 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)
- * - children: an array of direct children
- * - id a text identifier, for information purpose
- * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
- * - rotation: the initial rotation (in radian) of the primitive. default is 0
- * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
- * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
- * - alignToPixel: if true the primitive will be aligned to the target rendering device's pixel
- * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
- * - zOrder: override the zOrder with the specified value
- * - origin: define the normalized origin point location, default [0.5;0.5]
- * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
- * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
- * - 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)
- * - 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)
- * - borderThickness: the thickness of the drawn border, default is 1.
- * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
- * - 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.
- * - 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.
- * - 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!
- * - 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.
- * - 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).
- * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
- * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
- * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
- * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
- * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
- * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
- */
- function Rectangle2D(settings) {
- var _this = this;
- // Avoid checking every time if the object exists
- if (settings == null) {
- settings = {};
- }
- _this = _super.call(this, settings) || this;
- if (settings.size != null) {
- _this.size = settings.size;
- }
- else if (settings.width || settings.height) {
- var size = new BABYLON.Size(settings.width, settings.height);
- _this.size = size;
- }
- //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
- var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
- var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
- //this.size = size;
- _this.roundRadius = roundRadius;
- _this.borderThickness = borderThickness;
- return _this;
- }
- Object.defineProperty(Rectangle2D.prototype, "notRounded", {
- get: function () {
- return this._notRounded;
- },
- set: function (value) {
- this._notRounded = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
- get: function () {
- return this._roundRadius;
- },
- set: function (value) {
- this._roundRadius = value;
- this.notRounded = value === 0;
- this._positioningDirty();
- },
- enumerable: true,
- configurable: true
- });
- Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
- // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
- if (this.notRounded) {
- return true;
- }
- // 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.
- // 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)
- // 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.
- // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
- var size = this.size;
- Rectangle2D_1._i0.x = intersectInfo._localPickPosition.x;
- Rectangle2D_1._i0.y = intersectInfo._localPickPosition.y;
- var rr = this.roundRadius;
- var rrs = rr * rr;
- // Check if the point is in the bottom/left quarter area
- Rectangle2D_1._i1.x = rr;
- Rectangle2D_1._i1.y = rr;
- if (Rectangle2D_1._i0.x <= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y <= Rectangle2D_1._i1.y) {
- // Compute the intersection point in the quarter local space
- Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
- Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
- // It's a hit if the squared distance is less/equal to the squared radius of the round circle
- return Rectangle2D_1._i2.lengthSquared() <= rrs;
- }
- // Check if the point is in the top/left quarter area
- Rectangle2D_1._i1.x = rr;
- Rectangle2D_1._i1.y = size.height - rr;
- if (Rectangle2D_1._i0.x <= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y >= Rectangle2D_1._i1.y) {
- // Compute the intersection point in the quarter local space
- Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
- Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
- // It's a hit if the squared distance is less/equal to the squared radius of the round circle
- return Rectangle2D_1._i2.lengthSquared() <= rrs;
- }
- // Check if the point is in the top/right quarter area
- Rectangle2D_1._i1.x = size.width - rr;
- Rectangle2D_1._i1.y = size.height - rr;
- if (Rectangle2D_1._i0.x >= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y >= Rectangle2D_1._i1.y) {
- // Compute the intersection point in the quarter local space
- Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
- Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
- // It's a hit if the squared distance is less/equal to the squared radius of the round circle
- return Rectangle2D_1._i2.lengthSquared() <= rrs;
- }
- // Check if the point is in the bottom/right quarter area
- Rectangle2D_1._i1.x = size.width - rr;
- Rectangle2D_1._i1.y = rr;
- if (Rectangle2D_1._i0.x >= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y <= Rectangle2D_1._i1.y) {
- // Compute the intersection point in the quarter local space
- Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
- Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
- // It's a hit if the squared distance is less/equal to the squared radius of the round circle
- return Rectangle2D_1._i2.lengthSquared() <= rrs;
- }
- // At any other locations the point is guarantied to be inside
- return true;
- };
- Rectangle2D.prototype.updateLevelBoundingInfo = function () {
- BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
- return true;
- };
- Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
- var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
- return renderCache;
- };
- Rectangle2D.prototype.updateTriArray = function () {
- // Not Rounded = sharp edge rect, the default implementation is the right one!
- if (this.notRounded) {
- _super.prototype.updateTriArray.call(this);
- return;
- }
- // Rounded Corner? It's more complicated! :)
- var subDiv = Rectangle2D_1.roundSubdivisions * 4;
- if (this._primTriArray == null) {
- this._primTriArray = new BABYLON.Tri2DArray(subDiv);
- }
- else {
- this._primTriArray.clear(subDiv);
- }
- var size = this.actualSize;
- var w = size.width;
- var h = size.height;
- var r = this.roundRadius;
- var rsub0 = subDiv * 0.25;
- var rsub1 = subDiv * 0.50;
- var rsub2 = subDiv * 0.75;
- var center = new BABYLON.Vector2(0.5 * size.width, 0.5 * size.height);
- var twopi = Math.PI * 2;
- var nru = r / w;
- var nrv = r / h;
- var computePos = function (index, p) {
- // right/bottom
- if (index < rsub0) {
- p.x = 1.0 - nru;
- p.y = nrv;
- }
- else if (index < rsub1) {
- p.x = nru;
- p.y = nrv;
- }
- else if (index < rsub2) {
- p.x = nru;
- p.y = 1.0 - nrv;
- }
- else {
- p.x = 1.0 - nru;
- p.y = 1.0 - nrv;
- }
- var angle = twopi - (index * twopi / (subDiv - 0.5));
- p.x += Math.cos(angle) * nru;
- p.y += Math.sin(angle) * nrv;
- p.x *= w;
- p.y *= h;
- };
- console.log("Genetre TriList for " + this.id);
- var first = BABYLON.Vector2.Zero();
- var cur = BABYLON.Vector2.Zero();
- computePos(0, first);
- var prev = first.clone();
- for (var index = 1; index < subDiv; index++) {
- computePos(index, cur);
- this._primTriArray.storeTriangle(index - 1, center, prev, cur);
- console.log(index - 1 + ", " + center + ", " + prev + ", " + cur);
- prev.copyFrom(cur);
- }
- this._primTriArray.storeTriangle(subDiv - 1, center, first, prev);
- console.log(subDiv - 1 + ", " + center + ", " + prev + ", " + first);
- };
- Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
- var renderCache = modelRenderCache;
- var engine = this.owner.engine;
- // Need to create WebGL resources for fill part?
- if (this.fill) {
- var vbSize = ((this.notRounded ? 1 : Rectangle2D_1.roundSubdivisions) * 4) + 1;
- var vb = new Float32Array(vbSize);
- for (var i = 0; i < vbSize; i++) {
- vb[i] = i;
- }
- renderCache.fillVB = engine.createVertexBuffer(vb);
- var triCount = vbSize - 1;
- var ib = new Float32Array(triCount * 3);
- for (var i = 0; i < triCount; i++) {
- ib[i * 3 + 0] = 0;
- ib[i * 3 + 2] = i + 1;
- ib[i * 3 + 1] = i + 2;
- }
- ib[triCount * 3 - 2] = 1;
- renderCache.fillIB = engine.createIndexBuffer(ib);
- renderCache.fillIndicesCount = triCount * 3;
- // 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
- var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
- if (ei) {
- renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
- }
- // Get the non instanced version
- ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
- renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
- }
- // Need to create WebGL resource for border part?
- if (this.border) {
- var vbSize = (this.notRounded ? 1 : Rectangle2D_1.roundSubdivisions) * 4 * 2;
- var vb = new Float32Array(vbSize);
- for (var i = 0; i < vbSize; i++) {
- vb[i] = i;
- }
- renderCache.borderVB = engine.createVertexBuffer(vb);
- var triCount = vbSize;
- var rs = triCount / 2;
- var ib = new Float32Array(triCount * 3);
- for (var i = 0; i < rs; i++) {
- var r0 = i;
- var r1 = (i + 1) % rs;
- ib[i * 6 + 0] = rs + r1;
- ib[i * 6 + 1] = rs + r0;
- ib[i * 6 + 2] = r0;
- ib[i * 6 + 3] = r1;
- ib[i * 6 + 4] = rs + r1;
- ib[i * 6 + 5] = r0;
- }
- renderCache.borderIB = engine.createIndexBuffer(ib);
- renderCache.borderIndicesCount = triCount * 3;
- // 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
- var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
- if (ei) {
- renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
- }
- // Get the non instanced version
- ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
- renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
- }
- return renderCache;
- };
- // 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
- Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
- // Fall back to default implementation if there's no round Radius
- if (this._notRounded) {
- _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
- }
- else {
- var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
- initialContentPosition.x = initialContentPosition.y = rr;
- initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
- initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
- initialContentPosition.z = primSize.width - (initialContentPosition.x + initialContentArea.width);
- initialContentPosition.w = primSize.height - (initialContentPosition.y + initialContentArea.height);
- }
- };
- Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, paddingOffset, newPrimSize) {
- // Fall back to default implementation if there's no round Radius
- if (this._notRounded) {
- _super.prototype._getActualSizeFromContentToRef.call(this, primSize, paddingOffset, newPrimSize);
- }
- else {
- var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
- newPrimSize.copyFrom(primSize);
- newPrimSize.width += rr * 2;
- newPrimSize.height += rr * 2;
- paddingOffset.x += rr;
- paddingOffset.y += rr;
- paddingOffset.z += rr;
- paddingOffset.w += rr;
- }
- };
- Rectangle2D.prototype.createInstanceDataParts = function () {
- var res = new Array();
- if (this.border) {
- res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
- }
- if (this.fill) {
- res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
- }
- return res;
- };
- Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
- if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
- return false;
- }
- //let s = Rectangle2D._riv0;
- //this.getActualGlobalScaleToRef(s);
- if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
- var d = part;
- var size = this.actualSize;
- d.properties = new BABYLON.Vector3(size.width /* * s.x*/, size.height /* * s.y*/, this.roundRadius || 0);
- }
- else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
- var d = part;
- var size = this.actualSize;
- d.properties = new BABYLON.Vector3(size.width /* * s.x*/, size.height /* * s.y*/, this.roundRadius || 0);
- }
- return true;
- };
- return Rectangle2D;
- }(BABYLON.Shape2D));
- Rectangle2D._i0 = BABYLON.Vector2.Zero();
- Rectangle2D._i1 = BABYLON.Vector2.Zero();
- Rectangle2D._i2 = BABYLON.Vector2.Zero();
- Rectangle2D.roundSubdivisions = 16;
- Rectangle2D._riv0 = new BABYLON.Vector2(0, 0);
- __decorate([
- BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D_1.notRoundedProperty = pi; })
- /**
- * Get if the rectangle is notRound (returns true) or rounded (returns false).
- * Don't use the setter, it's for internal purpose only
- */
- ], Rectangle2D.prototype, "notRounded", null);
- __decorate([
- BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D_1.roundRadiusProperty = pi; })
- /**
- * Get/set the round Radius, a value of 0 for a sharp edges rectangle, otherwise the value will be used as the diameter of the round to apply on corder. The Rectangle2D.notRounded property will be updated accordingly.
- */
- ], Rectangle2D.prototype, "roundRadius", null);
- Rectangle2D = Rectangle2D_1 = __decorate([
- BABYLON.className("Rectangle2D", "BABYLON")
- /**
- * The Rectangle Primitive type
- */
- ], Rectangle2D);
- BABYLON.Rectangle2D = Rectangle2D;
- var Rectangle2D_1;
- })(BABYLON || (BABYLON = {}));
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var Ellipse2DRenderCache = (function (_super) {
- __extends(Ellipse2DRenderCache, _super);
- function Ellipse2DRenderCache(engine, modelKey) {
- var _this = _super.call(this, engine, modelKey) || this;
- _this.effectsReady = false;
- _this.fillVB = null;
- _this.fillIB = null;
- _this.fillIndicesCount = 0;
- _this.instancingFillAttributes = null;
- _this.effectFillInstanced = null;
- _this.effectFill = null;
- _this.borderVB = null;
- _this.borderIB = null;
- _this.borderIndicesCount = 0;
- _this.instancingBorderAttributes = null;
- _this.effectBorderInstanced = null;
- _this.effectBorder = null;
- return _this;
- }
- Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
- // Do nothing if the shader is still loading/preparing
- if (!this.effectsReady) {
- if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
- (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
- return false;
- }
- this.effectsReady = true;
- }
- var canvas = instanceInfo.owner.owner;
- var engine = canvas.engine;
- var depthFunction = 0;
- if (this.effectFill && this.effectBorder) {
- depthFunction = engine.getDepthFunction();
- engine.setDepthFunctionToLessOrEqual();
- }
- var curAlphaMode = engine.getAlphaMode();
- if (this.effectFill) {
- var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
- var pid = context.groupInfoPartData[partIndex];
- if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
- engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
- }
- var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
- engine.enableEffect(effect);
- engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
- if (context.useInstancing) {
- if (!this.instancingFillAttributes) {
- this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
- }
- var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
- var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
- canvas._addDrawCallCount(1, context.renderMode);
- engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
- engine.draw(true, 0, this.fillIndicesCount, count);
- engine.unbindInstanceAttributes();
- }
- else {
- canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
- for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
- this.setupUniforms(effect, partIndex, pid._partData, i);
- engine.draw(true, 0, this.fillIndicesCount);
- }
- }
- }
- if (this.effectBorder) {
- var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
- var pid = context.groupInfoPartData[partIndex];
- if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
- engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
- }
- var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
- engine.enableEffect(effect);
- engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
- if (context.useInstancing) {
- if (!this.instancingBorderAttributes) {
- this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
- }
- var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
- var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
- canvas._addDrawCallCount(1, context.renderMode);
- engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
- engine.draw(true, 0, this.borderIndicesCount, count);
- engine.unbindInstanceAttributes();
- }
- else {
- canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
- for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
- this.setupUniforms(effect, partIndex, pid._partData, i);
- engine.draw(true, 0, this.borderIndicesCount);
- }
- }
- }
- engine.setAlphaMode(curAlphaMode, true);
- if (this.effectFill && this.effectBorder) {
- engine.setDepthFunction(depthFunction);
- }
- return true;
- };
- Ellipse2DRenderCache.prototype.dispose = function () {
- if (!_super.prototype.dispose.call(this)) {
- return false;
- }
- if (this.fillVB) {
- this._engine._releaseBuffer(this.fillVB);
- this.fillVB = null;
- }
- if (this.fillIB) {
- this._engine._releaseBuffer(this.fillIB);
- this.fillIB = null;
- }
- this.effectFill = null;
- this.effectFillInstanced = null;
- this.effectBorder = null;
- this.effectBorderInstanced = null;
- if (this.borderVB) {
- this._engine._releaseBuffer(this.borderVB);
- this.borderVB = null;
- }
- if (this.borderIB) {
- this._engine._releaseBuffer(this.borderIB);
- this.borderIB = null;
- }
- return true;
- };
- return Ellipse2DRenderCache;
- }(BABYLON.ModelRenderCache));
- BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
- var Ellipse2DInstanceData = (function (_super) {
- __extends(Ellipse2DInstanceData, _super);
- function Ellipse2DInstanceData(partId) {
- return _super.call(this, partId, 1) || this;
- }
- Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- return Ellipse2DInstanceData;
- }(BABYLON.Shape2DInstanceData));
- __decorate([
- BABYLON.instanceData()
- ], Ellipse2DInstanceData.prototype, "properties", null);
- BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
- var Ellipse2D = Ellipse2D_1 = (function (_super) {
- __extends(Ellipse2D, _super);
- /**
- * Create an Ellipse 2D Shape primitive
- * @param settings a combination of settings, possible ones are
- * - 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)
- * - children: an array of direct children
- * - id: a text identifier, for information purpose
- * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
- * - rotation: the initial rotation (in radian) of the primitive. default is 0
- * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
- * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
- * - alignToPixel: if true the primitive will be aligned to the target rendering device's pixel
- * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
- * - zOrder: override the zOrder with the specified value
- * - origin: define the normalized origin point location, default [0.5;0.5]
- * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
- * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
- * - 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)
- * - 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)
- * - borderThickness: the thickness of the drawn border, default is 1.
- * - isVisible: true if the group must be visible, false for hidden. Default is true.
- * - 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.
- * - 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.
- * - 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!
- * - 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.
- * - 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).
- * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
- * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
- * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
- * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
- * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
- * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
- */
- function Ellipse2D(settings) {
- var _this = this;
- // Avoid checking every time if the object exists
- if (settings == null) {
- settings = {};
- }
- _this = _super.call(this, settings) || this;
- if (settings.size != null) {
- _this.size = settings.size;
- }
- else if (settings.width || settings.height) {
- var size = new BABYLON.Size(settings.width, settings.height);
- _this.size = size;
- }
- var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
- _this.subdivisions = sub;
- return _this;
- }
- Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
- get: function () {
- return this._subdivisions;
- },
- set: function (value) {
- this._subdivisions = value;
- },
- enumerable: true,
- configurable: true
- });
- Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
- var w = this.size.width / 2;
- var h = this.size.height / 2;
- var x = intersectInfo._localPickPosition.x - w;
- var y = intersectInfo._localPickPosition.y - h;
- return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
- };
- Ellipse2D.prototype.updateLevelBoundingInfo = function () {
- BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
- return true;
- };
- Ellipse2D.prototype.updateTriArray = function () {
- var subDiv = this._subdivisions;
- if (this._primTriArray == null) {
- this._primTriArray = new BABYLON.Tri2DArray(subDiv);
- }
- else {
- this._primTriArray.clear(subDiv);
- }
- var size = this.actualSize;
- var center = new BABYLON.Vector2(0.5 * size.width, 0.5 * size.height);
- var v1 = BABYLON.Vector2.Zero();
- var v2 = BABYLON.Vector2.Zero();
- for (var i = 0; i < subDiv; i++) {
- var angle1 = Math.PI * 2 * (i - 1) / subDiv;
- var angle2 = Math.PI * 2 * i / subDiv;
- v1.x = ((Math.cos(angle1) / 2.0) + 0.5) * size.width;
- v1.y = ((Math.sin(angle1) / 2.0) + 0.5) * size.height;
- v2.x = ((Math.cos(angle2) / 2.0) + 0.5) * size.width;
- v2.y = ((Math.sin(angle2) / 2.0) + 0.5) * size.height;
- this._primTriArray.storeTriangle(i, center, v1, v2);
- }
- };
- Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
- var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
- return renderCache;
- };
- Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
- var renderCache = modelRenderCache;
- var engine = this.owner.engine;
- // Need to create WebGL resources for fill part?
- if (this.fill) {
- var vbSize = this.subdivisions + 1;
- var vb = new Float32Array(vbSize);
- for (var i = 0; i < vbSize; i++) {
- vb[i] = i;
- }
- renderCache.fillVB = engine.createVertexBuffer(vb);
- var triCount = vbSize - 1;
- var ib = new Float32Array(triCount * 3);
- for (var i = 0; i < triCount; i++) {
- ib[i * 3 + 0] = 0;
- ib[i * 3 + 2] = i + 2;
- ib[i * 3 + 1] = i + 1;
- }
- ib[triCount * 3 - 1] = 1;
- renderCache.fillIB = engine.createIndexBuffer(ib);
- renderCache.fillIndicesCount = triCount * 3;
- // 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
- var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
- if (ei) {
- renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
- }
- // Get the non instanced version
- ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
- renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
- }
- // Need to create WebGL resource for border part?
- if (this.border) {
- var vbSize = this.subdivisions * 2;
- var vb = new Float32Array(vbSize);
- for (var i = 0; i < vbSize; i++) {
- vb[i] = i;
- }
- renderCache.borderVB = engine.createVertexBuffer(vb);
- var triCount = vbSize;
- var rs = triCount / 2;
- var ib = new Float32Array(triCount * 3);
- for (var i = 0; i < rs; i++) {
- var r0 = i;
- var r1 = (i + 1) % rs;
- ib[i * 6 + 0] = rs + r1;
- ib[i * 6 + 1] = rs + r0;
- ib[i * 6 + 2] = r0;
- ib[i * 6 + 3] = r1;
- ib[i * 6 + 4] = rs + r1;
- ib[i * 6 + 5] = r0;
- }
- renderCache.borderIB = engine.createIndexBuffer(ib);
- renderCache.borderIndicesCount = (triCount * 3);
- // 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
- var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
- if (ei) {
- renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
- }
- // Get the non instanced version
- ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
- renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
- }
- return renderCache;
- };
- Ellipse2D.prototype.createInstanceDataParts = function () {
- var res = new Array();
- if (this.border) {
- res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
- }
- if (this.fill) {
- res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
- }
- return res;
- };
- Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
- if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
- return false;
- }
- //let s = Ellipse2D._riv0;
- //this.getActualGlobalScaleToRef(s);
- if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
- var d = part;
- var size = this.actualSize;
- d.properties = new BABYLON.Vector3(size.width /* * s.x*/, size.height /* * s.y*/, this.subdivisions);
- }
- else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
- var d = part;
- var size = this.actualSize;
- d.properties = new BABYLON.Vector3(size.width /* * s.x*/, size.height /* * s.y*/, this.subdivisions);
- }
- return true;
- };
- return Ellipse2D;
- }(BABYLON.Shape2D));
- Ellipse2D._riv0 = new BABYLON.Vector2(0, 0);
- __decorate([
- BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D_1.subdivisionsProperty = pi; })
- /**
- * Get/set the number of subdivisions used to draw the ellipsis. Default is 64.
- */
- ], Ellipse2D.prototype, "subdivisions", null);
- Ellipse2D = Ellipse2D_1 = __decorate([
- BABYLON.className("Ellipse2D", "BABYLON")
- /**
- * Ellipse Primitive class
- */
- ], Ellipse2D);
- BABYLON.Ellipse2D = Ellipse2D;
- var Ellipse2D_1;
- })(BABYLON || (BABYLON = {}));
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var Sprite2DRenderCache = (function (_super) {
- __extends(Sprite2DRenderCache, _super);
- function Sprite2DRenderCache() {
- var _this = _super !== null && _super.apply(this, arguments) || this;
- _this.effectsReady = false;
- _this.vb = null;
- _this.ib = null;
- _this.instancingAttributes = null;
- _this.texture = null;
- _this.effect = null;
- _this.effectInstanced = null;
- return _this;
- }
- Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
- // Do nothing if the shader is still loading/preparing
- if (!this.effectsReady) {
- if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
- return false;
- }
- this.effectsReady = true;
- }
- // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
- var canvas = instanceInfo.owner.owner;
- var engine = canvas.engine;
- var cur = engine.getAlphaMode();
- var effect = context.useInstancing ? this.effectInstanced : this.effect;
- engine.enableEffect(effect);
- effect.setTexture("diffuseSampler", this.texture);
- engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
- if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
- engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
- }
- effect.setBool("alphaTest", context.renderMode === BABYLON.Render2DContext.RenderModeAlphaTest);
- var pid = context.groupInfoPartData[0];
- if (context.useInstancing) {
- if (!this.instancingAttributes) {
- this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
- }
- var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
- var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
- canvas._addDrawCallCount(1, context.renderMode);
- engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
- engine.draw(true, 0, 6, count);
- engine.unbindInstanceAttributes();
- }
- else {
- canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
- for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
- this.setupUniforms(effect, 0, pid._partData, i);
- engine.draw(true, 0, 6);
- }
- }
- engine.setAlphaMode(cur, true);
- return true;
- };
- Sprite2DRenderCache.prototype.dispose = function () {
- if (!_super.prototype.dispose.call(this)) {
- return false;
- }
- if (this.vb) {
- this._engine._releaseBuffer(this.vb);
- this.vb = null;
- }
- if (this.ib) {
- this._engine._releaseBuffer(this.ib);
- this.ib = null;
- }
- //if (this.texture) {
- // this.texture.dispose();
- // this.texture = null;
- //}
- this.effect = null;
- this.effectInstanced = null;
- return true;
- };
- return Sprite2DRenderCache;
- }(BABYLON.ModelRenderCache));
- BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
- var Sprite2D = Sprite2D_1 = (function (_super) {
- __extends(Sprite2D, _super);
- /**
- * Create an 2D Sprite primitive
- * @param texture the texture that stores the sprite to render
- * @param settings a combination of settings, possible ones are
- * - 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)
- * - children: an array of direct children
- * - id a text identifier, for information purpose
- * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
- * - rotation: the initial rotation (in radian) of the primitive. default is 0
- * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
- * - size: the size of the sprite displayed in the canvas, if not specified the spriteSize will be used
- * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
- * - 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.
- * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
- * - zOrder: override the zOrder with the specified value
- * - origin: define the normalized origin point location, default [0.5;0.5]
- * - 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.
- * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
- * - 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
- * - invertY: if true the texture Y will be inverted, default is false.
- * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
- * - 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.
- * - 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.
- * - 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!
- * - 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.
- * - 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).
- * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
- * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
- * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
- * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
- * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
- * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
- */
- function Sprite2D(texture, settings) {
- var _this = this;
- if (!settings) {
- settings = {};
- }
- _this = _super.call(this, settings) || this;
- _this.texture = texture;
- // This is removed to let the user the possibility to setup the addressing mode he wants
- //this.texture.wrapU = Texture.CLAMP_ADDRESSMODE;
- //this.texture.wrapV = Texture.CLAMP_ADDRESSMODE;
- _this._useSize = false;
- _this._spriteSize = (settings.spriteSize != null) ? settings.spriteSize.clone() : null;
- _this._spriteLocation = (settings.spriteLocation != null) ? settings.spriteLocation.clone() : new BABYLON.Vector2(0, 0);
- if (settings.size != null) {
- _this.size = settings.size;
- }
- _this._updatePositioningState();
- _this.spriteFrame = 0;
- _this.invertY = (settings.invertY == null) ? false : settings.invertY;
- _this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
- _this.useAlphaFromTexture = true;
- _this._scale9 = (settings.scale9 != null) ? settings.scale9.clone() : null;
- // 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.
- // The fucking delayed texture sprite bug is fixed!
- if (settings.spriteSize == null) {
- _this.spriteSize = new BABYLON.Size(10, 10);
- }
- if (settings.spriteSize == null || !texture.isReady()) {
- if (texture.isReady()) {
- var s = texture.getBaseSize();
- _this.spriteSize = new BABYLON.Size(s.width, s.height);
- _this._updateSpriteScaleFactor();
- }
- else {
- texture.onLoadObservable.add(function () {
- if (settings.spriteSize == null) {
- var s = texture.getBaseSize();
- _this.spriteSize = new BABYLON.Size(s.width, s.height);
- }
- _this._updateSpriteScaleFactor();
- _this._positioningDirty();
- _this._setLayoutDirty();
- _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId | Sprite2D_1.textureProperty.flagId; // To make sure the sprite is issued again for render
- });
- }
- }
- return _this;
- }
- Object.defineProperty(Sprite2D.prototype, "texture", {
- get: function () {
- return this._texture;
- },
- set: function (value) {
- this._texture = value;
- this._oldTextureHasAlpha = this._texture && this.texture.hasAlpha;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Sprite2D.prototype, "useAlphaFromTexture", {
- get: function () {
- return this._useAlphaFromTexture;
- },
- set: function (value) {
- if (this._useAlphaFromTexture === value) {
- return;
- }
- this._useAlphaFromTexture = value;
- this._updateRenderMode();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Sprite2D.prototype, "size", {
- get: function () {
- if (this._size == null) {
- return this.spriteSize;
- }
- return this.internalGetSize();
- },
- set: function (value) {
- this._useSize = value != null;
- this.internalSetSize(value);
- this._updateSpriteScaleFactor();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Sprite2D.prototype, "spriteSize", {
- get: function () {
- return this._spriteSize;
- },
- set: function (value) {
- if (!this._spriteSize) {
- this._spriteSize = value.clone();
- }
- else {
- this._spriteSize.copyFrom(value);
- }
- this._updateSpriteScaleFactor();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
- get: function () {
- return this._spriteLocation;
- },
- set: function (value) {
- if (!this._spriteLocation) {
- this._spriteLocation = value.clone();
- }
- else {
- this._spriteLocation.copyFrom(value);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
- get: function () {
- return this._spriteFrame;
- },
- set: function (value) {
- this._spriteFrame = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Sprite2D.prototype, "invertY", {
- get: function () {
- return this._invertY;
- },
- set: function (value) {
- this._invertY = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Sprite2D.prototype, "isScale9", {
- get: function () {
- return this._scale9 !== null;
- },
- enumerable: true,
- configurable: true
- });
- //@instanceLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, pi => Sprite2D.spriteScaleFactorProperty = pi)
- ///**
- // * Get/set the sprite location (in pixels) in the texture
- // */
- //public get spriteScaleFactor(): Vector2 {
- // return this._spriteScaleFactor;
- //}
- //public set spriteScaleFactor(value: Vector2) {
- // this._spriteScaleFactor = value;
- //}
- Sprite2D.prototype.updateLevelBoundingInfo = function () {
- BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
- return true;
- };
- /**
- * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
- */
- Sprite2D.prototype.getAnimatables = function () {
- var res = new Array();
- if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
- res.push(this.texture);
- }
- return res;
- };
- Sprite2D.prototype.levelIntersect = function (intersectInfo) {
- // 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
- return true;
- };
- Object.defineProperty(Sprite2D.prototype, "isSizeAuto", {
- get: function () {
- return this.size == null;
- },
- enumerable: true,
- configurable: true
- });
- Sprite2D.prototype.createModelRenderCache = function (modelKey) {
- var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
- return renderCache;
- };
- Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
- var renderCache = modelRenderCache;
- var engine = this.owner.engine;
- var vb = new Float32Array(4);
- for (var i = 0; i < 4; i++) {
- vb[i] = i;
- }
- renderCache.vb = engine.createVertexBuffer(vb);
- var ib = new Float32Array(6);
- ib[0] = 0;
- ib[1] = 2;
- ib[2] = 1;
- ib[3] = 0;
- ib[4] = 3;
- ib[5] = 2;
- renderCache.ib = engine.createIndexBuffer(ib);
- renderCache.texture = this.texture;
- // 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
- var ei = this.getDataPartEffectInfo(Sprite2D_1.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], true);
- if (ei) {
- renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
- }
- ei = this.getDataPartEffectInfo(Sprite2D_1.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], false);
- renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
- return renderCache;
- };
- Sprite2D.prototype.getUsedShaderCategories = function (dataPart) {
- var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
- if (dataPart.id === Sprite2D_1.SPRITE2D_MAINPARTID) {
- var useScale9 = this._scale9 != null;
- if (useScale9) {
- cat.push(Sprite2D_1.SHAPE2D_CATEGORY_SCALE9);
- }
- }
- return cat;
- };
- Sprite2D.prototype.createInstanceDataParts = function () {
- return [new Sprite2DInstanceData(Sprite2D_1.SPRITE2D_MAINPARTID)];
- };
- Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
- Sprite2D_1.layoutConstructMode = true;
- };
- // if obj contains something, we restore the _text property
- Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
- Sprite2D_1.layoutConstructMode = false;
- };
- Sprite2D.prototype.refreshInstanceDataPart = function (part) {
- if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
- return false;
- }
- if (!this.texture.isReady() && !Sprite2D_1.layoutConstructMode) {
- return false;
- }
- if (part.id === Sprite2D_1.SPRITE2D_MAINPARTID) {
- var d = this._instanceDataParts[0];
- if (Sprite2D_1.layoutConstructMode) {
- d.topLeftUV = BABYLON.Vector2.Zero();
- d.sizeUV = BABYLON.Vector2.Zero();
- d.properties = BABYLON.Vector3.Zero();
- d.textureSize = BABYLON.Vector2.Zero();
- d.scaleFactor = BABYLON.Vector2.Zero();
- if (this.isScale9) {
- d.scale9 = BABYLON.Vector4.Zero();
- }
- }
- else {
- var ts = this.texture.getBaseSize();
- var ss = this.spriteSize;
- var sl = this.spriteLocation;
- var ssf = this.actualScale;
- d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
- var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
- d.sizeUV = suv;
- d.scaleFactor = ssf;
- Sprite2D_1._prop.x = this.spriteFrame;
- Sprite2D_1._prop.y = this.invertY ? 1 : 0;
- Sprite2D_1._prop.z = this.alignToPixel ? 1 : 0;
- d.properties = Sprite2D_1._prop;
- d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
- var scale9 = this._scale9;
- if (scale9 != null) {
- 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);
- d.scale9 = normalizedScale9;
- }
- }
- }
- return true;
- };
- Sprite2D.prototype._mustUpdateInstance = function () {
- var res = this._oldTextureHasAlpha !== (this.texture != null && this.texture.hasAlpha);
- this._oldTextureHasAlpha = this.texture != null && this.texture.hasAlpha;
- if (res) {
- this._updateRenderMode();
- }
- return res;
- };
- Sprite2D.prototype._useTextureAlpha = function () {
- return this.texture != null && this.texture.hasAlpha;
- };
- Sprite2D.prototype._shouldUseAlphaFromTexture = function () {
- return this.texture != null && this.texture.hasAlpha && this.useAlphaFromTexture;
- };
- Sprite2D.prototype._updateSpriteScaleFactor = function () {
- if (!this._useSize) {
- return;
- }
- var sS = this.spriteSize;
- var s = this.size;
- if (s == null || sS == null) {
- return;
- }
- this._postScale.x = s.width / sS.width;
- this._postScale.y = s.height / sS.height;
- };
- return Sprite2D;
- }(BABYLON.RenderablePrim2D));
- Sprite2D.SPRITE2D_MAINPARTID = 1;
- Sprite2D.SHAPE2D_CATEGORY_SCALE9 = "Scale9";
- Sprite2D._prop = BABYLON.Vector3.Zero();
- Sprite2D.layoutConstructMode = false;
- __decorate([
- BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D_1.textureProperty = pi; })
- /**
- * Get/set the texture that contains the sprite to display
- */
- ], Sprite2D.prototype, "texture", null);
- __decorate([
- BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D_1.useAlphaFromTextureProperty = pi; })
- /**
- * If true and the texture has an Alpha Channel which is used (BaseTexture.hasAlpha = true) the Sprite2d will be rendered as a Transparent Primitive, if false and the texture has an Alpha Channel which is used (BaseTexture.hasAlpha = true) the Sprite2d will be rendered as Alpha Test. If false or if the Texture has no alpha or it's not used (BaseTexture.hasAlpha = false) the Sprite2d will be rendered as an Opaque Primitive
- */
- ], Sprite2D.prototype, "useAlphaFromTexture", null);
- __decorate([
- BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D_1.spriteSizeProperty = pi; }, false, true)
- /**
- * Get/set the sprite location (in pixels) in the texture
- */
- ], Sprite2D.prototype, "spriteSize", null);
- __decorate([
- BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D_1.spriteLocationProperty = pi; })
- /**
- * Get/set the sprite location (in pixels) in the texture
- */
- ], Sprite2D.prototype, "spriteLocation", null);
- __decorate([
- BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D_1.spriteFrameProperty = pi; })
- /**
- * Get/set the sprite frame to display.
- * The frame number is just an offset applied horizontally, based on the sprite's width. it does not wrap, all the frames must be on the same line.
- */
- ], Sprite2D.prototype, "spriteFrame", null);
- __decorate([
- BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Sprite2D_1.invertYProperty = pi; })
- /**
- * Get/set if the sprite texture coordinates should be inverted on the Y axis
- */
- ], Sprite2D.prototype, "invertY", null);
- __decorate([
- BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 8, function (pi) { return Sprite2D_1.spriteScale9Property = pi; })
- /**
- * Get/set the texture that contains the sprite to display
- */
- ], Sprite2D.prototype, "isScale9", null);
- Sprite2D = Sprite2D_1 = __decorate([
- BABYLON.className("Sprite2D", "BABYLON")
- /**
- * Primitive that displays a Sprite/Picture
- */
- ], Sprite2D);
- BABYLON.Sprite2D = Sprite2D;
- var Sprite2DInstanceData = (function (_super) {
- __extends(Sprite2DInstanceData, _super);
- function Sprite2DInstanceData(partId) {
- return _super.call(this, partId, 1) || this;
- }
- Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
- // 3 floats being:
- // - x: frame number to display
- // - y: invertY setting
- // - z: alignToPixel setting
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Sprite2DInstanceData.prototype, "scale9", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- return Sprite2DInstanceData;
- }(BABYLON.InstanceDataBase));
- __decorate([
- BABYLON.instanceData()
- ], Sprite2DInstanceData.prototype, "topLeftUV", null);
- __decorate([
- BABYLON.instanceData()
- ], Sprite2DInstanceData.prototype, "sizeUV", null);
- __decorate([
- BABYLON.instanceData(Sprite2D.SHAPE2D_CATEGORY_SCALE9)
- ], Sprite2DInstanceData.prototype, "scaleFactor", null);
- __decorate([
- BABYLON.instanceData()
- ], Sprite2DInstanceData.prototype, "textureSize", null);
- __decorate([
- BABYLON.instanceData()
- ], Sprite2DInstanceData.prototype, "properties", null);
- __decorate([
- BABYLON.instanceData(Sprite2D.SHAPE2D_CATEGORY_SCALE9)
- ], Sprite2DInstanceData.prototype, "scale9", null);
- BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
- var Sprite2D_1;
- })(BABYLON || (BABYLON = {}));
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- /**
- * This class will contains information about a sub picture present in an Atlas Picture.
- */
- var AtlasSubPictureInfo = (function () {
- function AtlasSubPictureInfo() {
- }
- return AtlasSubPictureInfo;
- }());
- BABYLON.AtlasSubPictureInfo = AtlasSubPictureInfo;
- /**
- * This class represent an Atlas Picture, it contains the information of all the sub pictures and the Texture that stores the bitmap.
- * You get an instance of this class using methods of the AtlasPictureInfoFactory
- */
- var AtlasPictureInfo = (function () {
- function AtlasPictureInfo() {
- }
- /**
- * Creates many sprite from the Atlas Picture
- * @param filterCallback a predicate if true is returned then the corresponding sub picture will be used to create a sprite.
- * The Predicate has many parameters:
- * - index: just an index incremented at each sub picture submitted for Sprite creation
- * - name: the sub picture's name
- * - aspi: the AtlasSubPictureInfo corresponding to the submitted sub picture
- * - settings: the Sprite2D creation settings, you can alter this JSON object but BEWARE, the alterations will be kept for subsequent Sprite2D creations!
- * @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.
- */
- AtlasPictureInfo.prototype.createSprites = function (filterCallback, spriteSettings) {
- var _this = this;
- var res = new Array();
- var index = 0;
- this.subPictures.forEach(function (k, v) {
- if (!filterCallback || filterCallback(index++, k, v, spriteSettings)) {
- var s = _this.createSprite(k, spriteSettings);
- if (s) {
- res.push(s);
- }
- }
- });
- return res;
- };
- /**
- * Create one Sprite from a sub picture
- * @param subPictureName the name of the sub picture to use
- * @param spriteSettings the Sprite2D settings to use for the Sprite instance creation
- */
- AtlasPictureInfo.prototype.createSprite = function (subPictureName, spriteSettings) {
- var spi = this.subPictures.get(subPictureName);
- if (!spi) {
- return null;
- }
- if (!spriteSettings) {
- spriteSettings = {};
- }
- var s = spriteSettings;
- s.id = subPictureName;
- s.spriteLocation = spi.location;
- s.spriteSize = spi.size;
- var sprite = new BABYLON.Sprite2D(this.texture, spriteSettings);
- return sprite;
- };
- return AtlasPictureInfo;
- }());
- BABYLON.AtlasPictureInfo = AtlasPictureInfo;
- /**
- * This if the Factory class containing static method to create Atlas Pictures Info objects or add new loaders
- */
- var AtlasPictureInfoFactory = (function () {
- function AtlasPictureInfoFactory() {
- }
- /**
- * Add a custom loader
- * @param fileExtension must be the file extension (without the dot) of the file that is loaded by this loader (e.g.: json)
- * @param plugin the instance of the loader
- */
- AtlasPictureInfoFactory.addLoader = function (fileExtension, plugin) {
- var a = AtlasPictureInfoFactory.plugins.getOrAddWithFactory(fileExtension.toLocaleLowerCase(), function () { return new Array(); });
- a.push(plugin);
- };
- /**
- * Load an Atlas Picture Info object from a data file at a given url and with a given texture
- * @param texture the texture containing the atlas bitmap
- * @param url the URL of the Atlas Info data file
- * @param onLoad a callback that will be called when the AtlasPictureInfo object will be loaded and ready
- * @param onError a callback that will be called in case of error
- */
- AtlasPictureInfoFactory.loadFromUrl = function (texture, url, onLoad, onError) {
- if (onError === void 0) { onError = null; }
- BABYLON.Tools.LoadFile(url, function (data) {
- var ext = url.split('.').pop().split(/\#|\?/)[0];
- var plugins = AtlasPictureInfoFactory.plugins.get(ext.toLocaleLowerCase());
- if (!plugins) {
- if (onError) {
- onError("couldn't find a plugin for this file extension", -1);
- }
- return;
- }
- for (var _i = 0, plugins_1 = plugins; _i < plugins_1.length; _i++) {
- var p = plugins_1[_i];
- var ret = p.loadFile(data);
- if (ret) {
- if (ret.api) {
- ret.api.texture = texture;
- if (onLoad) {
- onLoad(ret.api);
- }
- }
- else if (onError) {
- onError(ret.errorMsg, ret.errorCode);
- }
- return;
- }
- }
- if (onError) {
- onError("No plugin to load this Atlas Data file format", -1);
- }
- }, null, null, null, function () {
- if (onError) {
- onError("Couldn't load file", -1);
- }
- });
- return null;
- };
- return AtlasPictureInfoFactory;
- }());
- AtlasPictureInfoFactory.plugins = new BABYLON.StringDictionary();
- BABYLON.AtlasPictureInfoFactory = AtlasPictureInfoFactory;
- // Loader class for the TexturePacker's JSON Array data format
- var JSONArrayLoader = JSONArrayLoader_1 = (function () {
- function JSONArrayLoader() {
- }
- JSONArrayLoader.prototype.loadFile = function (content) {
- var errorMsg = null;
- var errorCode = 0;
- var root = null;
- var api = null;
- try {
- var frames_1;
- var meta = void 0;
- try {
- root = JSON.parse(content);
- frames_1 = root.frames;
- meta = root.meta;
- if (!frames_1 || !meta) {
- throw Error("Not a JSON Array file format");
- }
- }
- catch (ex1) {
- return null;
- }
- api = new AtlasPictureInfo();
- api.atlasSize = new BABYLON.Size(meta.size.w, meta.size.h);
- api.subPictures = new BABYLON.StringDictionary();
- for (var _i = 0, frames_2 = frames_1; _i < frames_2.length; _i++) {
- var f = frames_2[_i];
- var aspi = new AtlasSubPictureInfo();
- aspi.name = f.filename;
- aspi.location = new BABYLON.Vector2(f.frame.x, api.atlasSize.height - (f.frame.y + f.frame.h));
- aspi.size = new BABYLON.Size(f.frame.w, f.frame.h);
- api.subPictures.add(aspi.name, aspi);
- }
- }
- catch (ex2) {
- errorMsg = "Unknown Exception: " + ex2;
- errorCode = -2;
- }
- return { api: api, errorMsg: errorMsg, errorCode: errorCode };
- };
- return JSONArrayLoader;
- }());
- JSONArrayLoader = JSONArrayLoader_1 = __decorate([
- AtlasLoaderPlugin("json", new JSONArrayLoader_1())
- ], JSONArrayLoader);
- /**
- * Use this decorator when you declare an Atlas Loader Class for the loader to register itself automatically.
- * @param fileExtension the extension of the file that the plugin is loading (there can be many plugin for the same extension)
- * @param plugin an instance of the plugin class to add to the AtlasPictureInfoFactory
- */
- function AtlasLoaderPlugin(fileExtension, plugin) {
- return function () {
- AtlasPictureInfoFactory.addLoader(fileExtension, plugin);
- };
- }
- BABYLON.AtlasLoaderPlugin = AtlasLoaderPlugin;
- var JSONArrayLoader_1;
- })(BABYLON || (BABYLON = {}));
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var Text2DRenderCache = (function (_super) {
- __extends(Text2DRenderCache, _super);
- function Text2DRenderCache() {
- var _this = _super !== null && _super.apply(this, arguments) || this;
- _this.effectsReady = false;
- _this.vb = null;
- _this.ib = null;
- _this.instancingAttributes = null;
- _this.fontTexture = null;
- _this.effect = null;
- _this.effectInstanced = null;
- _this.fontPremulAlpha = false;
- return _this;
- }
- Text2DRenderCache.prototype.render = function (instanceInfo, context) {
- // Do nothing if the shader is still loading/preparing
- if (!this.effectsReady) {
- if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
- return false;
- }
- this.effectsReady = true;
- }
- var canvas = instanceInfo.owner.owner;
- var engine = canvas.engine;
- this.fontTexture.update();
- var effect = context.useInstancing ? this.effectInstanced : this.effect;
- engine.enableEffect(effect);
- effect.setTexture("diffuseSampler", this.fontTexture);
- engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
- var sdf = this.fontTexture.isSignedDistanceField;
- // Enable alpha mode only if the texture is not using SDF, SDF is rendered in AlphaTest mode, which mean no alpha blend
- var curAlphaMode;
- if (!sdf) {
- curAlphaMode = engine.getAlphaMode();
- engine.setAlphaMode(this.fontPremulAlpha ? BABYLON.Engine.ALPHA_PREMULTIPLIED : BABYLON.Engine.ALPHA_COMBINE, true);
- }
- var pid = context.groupInfoPartData[0];
- if (context.useInstancing) {
- if (!this.instancingAttributes) {
- this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
- }
- var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
- var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
- canvas._addDrawCallCount(1, context.renderMode);
- engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
- engine.draw(true, 0, 6, count);
- engine.unbindInstanceAttributes();
- }
- else {
- canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
- for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
- this.setupUniforms(effect, 0, pid._partData, i);
- engine.draw(true, 0, 6);
- }
- }
- if (!sdf) {
- engine.setAlphaMode(curAlphaMode, true);
- }
- return true;
- };
- Text2DRenderCache.prototype.dispose = function () {
- if (!_super.prototype.dispose.call(this)) {
- return false;
- }
- if (this.vb) {
- this._engine._releaseBuffer(this.vb);
- this.vb = null;
- }
- if (this.ib) {
- this._engine._releaseBuffer(this.ib);
- this.ib = null;
- }
- if (this.fontTexture) {
- this.fontTexture.decCachedFontTextureCounter();
- this.fontTexture = null;
- }
- this.effect = null;
- this.effectInstanced = null;
- return true;
- };
- return Text2DRenderCache;
- }(BABYLON.ModelRenderCache));
- BABYLON.Text2DRenderCache = Text2DRenderCache;
- var Text2DInstanceData = (function (_super) {
- __extends(Text2DInstanceData, _super);
- function Text2DInstanceData(partId, dataElementCount) {
- return _super.call(this, partId, dataElementCount) || this;
- }
- Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2DInstanceData.prototype, "color", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- return Text2DInstanceData;
- }(BABYLON.InstanceDataBase));
- __decorate([
- BABYLON.instanceData()
- ], Text2DInstanceData.prototype, "topLeftUV", null);
- __decorate([
- BABYLON.instanceData()
- ], Text2DInstanceData.prototype, "sizeUV", null);
- __decorate([
- BABYLON.instanceData()
- ], Text2DInstanceData.prototype, "textureSize", null);
- __decorate([
- BABYLON.instanceData()
- ], Text2DInstanceData.prototype, "color", null);
- __decorate([
- BABYLON.instanceData()
- ], Text2DInstanceData.prototype, "superSampleFactor", null);
- BABYLON.Text2DInstanceData = Text2DInstanceData;
- var Text2D = Text2D_1 = (function (_super) {
- __extends(Text2D, _super);
- /**
- * Create a Text primitive
- * @param text the text to display
- * @param settings a combination of settings, possible ones are
- * - 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)
- * - children: an array of direct children
- * - id a text identifier, for information purpose
- * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
- * - rotation: the initial rotation (in radian) of the primitive. default is 0
- * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
- * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
- * - alignToPixel: if true the primitive will be aligned to the target rendering device's pixel
- * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
- * - zOrder: override the zOrder with the specified value
- * - origin: define the normalized origin point location, default [0.5;0.5]
- * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
- * - 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.
- * - 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.
- * - bitmapFontTexture: set a BitmapFontTexture to use instead of a fontName.
- * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white.
- * - useBilinearFiltering: if true a FontTexture using Bilinear filtering will be used, if false a FontTexture using Nearest filtering will be used. If not specified then bilinear will be chosen for Signed Distance Field mode or a Text2D inside a WorldSpaceCanvas2D, otherwise nearest will be chose.
- * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
- * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
- * - isVisible: true if the text must be visible, false for hidden. Default is true.
- * - 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.
- * - 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.
- * - 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!
- * - 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.
- * - 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).
- * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
- * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
- * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
- * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
- * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
- * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
- * - textAlignmentH: align text horizontally (Text2D.AlignLeft, Text2D.AlignCenter, Text2D.AlignRight)
- * - textAlignmentV: align text vertically (Text2D.AlignTop, Text2D.AlignCenter, Text2D.AlignBottom)
- * - textAlignment: a string defining the text alignment, text can be: [<h:|horizontal:><left|right|center>], [<v:|vertical:><top|bottom|center>]
- * - wordWrap: if true the text will wrap inside content area
- */
- function Text2D(text, settings) {
- var _this = this;
- if (!settings) {
- settings = {};
- }
- _this = _super.call(this, settings) || this;
- if (settings.bitmapFontTexture != null) {
- _this._fontTexture = settings.bitmapFontTexture;
- _this._fontName = null;
- _this._fontSuperSample = false;
- _this._fontSDF = false;
- _this._textureIsPremulAlpha = _this._fontTexture.isPremultipliedAlpha;
- var ft = _this._fontTexture;
- if (ft != null && !ft.isReady()) {
- ft.onLoadObservable.add(function () {
- _this._positioningDirty();
- _this._setLayoutDirty();
- _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId; // To make sure the Text2D is issued again for render
- });
- }
- }
- else {
- _this._fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
- _this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
- _this._fontSDF = (settings.fontSignedDistanceField != null && settings.fontSignedDistanceField);
- }
- _this._defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor.clone();
- _this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
- _this._textureIsPremulAlpha = true; //settings.fontTexturePremulAlpha === true;
- _this._textSize = null;
- _this.text = text;
- if (settings.size != null) {
- _this.size = settings.size;
- _this._sizeSetByUser = true;
- }
- else {
- _this.size = null;
- }
- _this._useBilinearFiltering = (settings.useBilinearFiltering != null) ? settings.useBilinearFiltering : null;
- _this._fontBilinearFiltering = false;
- // Text rendering must always be aligned to the target's pixel to ensure a good quality
- _this.alignToPixel = true;
- _this.textAlignmentH = (settings.textAlignmentH == null) ? Text2D_1.AlignLeft : settings.textAlignmentH;
- _this.textAlignmentV = (settings.textAlignmentV == null) ? Text2D_1.AlignTop : settings.textAlignmentV;
- _this.textAlignment = (settings.textAlignment == null) ? "" : settings.textAlignment;
- _this._wordWrap = (settings.wordWrap == null) ? false : settings.wordWrap;
- _this._updateRenderMode();
- return _this;
- }
- Object.defineProperty(Text2D, "AlignLeft", {
- /**
- * Alignment is made relative to the left edge of the Content Area. Valid for horizontal alignment only.
- */
- get: function () { return Text2D_1._AlignLeft; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2D, "AlignTop", {
- /**
- * Alignment is made relative to the top edge of the Content Area. Valid for vertical alignment only.
- */
- get: function () { return Text2D_1._AlignTop; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2D, "AlignRight", {
- /**
- * Alignment is made relative to the right edge of the Content Area. Valid for horizontal alignment only.
- */
- get: function () { return Text2D_1._AlignRight; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2D, "AlignBottom", {
- /**
- * Alignment is made relative to the bottom edge of the Content Area. Valid for vertical alignment only.
- */
- get: function () { return Text2D_1._AlignBottom; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2D, "AlignCenter", {
- /**
- * Alignment is made to center the text from equal distance to the opposite edges of the Content Area
- */
- get: function () { return Text2D_1._AlignCenter; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2D.prototype, "fontName", {
- get: function () {
- return this._fontName;
- },
- set: function (value) {
- if (this._fontName) {
- throw new Error("Font Name change is not supported right now.");
- }
- this._fontName = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2D.prototype, "defaultFontColor", {
- get: function () {
- return this._defaultFontColor;
- },
- set: function (value) {
- if (!this._defaultFontColor) {
- this._defaultFontColor = value.clone();
- }
- else {
- this._defaultFontColor.copyFrom(value);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2D.prototype, "text", {
- get: function () {
- return this._text;
- },
- set: function (value) {
- if (!value) {
- value = "";
- }
- this._text = value;
- this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
- if (!this._sizeSetByUser) {
- this._size = null;
- this._actualSize = null;
- }
- this._updateCharCount();
- // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
- var s = this.textSize;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2D.prototype, "size", {
- get: function () {
- if (this._size != null) {
- return this._size;
- }
- return this.textSize;
- },
- set: function (value) {
- this.internalSetSize(value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2D.prototype, "fontSuperSample", {
- get: function () {
- return this._fontTexture && this._fontTexture.isSuperSampled;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2D.prototype, "fontSignedDistanceField", {
- get: function () {
- return this._fontTexture && this._fontTexture.isSignedDistanceField;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2D.prototype, "textureIsPremulAlpha", {
- get: function () {
- return this._textureIsPremulAlpha;
- },
- set: function (value) {
- this._textureIsPremulAlpha = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2D.prototype, "isSizeAuto", {
- get: function () {
- return false;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2D.prototype, "isVerticalSizeAuto", {
- get: function () {
- return false;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2D.prototype, "isHorizontalSizeAuto", {
- get: function () {
- return false;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Text2D.prototype, "textSize", {
- /**
- * Get the area that bounds the text associated to the primitive
- */
- get: function () {
- if (!this._textSize) {
- if (this.owner && this._text) {
- var ft = this.fontTexture;
- if (ft == null) {
- return Text2D_1.nullSize;
- }
- var newSize = ft.measureText(this._text, this._tabulationSize);
- if (!newSize.equals(this._textSize)) {
- this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
- this._positioningDirty();
- }
- this._textSize = newSize;
- }
- else {
- return Text2D_1.nullSize;
- }
- }
- return this._textSize;
- },
- enumerable: true,
- configurable: true
- });
- Text2D.prototype.onSetOwner = function () {
- if (!this._textSize) {
- this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
- this._setLayoutDirty();
- this._positioningDirty();
- this._actualSize = null;
- this._setFlags(BABYLON.SmartPropertyPrim.flagLevelBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
- }
- };
- Object.defineProperty(Text2D.prototype, "fontTexture", {
- get: function () {
- if (this._fontTexture) {
- return this._fontTexture;
- }
- if (this.fontName == null || this.owner == null || this.owner.scene == null) {
- return null;
- }
- this._fontBilinearFiltering = (this._useBilinearFiltering === null) ? (this.owner instanceof BABYLON.WorldSpaceCanvas2D) : this._useBilinearFiltering;
- this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample, this._fontSDF, this._fontBilinearFiltering);
- this._textureIsPremulAlpha = this._fontTexture.isPremultipliedAlpha;
- return this._fontTexture;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Dispose the primitive, remove it from its parent
- */
- Text2D.prototype.dispose = function () {
- if (!_super.prototype.dispose.call(this)) {
- return false;
- }
- if (this._fontTexture) {
- BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample, this._fontSDF, this._fontBilinearFiltering);
- this._fontTexture = null;
- }
- return true;
- };
- Text2D.prototype.updateLevelBoundingInfo = function () {
- if (!this.owner || !this._text) {
- return false;
- }
- var asize = this.actualSize;
- if (asize.width === 0 && asize.height === 0) {
- return false;
- }
- BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
- return true;
- };
- Object.defineProperty(Text2D.prototype, "textAlignment", {
- /**
- * You can get/set the text alignment through this property
- */
- get: function () {
- return this._textAlignment;
- },
- set: function (value) {
- this._textAlignment = value;
- this._setTextAlignmentfromString(value);
- },
- enumerable: true,
- configurable: true
- });
- Text2D.prototype.levelIntersect = function (intersectInfo) {
- // 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...
- return true;
- };
- Text2D.prototype.createModelRenderCache = function (modelKey) {
- var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
- return renderCache;
- };
- Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
- var renderCache = modelRenderCache;
- var engine = this.owner.engine;
- renderCache.fontTexture = this.fontTexture;
- renderCache.fontTexture.incCachedFontTextureCounter();
- renderCache.fontPremulAlpha = this.textureIsPremulAlpha;
- var vb = new Float32Array(4);
- for (var i = 0; i < 4; i++) {
- vb[i] = i;
- }
- renderCache.vb = engine.createVertexBuffer(vb);
- var ib = new Float32Array(6);
- ib[0] = 0;
- ib[1] = 2;
- ib[2] = 1;
- ib[3] = 0;
- ib[4] = 3;
- ib[5] = 2;
- renderCache.ib = engine.createIndexBuffer(ib);
- // 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
- var ei = this.getDataPartEffectInfo(Text2D_1.TEXT2D_MAINPARTID, ["index"], null, true);
- if (ei) {
- renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
- }
- ei = this.getDataPartEffectInfo(Text2D_1.TEXT2D_MAINPARTID, ["index"], null, false);
- renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
- return renderCache;
- };
- Text2D.prototype.createInstanceDataParts = function () {
- return [new Text2DInstanceData(Text2D_1.TEXT2D_MAINPARTID, this._charCount)];
- };
- // Looks like a hack!? Yes! Because that's what it is!
- // 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
- // 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)
- Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
- if (!this._charCount) {
- var curText = this._text;
- this.text = "A";
- return curText;
- }
- };
- // if obj contains something, we restore the _text property
- Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
- if (obj !== undefined) {
- this.text = obj;
- }
- };
- Text2D.prototype.getUsedShaderCategories = function (dataPart) {
- var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
- if (this._fontSDF) {
- cat.push(Text2D_1.TEXT2D_CATEGORY_SDF);
- }
- if (this._fontTexture instanceof BABYLON.FontTexture) {
- cat.push(Text2D_1.TEXT2D_CATEGORY_FONTTEXTURE);
- }
- return cat;
- };
- Text2D.prototype.refreshInstanceDataPart = function (part) {
- if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
- return false;
- }
- if (part.id === Text2D_1.TEXT2D_MAINPARTID) {
- var d = part;
- var ft = this.fontTexture;
- var texture = ft;
- if (!texture) {
- return false;
- }
- var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
- var ts = texture.getSize();
- var offset = BABYLON.Vector2.Zero();
- var lh = ft.lineHeight;
- d.dataElementCount = this._charCount;
- d.curElement = 0;
- var lineLengths = [];
- var charWidths = [];
- var charsPerLine = [];
- var numCharsCurrenLine = 0;
- var contentAreaWidth = this.contentArea.width;
- var contentAreaHeight = this.contentArea.height;
- var numCharsCurrentWord = 0;
- var widthCurrentWord = 0;
- var numWordsPerLine = 0;
- var text = this.text;
- var tabWidth = this._tabulationSize * texture.spaceWidth;
- // First pass: analyze the text to build data like pixel length of each lines, width of each char, number of char per line
- for (var i_1 = 0; i_1 < text.length; i_1++) {
- var char = text[i_1];
- numCharsCurrenLine++;
- charWidths[i_1] = 0;
- // Line feed
- if (this._isWhiteSpaceCharVert(char)) {
- lineLengths.push(offset.x);
- charsPerLine.push(numCharsCurrenLine - 1);
- numCharsCurrenLine = 1;
- offset.x = 0;
- if (widthCurrentWord > 0) {
- numWordsPerLine++;
- }
- numWordsPerLine = 0;
- numCharsCurrentWord = 0;
- widthCurrentWord = 0;
- continue;
- }
- var ci = texture.getChar(char);
- var charWidth = 0;
- if (char === "\t") {
- charWidth = tabWidth;
- }
- else {
- charWidth = ci.xAdvance;
- }
- offset.x += charWidth;
- charWidths[i_1] = charWidth;
- if (this._isWhiteSpaceCharHoriz(char)) {
- if (widthCurrentWord > 0) {
- numWordsPerLine++;
- }
- numCharsCurrentWord = 0;
- widthCurrentWord = 0;
- }
- else {
- widthCurrentWord += ci.xAdvance;
- numCharsCurrentWord++;
- }
- if (this._wordWrap && numWordsPerLine > 0 && offset.x > contentAreaWidth) {
- lineLengths.push(offset.x - widthCurrentWord);
- numCharsCurrenLine -= numCharsCurrentWord;
- var j = i_1 - numCharsCurrentWord;
- //skip white space at the end of this line
- while (this._isWhiteSpaceCharHoriz(text[j])) {
- lineLengths[lineLengths.length - 1] -= charWidths[j];
- j--;
- }
- charsPerLine.push(numCharsCurrenLine);
- if (this._isWhiteSpaceCharHoriz(text[i_1])) {
- //skip white space at the beginning of next line
- var numSpaces = 0;
- while (this._isWhiteSpaceCharHoriz(text[i_1 + numSpaces])) {
- numSpaces++;
- charWidths[i_1 + numSpaces] = 0;
- }
- i_1 += numSpaces - 1;
- offset.x = 0;
- numCharsCurrenLine = numSpaces - 1;
- }
- else {
- numCharsCurrenLine = numCharsCurrentWord;
- offset.x = widthCurrentWord;
- }
- numWordsPerLine = 0;
- }
- }
- lineLengths.push(offset.x);
- charsPerLine.push(numCharsCurrenLine);
- //skip white space at the end
- var i = text.length - 1;
- while (this._isWhiteSpaceCharHoriz(text[i])) {
- lineLengths[lineLengths.length - 1] -= charWidths[i];
- i--;
- }
- var charNum = 0;
- var maxLineLen = 0;
- var alignH = this.textAlignmentH;
- var alignV = this.textAlignmentV;
- offset.x = 0;
- if (alignH == Text2D_1.AlignRight || alignH == Text2D_1.AlignCenter) {
- for (var i_2 = 0; i_2 < lineLengths.length; i_2++) {
- if (lineLengths[i_2] > maxLineLen) {
- maxLineLen = lineLengths[i_2];
- }
- }
- }
- var textHeight = lineLengths.length * lh;
- var offsetX = this.padding.leftPixels;
- if (alignH == Text2D_1.AlignRight) {
- offsetX += contentAreaWidth - maxLineLen;
- }
- else if (alignH == Text2D_1.AlignCenter) {
- offsetX += (contentAreaWidth - maxLineLen) * .5;
- }
- offset.x += Math.floor(offsetX);
- offset.y += contentAreaHeight + textHeight - lh;
- offset.y += this.padding.bottomPixels;
- if (alignV == Text2D_1.AlignBottom) {
- offset.y -= contentAreaHeight;
- }
- else if (alignV == Text2D_1.AlignCenter) {
- offset.y -= (contentAreaHeight - textHeight) * .5 + lineLengths.length * lh;
- }
- else {
- offset.y -= lineLengths.length * lh;
- }
- var lineHeight = texture.lineHeight;
- for (var i_3 = 0; i_3 < lineLengths.length; i_3++) {
- var numChars = charsPerLine[i_3];
- var lineLength = lineLengths[i_3];
- if (alignH == Text2D_1.AlignRight) {
- offset.x += maxLineLen - lineLength;
- }
- else if (alignH == Text2D_1.AlignCenter) {
- offset.x += (maxLineLen - lineLength) * .5;
- }
- for (var j = 0; j < numChars; j++) {
- var char = text[charNum];
- var charWidth = charWidths[charNum];
- if (char !== "\t" && !this._isWhiteSpaceCharVert(char)) {
- //make sure space char gets processed here or overlapping can occur when text is set
- var ci = texture.getChar(char);
- var partOffset = new BABYLON.Vector2(Math.floor(offset.x + ci.xOffset), Math.floor(offset.y + ci.yOffset));
- this.updateInstanceDataPart(d, partOffset);
- d.topLeftUV = ci.topLeftUV;
- var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
- d.sizeUV = suv;
- d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
- d.color = this.defaultFontColor;
- d.superSampleFactor = superSampleFactor;
- //console.log(`Char: ${char}, Offset: ${partOffset}`);
- ++d.curElement;
- }
- offset.x += Math.floor(charWidth);
- charNum++;
- }
- offset.x = offsetX;
- offset.y -= lineHeight;
- }
- }
- return true;
- };
- Text2D.prototype._isWhiteSpaceCharHoriz = function (char) {
- if (char === " " || char === "\t") {
- return true;
- }
- };
- Text2D.prototype._isWhiteSpaceCharVert = function (char) {
- if (char === "\n" || char === "\r") {
- return true;
- }
- };
- Text2D.prototype._updateCharCount = function () {
- var count = 0;
- for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
- var char = _a[_i];
- if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
- continue;
- }
- ++count;
- }
- this._charCount = count;
- };
- Text2D.prototype._setTextAlignmentfromString = function (value) {
- var m = value.trim().split(",");
- for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
- var v = m_1[_i];
- v = v.toLocaleLowerCase().trim();
- // Horizontal
- var i = v.indexOf("h:");
- if (i === -1) {
- i = v.indexOf("horizontal:");
- }
- if (i !== -1) {
- v = v.substr(v.indexOf(":") + 1);
- this._setTextAlignmentHorizontal(v);
- continue;
- }
- // Vertical
- i = v.indexOf("v:");
- if (i === -1) {
- i = v.indexOf("vertical:");
- }
- if (i !== -1) {
- v = v.substr(v.indexOf(":") + 1);
- this._setTextAlignmentVertical(v);
- continue;
- }
- }
- };
- Text2D.prototype._setTextAlignmentHorizontal = function (text) {
- var v = text.trim().toLocaleLowerCase();
- switch (v) {
- case "left":
- this.textAlignmentH = Text2D_1.AlignLeft;
- return;
- case "right":
- this.textAlignmentH = Text2D_1.AlignRight;
- return;
- case "center":
- this.textAlignmentH = Text2D_1.AlignCenter;
- return;
- }
- };
- Text2D.prototype._setTextAlignmentVertical = function (text) {
- var v = text.trim().toLocaleLowerCase();
- switch (v) {
- case "top":
- this.textAlignmentV = Text2D_1.AlignTop;
- return;
- case "bottom":
- this.textAlignmentV = Text2D_1.AlignBottom;
- return;
- case "center":
- this.textAlignmentV = Text2D_1.AlignCenter;
- return;
- }
- };
- Text2D.prototype._useTextureAlpha = function () {
- return this._fontSDF;
- };
- Text2D.prototype._shouldUseAlphaFromTexture = function () {
- return !this._fontSDF;
- };
- return Text2D;
- }(BABYLON.RenderablePrim2D));
- Text2D.TEXT2D_MAINPARTID = 1;
- Text2D.TEXT2D_CATEGORY_SDF = "SignedDistanceField";
- Text2D.TEXT2D_CATEGORY_FONTTEXTURE = "FontTexture";
- Text2D._AlignLeft = 1;
- Text2D._AlignTop = 1; // Same as left
- Text2D._AlignRight = 2;
- Text2D._AlignBottom = 2; // Same as right
- Text2D._AlignCenter = 3;
- __decorate([
- BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D_1.fontProperty = pi; }, false, true)
- /**
- * Get/set the font name to use, using HTML CSS notation.
- * Set is not supported right now.
- */
- ], Text2D.prototype, "fontName", null);
- __decorate([
- BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D_1.defaultFontColorProperty = pi; })
- /**
- * Get/set the font default color
- */
- ], Text2D.prototype, "defaultFontColor", null);
- __decorate([
- BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D_1.textProperty = pi; }, false, true)
- /**
- * Get/set the text to render.
- * \n \t character are supported.
- */
- ], Text2D.prototype, "text", null);
- __decorate([
- BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D_1.sizeProperty = pi; })
- /**
- * Get/set the size of the area where the text is drawn.
- * You should not set this size, the default behavior compute the size based on the actual text.
- */
- ], Text2D.prototype, "size", null);
- __decorate([
- BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Text2D_1.fontSuperSampleProperty = pi; }, false, false)
- /**
- * Get/set the font name to use, using HTML CSS notation.
- * Set is not supported right now.
- */
- ], Text2D.prototype, "fontSuperSample", null);
- __decorate([
- BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Text2D_1.fontSignedDistanceFieldProperty = pi; }, false, false)
- /**
- * Get/set the font name to use, using HTML CSS notation.
- * Set is not supported right now.
- */
- ], Text2D.prototype, "fontSignedDistanceField", null);
- __decorate([
- BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Text2D_1.textureIsPremulAlphaProperty = pi; })
- /**
- * Set to true if the FontTexture use Premultiplied Alpha, default is false
- */
- ], Text2D.prototype, "textureIsPremulAlpha", null);
- __decorate([
- BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 8, function (pi) { return Text2D_1.fontTextureProperty = pi; })
- ], Text2D.prototype, "fontTexture", null);
- Text2D = Text2D_1 = __decorate([
- BABYLON.className("Text2D", "BABYLON")
- /**
- * Primitive that render text using a specific font
- */
- ], Text2D);
- BABYLON.Text2D = Text2D;
- var Text2D_1;
- })(BABYLON || (BABYLON = {}));
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var Lines2DRenderCache = (function (_super) {
- __extends(Lines2DRenderCache, _super);
- function Lines2DRenderCache(engine, modelKey) {
- var _this = _super.call(this, engine, modelKey) || this;
- _this.effectsReady = false;
- _this.fillVB = null;
- _this.fillIB = null;
- _this.fillIndicesCount = 0;
- _this.instancingFillAttributes = null;
- _this.effectFill = null;
- _this.effectFillInstanced = null;
- _this.borderVB = null;
- _this.borderIB = null;
- _this.borderIndicesCount = 0;
- _this.instancingBorderAttributes = null;
- _this.effectBorder = null;
- _this.effectBorderInstanced = null;
- return _this;
- }
- Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
- // Do nothing if the shader is still loading/preparing
- if (!this.effectsReady) {
- if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
- (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
- return false;
- }
- this.effectsReady = true;
- }
- var canvas = instanceInfo.owner.owner;
- var engine = canvas.engine;
- engine.setState(false, undefined, true);
- var depthFunction = 0;
- if (this.effectFill && this.effectBorder) {
- depthFunction = engine.getDepthFunction();
- engine.setDepthFunctionToLessOrEqual();
- }
- var curAlphaMode = engine.getAlphaMode();
- if (this.effectFill) {
- var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
- var pid = context.groupInfoPartData[partIndex];
- if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
- engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
- }
- var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
- engine.enableEffect(effect);
- engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
- if (context.useInstancing) {
- if (!this.instancingFillAttributes) {
- this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
- }
- var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
- var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
- canvas._addDrawCallCount(1, context.renderMode);
- engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
- engine.draw(true, 0, this.fillIndicesCount, count);
- engine.unbindInstanceAttributes();
- }
- else {
- canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
- for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
- this.setupUniforms(effect, partIndex, pid._partData, i);
- engine.draw(true, 0, this.fillIndicesCount);
- }
- }
- }
- if (this.effectBorder) {
- var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
- var pid = context.groupInfoPartData[partIndex];
- if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
- engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
- }
- var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
- engine.enableEffect(effect);
- engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
- if (context.useInstancing) {
- if (!this.instancingBorderAttributes) {
- this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
- }
- var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
- var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
- canvas._addDrawCallCount(1, context.renderMode);
- engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
- engine.draw(true, 0, this.borderIndicesCount, count);
- engine.unbindInstanceAttributes();
- }
- else {
- canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
- for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
- this.setupUniforms(effect, partIndex, pid._partData, i);
- engine.draw(true, 0, this.borderIndicesCount);
- }
- }
- }
- engine.setAlphaMode(curAlphaMode, true);
- if (this.effectFill && this.effectBorder) {
- engine.setDepthFunction(depthFunction);
- }
- return true;
- };
- Lines2DRenderCache.prototype.dispose = function () {
- if (!_super.prototype.dispose.call(this)) {
- return false;
- }
- if (this.fillVB) {
- this._engine._releaseBuffer(this.fillVB);
- this.fillVB = null;
- }
- if (this.fillIB) {
- this._engine._releaseBuffer(this.fillIB);
- this.fillIB = null;
- }
- this.effectFill = null;
- this.effectFillInstanced = null;
- this.effectBorder = null;
- this.effectBorderInstanced = null;
- if (this.borderVB) {
- this._engine._releaseBuffer(this.borderVB);
- this.borderVB = null;
- }
- if (this.borderIB) {
- this._engine._releaseBuffer(this.borderIB);
- this.borderIB = null;
- }
- return true;
- };
- return Lines2DRenderCache;
- }(BABYLON.ModelRenderCache));
- BABYLON.Lines2DRenderCache = Lines2DRenderCache;
- var Lines2DInstanceData = (function (_super) {
- __extends(Lines2DInstanceData, _super);
- function Lines2DInstanceData(partId) {
- return _super.call(this, partId, 1) || this;
- }
- Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
- get: function () {
- return null;
- },
- set: function (value) {
- },
- enumerable: true,
- configurable: true
- });
- return Lines2DInstanceData;
- }(BABYLON.Shape2DInstanceData));
- __decorate([
- BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
- ], Lines2DInstanceData.prototype, "boundingMin", null);
- __decorate([
- BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
- ], Lines2DInstanceData.prototype, "boundingMax", null);
- BABYLON.Lines2DInstanceData = Lines2DInstanceData;
- var Lines2D = Lines2D_1 = (function (_super) {
- __extends(Lines2D, _super);
- /**
- * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
- * @param points an array that describe the points to use to draw the line, must contain at least two entries.
- * @param settings a combination of settings, possible ones are
- * - 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)
- * - children: an array of direct children
- * - id a text identifier, for information purpose
- * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
- * - rotation: the initial rotation (in radian) of the primitive. default is 0
- * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
- * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
- * - alignToPixel: if true the primitive will be aligned to the target rendering device's pixel
- * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
- * - zOrder: override the zOrder with the specified value
- * - origin: define the normalized origin point location, default [0.5;0.5]
- * - 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.
- * - 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.
- * - 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.
- * - 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.
- * - 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)
- * - 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)
- * - borderThickness: the thickness of the drawn border, default is 1.
- * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
- * - 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.
- * - 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.
- * - 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!
- * - 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.
- * - 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).
- * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
- * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
- * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
- * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
- * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
- * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
- */
- function Lines2D(points, settings) {
- var _this = this;
- if (!settings) {
- settings = {};
- }
- _this = _super.call(this, settings) || this;
- _this._fillVB = null;
- _this._fillIB = null;
- _this._borderVB = null;
- _this._borderIB = null;
- _this._boundingMin = null;
- _this._boundingMax = null;
- var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
- var startCap = (settings.startCap == null) ? 0 : settings.startCap;
- var endCap = (settings.endCap == null) ? 0 : settings.endCap;
- var closed = (settings.closed == null) ? false : settings.closed;
- _this.points = points;
- _this.fillThickness = fillThickness;
- _this.startCap = startCap;
- _this.endCap = endCap;
- _this.closed = closed;
- return _this;
- }
- Object.defineProperty(Lines2D, "NoCap", {
- /**
- * No Cap to apply on the extremity
- */
- get: function () { return Lines2D_1._noCap; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Lines2D, "RoundCap", {
- /**
- * A round cap, will use the line thickness as diameter
- */
- get: function () { return Lines2D_1._roundCap; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Lines2D, "TriangleCap", {
- /**
- * Creates a triangle at the extremity.
- */
- get: function () { return Lines2D_1._triangleCap; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Lines2D, "SquareAnchorCap", {
- /**
- * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
- */
- get: function () { return Lines2D_1._squareAnchorCap; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Lines2D, "RoundAnchorCap", {
- /**
- * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
- */
- get: function () { return Lines2D_1._roundAnchorCap; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Lines2D, "DiamondAnchorCap", {
- /**
- * Creates a diamond anchor at the extremity.
- */
- get: function () { return Lines2D_1._diamondAnchorCap; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Lines2D, "ArrowCap", {
- /**
- * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
- */
- get: function () { return Lines2D_1._arrowCap; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Lines2D.prototype, "points", {
- get: function () {
- return this._points;
- },
- set: function (value) {
- this._points = value;
- this._primTriArrayDirty = true;
- this._boundingBoxDirty();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Lines2D.prototype, "fillThickness", {
- get: function () {
- return this._fillThickness;
- },
- set: function (value) {
- this._fillThickness = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Lines2D.prototype, "closed", {
- get: function () {
- return this._closed;
- },
- set: function (value) {
- this._closed = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Lines2D.prototype, "startCap", {
- get: function () {
- return this._startCap;
- },
- set: function (value) {
- this._startCap = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Lines2D.prototype, "endCap", {
- get: function () {
- return this._endCap;
- },
- set: function (value) {
- this._endCap = value;
- },
- enumerable: true,
- configurable: true
- });
- Lines2D.prototype.levelIntersect = function (intersectInfo) {
- var p = intersectInfo._localPickPosition;
- this.updateTriArray();
- return this._primTriArray.doesContain(p);
- };
- Object.defineProperty(Lines2D.prototype, "boundingMin", {
- get: function () {
- if (!this._boundingMin) {
- this._computeLines2D();
- }
- return this._boundingMin;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Lines2D.prototype, "boundingMax", {
- get: function () {
- if (!this._boundingMax) {
- this._computeLines2D();
- }
- return this._boundingMax;
- },
- enumerable: true,
- configurable: true
- });
- Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
- var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
- // Remove the BORDER category, we don't use it in the VertexShader
- var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
- if (i !== -1) {
- res.splice(i, 1);
- }
- return res;
- };
- Lines2D.prototype.updateLevelBoundingInfo = function () {
- if (!this._boundingMin) {
- this._computeLines2D();
- }
- BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
- return true;
- };
- Lines2D.prototype.createModelRenderCache = function (modelKey) {
- var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
- return renderCache;
- };
- ///////////////////////////////////////////////////////////////////////////////////
- // Methods for Lines building
- Lines2D.prototype._perp = function (v, res) {
- res.x = v.y;
- res.y = -v.x;
- };
- ;
- Lines2D.prototype._direction = function (a, b, res) {
- a.subtractToRef(b, res);
- res.normalize();
- };
- Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
- a.addToRef(b, tangent);
- tangent.normalize();
- miter.x = -tangent.y;
- miter.y = tangent.x;
- Lines2D_1._miterTps.x = -a.y;
- Lines2D_1._miterTps.y = a.x;
- return 1 / BABYLON.Vector2.Dot(miter, Lines2D_1._miterTps);
- };
- Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
- var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
- if (d === 0)
- return false;
- var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
- //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
- if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
- return false;
- if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
- return false;
- return true;
- };
- Lines2D.prototype._updateMinMax = function (array, offset) {
- if (offset >= array.length) {
- return;
- }
- this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
- this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
- this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
- this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
- };
- Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
- var borderMode = borderThickness != null && !isNaN(borderThickness);
- var off = index * (borderMode ? 8 : 4);
- // 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)
- if (off >= array.length) {
- return;
- }
- // Store start/end normal, we need it for the cap construction
- if (index === 0) {
- this._perp(n, Lines2D_1._startDir);
- }
- else if (index === max - 1) {
- this._perp(n, Lines2D_1._endDir);
- Lines2D_1._endDir.x *= -1;
- Lines2D_1._endDir.y *= -1;
- }
- var swap = false;
- array[off + 0] = p.x + n.x * halfThickness;
- array[off + 1] = p.y + n.y * halfThickness;
- array[off + 2] = p.x + n.x * -halfThickness;
- array[off + 3] = p.y + n.y * -halfThickness;
- this._updateMinMax(array, off);
- this._updateMinMax(array, off + 2);
- // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
- // 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
- if (detectFlip != 0) {
- // Flip if intersect
- var flipOff = detectFlip * (borderMode ? 8 : 4);
- 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])) {
- swap = true;
- var tps = array[off + 0];
- array[off + 0] = array[off + 2];
- array[off + 2] = tps;
- tps = array[off + 1];
- array[off + 1] = array[off + 3];
- array[off + 3] = tps;
- }
- }
- if (borderMode) {
- var t = halfThickness + borderThickness;
- array[off + 4] = p.x + n.x * (swap ? -t : t);
- array[off + 5] = p.y + n.y * (swap ? -t : t);
- array[off + 6] = p.x + n.x * (swap ? t : -t);
- array[off + 7] = p.y + n.y * (swap ? t : -t);
- this._updateMinMax(array, off + 4);
- this._updateMinMax(array, off + 6);
- }
- if (contour) {
- off += borderMode ? 4 : 0;
- contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
- contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
- }
- };
- Lines2D.prototype._getCapSize = function (type, border) {
- if (border === void 0) { border = false; }
- var sd = Lines2D_1._roundCapSubDiv;
- // If no array given, we call this to get the size
- var vbsize = 0, ibsize = 0;
- switch (type) {
- case Lines2D_1.NoCap:
- {
- // If the line is not close and we're computing border, we add the size to generate the edge border
- if (!this.closed && border) {
- vbsize = 4;
- ibsize = 6;
- }
- else {
- vbsize = ibsize = 0;
- }
- break;
- }
- case Lines2D_1.RoundCap:
- {
- if (border) {
- vbsize = sd;
- ibsize = (sd - 2) * 3;
- }
- else {
- vbsize = (sd / 2) + 1;
- ibsize = (sd / 2) * 3;
- }
- break;
- }
- case Lines2D_1.ArrowCap:
- {
- if (border) {
- vbsize = 12;
- ibsize = 24;
- }
- else {
- vbsize = 3;
- ibsize = 3;
- }
- break;
- }
- case Lines2D_1.TriangleCap:
- {
- if (border) {
- vbsize = 6;
- ibsize = 12;
- }
- else {
- vbsize = 3;
- ibsize = 3;
- }
- break;
- }
- case Lines2D_1.DiamondAnchorCap:
- {
- if (border) {
- vbsize = 10;
- ibsize = 24;
- }
- else {
- vbsize = 5;
- ibsize = 9;
- }
- break;
- }
- case Lines2D_1.SquareAnchorCap:
- {
- if (border) {
- vbsize = 12;
- ibsize = 30;
- }
- else {
- vbsize = 4;
- ibsize = 6;
- }
- break;
- }
- case Lines2D_1.RoundAnchorCap:
- {
- if (border) {
- vbsize = sd * 2;
- ibsize = (sd - 1) * 6;
- }
- else {
- vbsize = sd + 1;
- ibsize = (sd + 1) * 3;
- }
- break;
- }
- }
- return { vbsize: vbsize * 2, ibsize: ibsize };
- };
- Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
- var c = Math.cos(rotation);
- var s = Math.sin(rotation);
- Lines2D_1._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
- Lines2D_1._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
- var offset = baseOffset + (index * 2);
- vb[offset + 0] = Lines2D_1._tpsV.x;
- vb[offset + 1] = Lines2D_1._tpsV.y;
- if (contour) {
- contour.push(Lines2D_1._tpsV.x);
- contour.push(Lines2D_1._tpsV.y);
- }
- this._updateMinMax(vb, offset);
- return (baseOffset + index * 2) / 2;
- };
- Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
- ib[baseOffset + index] = vertexIndex;
- };
- Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
- // 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
- var sd = Lines2D_1._roundCapSubDiv;
- var dir = new BABYLON.Vector2(1, 0);
- var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
- var ht = thickness / 2;
- var t = thickness;
- var borderMode = borderThickness != null;
- var bt = borderThickness;
- switch (type) {
- case Lines2D_1.NoCap:
- if (borderMode && !this.closed) {
- var vi = 0;
- var ii = 0;
- var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
- var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
- var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
- var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
- this._storeIndex(ib, ibi, ii++, v1);
- this._storeIndex(ib, ibi, ii++, v2);
- this._storeIndex(ib, ibi, ii++, v3);
- this._storeIndex(ib, ibi, ii++, v1);
- this._storeIndex(ib, ibi, ii++, v3);
- this._storeIndex(ib, ibi, ii++, v4);
- }
- break;
- case Lines2D_1.ArrowCap:
- ht *= 2;
- case Lines2D_1.TriangleCap:
- {
- if (borderMode) {
- var f = type === Lines2D_1.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
- var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
- var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
- var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
- var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
- var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
- var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
- var ii = 0;
- this._storeIndex(ib, ibi, ii++, v1);
- this._storeIndex(ib, ibi, ii++, v4);
- this._storeIndex(ib, ibi, ii++, v5);
- this._storeIndex(ib, ibi, ii++, v1);
- this._storeIndex(ib, ibi, ii++, v5);
- this._storeIndex(ib, ibi, ii++, v2);
- this._storeIndex(ib, ibi, ii++, v6);
- this._storeIndex(ib, ibi, ii++, v3);
- this._storeIndex(ib, ibi, ii++, v2);
- this._storeIndex(ib, ibi, ii++, v6);
- this._storeIndex(ib, ibi, ii++, v2);
- this._storeIndex(ib, ibi, ii++, v5);
- if (type === Lines2D_1.ArrowCap) {
- var rht = thickness / 2;
- var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
- var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
- var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
- var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
- var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
- var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
- this._storeIndex(ib, ibi, ii++, v7);
- this._storeIndex(ib, ibi, ii++, v8);
- this._storeIndex(ib, ibi, ii++, v9);
- this._storeIndex(ib, ibi, ii++, v7);
- this._storeIndex(ib, ibi, ii++, v9);
- this._storeIndex(ib, ibi, ii++, v4);
- this._storeIndex(ib, ibi, ii++, v10);
- this._storeIndex(ib, ibi, ii++, v12);
- this._storeIndex(ib, ibi, ii++, v11);
- this._storeIndex(ib, ibi, ii++, v10);
- this._storeIndex(ib, ibi, ii++, v6);
- this._storeIndex(ib, ibi, ii++, v12);
- }
- }
- else {
- var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
- var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
- var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
- this._storeIndex(ib, ibi, 0, v1);
- this._storeIndex(ib, ibi, 1, v2);
- this._storeIndex(ib, ibi, 2, v3);
- }
- break;
- }
- case Lines2D_1.RoundCap:
- {
- if (borderMode) {
- var curA = -Math.PI / 2;
- var incA = Math.PI / (sd / 2 - 1);
- var ii = 0;
- for (var i = 0; i < (sd / 2); i++) {
- var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
- 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);
- if (i > 0) {
- this._storeIndex(ib, ibi, ii++, v1 - 2);
- this._storeIndex(ib, ibi, ii++, v2 - 2);
- this._storeIndex(ib, ibi, ii++, v2);
- this._storeIndex(ib, ibi, ii++, v1 - 2);
- this._storeIndex(ib, ibi, ii++, v2);
- this._storeIndex(ib, ibi, ii++, v1);
- }
- curA += incA;
- }
- }
- else {
- var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
- var curA = -Math.PI / 2;
- var incA = Math.PI / (sd / 2 - 1);
- this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
- curA += incA;
- for (var i = 1; i < (sd / 2); i++) {
- var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
- this._storeIndex(ib, ibi, i * 3 + 0, c);
- this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
- this._storeIndex(ib, ibi, i * 3 + 2, v2);
- curA += incA;
- }
- }
- break;
- }
- case Lines2D_1.SquareAnchorCap:
- {
- var vi = 0;
- var c = borderMode ? null : contour;
- var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
- var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
- var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
- var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
- if (borderMode) {
- var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
- var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
- var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
- var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
- var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
- var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
- var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
- var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
- var ii = 0;
- this._storeIndex(ib, ibi, ii++, v6);
- this._storeIndex(ib, ibi, ii++, v1);
- this._storeIndex(ib, ibi, ii++, v5);
- this._storeIndex(ib, ibi, ii++, v6);
- this._storeIndex(ib, ibi, ii++, v7);
- this._storeIndex(ib, ibi, ii++, v1);
- this._storeIndex(ib, ibi, ii++, v1);
- this._storeIndex(ib, ibi, ii++, v7);
- this._storeIndex(ib, ibi, ii++, v8);
- this._storeIndex(ib, ibi, ii++, v1);
- this._storeIndex(ib, ibi, ii++, v8);
- this._storeIndex(ib, ibi, ii++, v2);
- this._storeIndex(ib, ibi, ii++, v2);
- this._storeIndex(ib, ibi, ii++, v8);
- this._storeIndex(ib, ibi, ii++, v9);
- this._storeIndex(ib, ibi, ii++, v2);
- this._storeIndex(ib, ibi, ii++, v9);
- this._storeIndex(ib, ibi, ii++, v3);
- this._storeIndex(ib, ibi, ii++, v3);
- this._storeIndex(ib, ibi, ii++, v9);
- this._storeIndex(ib, ibi, ii++, v10);
- this._storeIndex(ib, ibi, ii++, v3);
- this._storeIndex(ib, ibi, ii++, v10);
- this._storeIndex(ib, ibi, ii++, v4);
- this._storeIndex(ib, ibi, ii++, v10);
- this._storeIndex(ib, ibi, ii++, v11);
- this._storeIndex(ib, ibi, ii++, v4);
- this._storeIndex(ib, ibi, ii++, v11);
- this._storeIndex(ib, ibi, ii++, v12);
- this._storeIndex(ib, ibi, ii++, v4);
- }
- else {
- this._storeIndex(ib, ibi, 0, v1);
- this._storeIndex(ib, ibi, 1, v2);
- this._storeIndex(ib, ibi, 2, v3);
- this._storeIndex(ib, ibi, 3, v1);
- this._storeIndex(ib, ibi, 4, v3);
- this._storeIndex(ib, ibi, 5, v4);
- }
- break;
- }
- case Lines2D_1.RoundAnchorCap:
- {
- var cpos = Math.sqrt(t * t - ht * ht);
- var center = new BABYLON.Vector2(cpos, 0);
- var curA = BABYLON.Tools.ToRadians(-150);
- var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
- if (borderMode) {
- var ii = 0;
- for (var i = 0; i < sd; i++) {
- var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
- 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);
- if (i > 0) {
- this._storeIndex(ib, ibi, ii++, v1 - 2);
- this._storeIndex(ib, ibi, ii++, v2 - 2);
- this._storeIndex(ib, ibi, ii++, v2);
- this._storeIndex(ib, ibi, ii++, v1 - 2);
- this._storeIndex(ib, ibi, ii++, v2);
- this._storeIndex(ib, ibi, ii++, v1);
- }
- curA += incA;
- }
- }
- else {
- var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
- this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
- curA += incA;
- for (var i = 1; i < sd; i++) {
- var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
- this._storeIndex(ib, ibi, i * 3 + 0, c);
- this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
- this._storeIndex(ib, ibi, i * 3 + 2, v2);
- curA += incA;
- }
- this._storeIndex(ib, ibi, sd * 3 + 0, c);
- this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
- this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
- }
- break;
- }
- case Lines2D_1.DiamondAnchorCap:
- {
- var vi = 0;
- var c = borderMode ? null : contour;
- var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
- var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
- var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
- var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
- var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
- if (borderMode) {
- var f = Math.sqrt(bt * bt * 2);
- var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
- var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
- var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
- var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
- var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
- var ii = 0;
- this._storeIndex(ib, ibi, ii++, v6);
- this._storeIndex(ib, ibi, ii++, v7);
- this._storeIndex(ib, ibi, ii++, v1);
- this._storeIndex(ib, ibi, ii++, v1);
- this._storeIndex(ib, ibi, ii++, v7);
- this._storeIndex(ib, ibi, ii++, v2);
- this._storeIndex(ib, ibi, ii++, v2);
- this._storeIndex(ib, ibi, ii++, v7);
- this._storeIndex(ib, ibi, ii++, v8);
- this._storeIndex(ib, ibi, ii++, v2);
- this._storeIndex(ib, ibi, ii++, v8);
- this._storeIndex(ib, ibi, ii++, v3);
- this._storeIndex(ib, ibi, ii++, v3);
- this._storeIndex(ib, ibi, ii++, v8);
- this._storeIndex(ib, ibi, ii++, v9);
- this._storeIndex(ib, ibi, ii++, v3);
- this._storeIndex(ib, ibi, ii++, v9);
- this._storeIndex(ib, ibi, ii++, v4);
- this._storeIndex(ib, ibi, ii++, v4);
- this._storeIndex(ib, ibi, ii++, v9);
- this._storeIndex(ib, ibi, ii++, v10);
- this._storeIndex(ib, ibi, ii++, v4);
- this._storeIndex(ib, ibi, ii++, v10);
- this._storeIndex(ib, ibi, ii++, v5);
- }
- else {
- this._storeIndex(ib, ibi, 0, v1);
- this._storeIndex(ib, ibi, 1, v2);
- this._storeIndex(ib, ibi, 2, v3);
- this._storeIndex(ib, ibi, 3, v1);
- this._storeIndex(ib, ibi, 4, v3);
- this._storeIndex(ib, ibi, 5, v5);
- this._storeIndex(ib, ibi, 6, v5);
- this._storeIndex(ib, ibi, 7, v3);
- this._storeIndex(ib, ibi, 8, v4);
- }
- break;
- }
- }
- return null;
- };
- Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
- var lineA = BABYLON.Vector2.Zero();
- var lineB = BABYLON.Vector2.Zero();
- var tangent = BABYLON.Vector2.Zero();
- var miter = BABYLON.Vector2.Zero();
- var curNormal = null;
- if (this.closed) {
- this.points.push(this.points[0]);
- }
- var total = this.points.length;
- for (var i = 1; i < total; i++) {
- var last = this.points[i - 1];
- var cur = this.points[i];
- var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
- this._direction(cur, last, lineA);
- if (!curNormal) {
- curNormal = BABYLON.Vector2.Zero();
- this._perp(lineA, curNormal);
- }
- if (i === 1) {
- this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
- }
- if (!next) {
- this._perp(lineA, curNormal);
- this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
- }
- else {
- this._direction(next, cur, lineB);
- var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
- this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
- }
- }
- if (this.points.length > 2 && this.closed) {
- var last2 = this.points[total - 2];
- var cur2 = this.points[0];
- var next2 = this.points[1];
- this._direction(cur2, last2, lineA);
- this._direction(next2, cur2, lineB);
- this._perp(lineA, curNormal);
- var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
- this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
- // Patch contour
- if (contour) {
- var off = (bt == null) ? 0 : 4;
- contour[0].x = vb[off + 0];
- contour[0].y = vb[off + 1];
- contour[1].x = vb[off + 2];
- contour[1].y = vb[off + 3];
- }
- }
- // Remove the point we added at the beginning
- if (this.closed) {
- this.points.splice(total - 1);
- }
- };
- // Methods for Lines building
- ///////////////////////////////////////////////////////////////////////////////////
- Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
- var renderCache = modelRenderCache;
- var engine = this.owner.engine;
- if (this._fillVB === null) {
- this._computeLines2D();
- }
- // Need to create WebGL resources for fill part?
- if (this.fill) {
- renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
- renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
- renderCache.fillIndicesCount = this._fillIB.length;
- // 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
- var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, true);
- if (ei) {
- renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
- }
- // Get the non instanced version
- ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, false);
- renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
- }
- // Need to create WebGL resources for border part?
- if (this.border) {
- renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
- renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
- renderCache.borderIndicesCount = this._borderIB.length;
- // 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
- var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, true);
- if (ei) {
- renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
- }
- // Get the non instanced version
- ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, false);
- renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
- }
- this._fillVB = null;
- this._fillIB = null;
- this._borderVB = null;
- this._borderIB = null;
- return renderCache;
- };
- Lines2D.prototype.updateTriArray = function () {
- if (this._primTriArrayDirty) {
- this._computeLines2D();
- }
- };
- Lines2D.prototype._computeLines2D = function () {
- // Init min/max because their being computed here
- this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
- this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
- var contour = new Array();
- var startCapContour = new Array();
- var endCapContour = new Array();
- // Need to create WebGL resources for fill part?
- if (this.fill) {
- var startCapInfo = this._getCapSize(this.startCap);
- var endCapInfo = this._getCapSize(this.endCap);
- var count = this.points.length;
- var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
- this._fillVB = new Float32Array(vbSize);
- var vb = this._fillVB;
- var ht = this.fillThickness / 2;
- var total = this.points.length;
- this._buildLine(vb, this.border ? null : contour, ht);
- var max = total * 2;
- var triCount = (count - (this.closed ? 0 : 1)) * 2;
- this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
- var ib = this._fillIB;
- for (var i = 0; i < triCount; i += 2) {
- ib[i * 3 + 0] = i + 0;
- ib[i * 3 + 1] = i + 1;
- ib[i * 3 + 2] = (i + 2) % max;
- ib[i * 3 + 3] = i + 1;
- ib[i * 3 + 4] = (i + 3) % max;
- ib[i * 3 + 5] = (i + 2) % max;
- }
- this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D_1._startDir, this.border ? null : startCapContour);
- 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);
- }
- // Need to create WebGL resources for border part?
- if (this.border) {
- var startCapInfo = this._getCapSize(this.startCap, true);
- var endCapInfo = this._getCapSize(this.endCap, true);
- var count = this.points.length;
- var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
- this._borderVB = new Float32Array(vbSize);
- var vb = this._borderVB;
- var ht = this.fillThickness / 2;
- var bt = this.borderThickness;
- var total = this.points.length;
- this._buildLine(vb, contour, ht, bt);
- var max = total * 2 * 2;
- var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
- this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
- var ib = this._borderIB;
- for (var i = 0; i < triCount; i += 4) {
- ib[i * 3 + 0] = i + 0;
- ib[i * 3 + 1] = i + 2;
- ib[i * 3 + 2] = (i + 6) % max;
- ib[i * 3 + 3] = i + 0;
- ib[i * 3 + 4] = (i + 6) % max;
- ib[i * 3 + 5] = (i + 4) % max;
- ib[i * 3 + 6] = i + 3;
- ib[i * 3 + 7] = i + 1;
- ib[i * 3 + 8] = (i + 5) % max;
- ib[i * 3 + 9] = i + 3;
- ib[i * 3 + 10] = (i + 5) % max;
- ib[i * 3 + 11] = (i + 7) % max;
- }
- this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D_1._startDir, startCapContour);
- 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);
- }
- var startCapTri;
- if (startCapContour.length > 0) {
- startCapTri = Earcut.earcut(startCapContour, null, 2);
- }
- var endCapTri;
- if (endCapContour.length > 0) {
- endCapTri = Earcut.earcut(endCapContour, null, 2);
- }
- // Build the Tri2DArray using the contour info from the shape and the caps (if any)
- {
- var pl = this.points.length;
- // Count the number of needed triangles
- var count = ((this.closed ? pl : (pl - 1)) * 2) + (startCapTri != null ? ((startCapTri.length + endCapTri.length) / 3) : 0);
- // Init/Clear the TriArray
- if (!this._primTriArray) {
- this._primTriArray = new BABYLON.Tri2DArray(count);
- }
- else {
- this._primTriArray.clear(count);
- }
- var pta_1 = this._primTriArray;
- var l = this.closed ? pl + 1 : pl;
- Lines2D_1._prevA.copyFrom(contour[0]);
- Lines2D_1._prevB.copyFrom(contour[1]);
- var si_1 = 0;
- for (var i = 1; i < l; i++) {
- Lines2D_1._curA.copyFrom(contour[(i % pl) * 2 + 0]);
- Lines2D_1._curB.copyFrom(contour[(i % pl) * 2 + 1]);
- pta_1.storeTriangle(si_1++, Lines2D_1._prevA, Lines2D_1._prevB, Lines2D_1._curA);
- pta_1.storeTriangle(si_1++, Lines2D_1._curA, Lines2D_1._prevB, Lines2D_1._curB);
- Lines2D_1._prevA.x = Lines2D_1._curA.x;
- Lines2D_1._prevA.y = Lines2D_1._curA.y;
- Lines2D_1._prevB.x = Lines2D_1._curB.x;
- Lines2D_1._prevB.y = Lines2D_1._curB.y;
- }
- var capIntersect = function (tri, points) {
- var l = tri.length;
- for (var i = 0; i < l; i += 3) {
- Lines2D_1._curA.x = points[tri[i + 0] * 2 + 0];
- Lines2D_1._curA.y = points[tri[i + 0] * 2 + 1];
- Lines2D_1._curB.copyFrom(Lines2D_1._curA);
- Lines2D_1._curA.x = points[tri[i + 1] * 2 + 0];
- Lines2D_1._curA.y = points[tri[i + 1] * 2 + 1];
- Lines2D_1._prevA.copyFrom(Lines2D_1._curA);
- Lines2D_1._curA.x = points[tri[i + 2] * 2 + 0];
- Lines2D_1._curA.y = points[tri[i + 2] * 2 + 1];
- Lines2D_1._prevB.copyFrom(Lines2D_1._curA);
- pta_1.storeTriangle(si_1++, Lines2D_1._prevA, Lines2D_1._prevB, Lines2D_1._curB);
- }
- return false;
- };
- if (startCapTri) {
- if (startCapTri) {
- capIntersect(startCapTri, startCapContour);
- }
- if (endCapTri) {
- capIntersect(endCapTri, endCapContour);
- }
- }
- this._primTriArrayDirty = false;
- }
- var bs = this._boundingMax.subtract(this._boundingMin);
- // If the size is not size we were computing the first pass to determine the size took by the primitive
- if (!this._size) {
- // Set the size and compute a second time to consider the size while computing the points using the origin
- this._size = new BABYLON.Size(bs.x, bs.y);
- this._updatePositioningState();
- }
- this._size.width = bs.x;
- this._size.height = bs.y;
- this._actualSize = null;
- };
- Object.defineProperty(Lines2D.prototype, "size", {
- get: function () {
- if (this._size == null) {
- this._computeLines2D();
- }
- return this._size;
- },
- enumerable: true,
- configurable: true
- });
- Lines2D.prototype.createInstanceDataParts = function () {
- var res = new Array();
- if (this.border) {
- res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
- }
- if (this.fill) {
- res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
- }
- return res;
- };
- Lines2D.prototype.applyActualScaleOnTransform = function () {
- return true;
- };
- Lines2D.prototype.refreshInstanceDataPart = function (part) {
- if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
- return false;
- }
- if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
- var d = part;
- if (this.border instanceof BABYLON.GradientColorBrush2D) {
- d.boundingMin = this.boundingMin;
- d.boundingMax = this.boundingMax;
- }
- }
- else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
- var d = part;
- if (this.fill instanceof BABYLON.GradientColorBrush2D) {
- d.boundingMin = this.boundingMin;
- d.boundingMax = this.boundingMax;
- }
- }
- return true;
- };
- return Lines2D;
- }(BABYLON.Shape2D));
- Lines2D._prevA = BABYLON.Vector2.Zero();
- Lines2D._prevB = BABYLON.Vector2.Zero();
- Lines2D._curA = BABYLON.Vector2.Zero();
- Lines2D._curB = BABYLON.Vector2.Zero();
- Lines2D._miterTps = BABYLON.Vector2.Zero();
- Lines2D._startDir = BABYLON.Vector2.Zero();
- Lines2D._endDir = BABYLON.Vector2.Zero();
- Lines2D._tpsV = BABYLON.Vector2.Zero();
- Lines2D._noCap = 0;
- Lines2D._roundCap = 1;
- Lines2D._triangleCap = 2;
- Lines2D._squareAnchorCap = 3;
- Lines2D._roundAnchorCap = 4;
- Lines2D._diamondAnchorCap = 5;
- Lines2D._arrowCap = 6;
- Lines2D._roundCapSubDiv = 36;
- __decorate([
- BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D_1.pointsProperty = pi; })
- /**
- * Get the list of points that define the Lines2D primitive. You shouldn't try to change the list or its content. it's not supported right now.
- */
- ], Lines2D.prototype, "points", null);
- __decorate([
- BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D_1.fillThicknessProperty = pi; })
- /**
- * Get the thickness of the line. You shouldn't try to change this value, it's not supported right now.
- */
- ], Lines2D.prototype, "fillThickness", null);
- __decorate([
- BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D_1.closedProperty = pi; })
- /**
- * Get if the Lines2D is a closed shape (true) or an opened one (false).
- * Don't change this property, setter is for internal purpose only.
- */
- ], Lines2D.prototype, "closed", null);
- __decorate([
- BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D_1.startCapProperty = pi; })
- /**
- * Get the start cap of the line. You shouldn't try to change this value, it's not supported right now.
- */
- ], Lines2D.prototype, "startCap", null);
- __decorate([
- BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D_1.endCapProperty = pi; })
- /**
- * Get the end cap of the line. You shouldn't try to change this value, it's not supported right now.
- */
- ], Lines2D.prototype, "endCap", null);
- Lines2D = Lines2D_1 = __decorate([
- BABYLON.className("Lines2D", "BABYLON")
- /**
- * Primitive drawing a series of line segments
- */
- ], Lines2D);
- BABYLON.Lines2D = Lines2D;
- var Lines2D_1;
- })(BABYLON || (BABYLON = {}));
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- // This class contains data that lifetime is bounding to the Babylon Engine object
- var Canvas2DEngineBoundData = (function () {
- function Canvas2DEngineBoundData() {
- this._modelCache = new BABYLON.StringDictionary();
- }
- Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
- return this._modelCache.getOrAddWithFactory(key, factory);
- };
- Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
- if (!modelRenderCache.isDisposed) {
- return false;
- }
- this._modelCache.remove(modelRenderCache.modelKey);
- return true;
- };
- return Canvas2DEngineBoundData;
- }());
- BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
- var Canvas2D = Canvas2D_1 = (function (_super) {
- __extends(Canvas2D, _super);
- function Canvas2D(scene, settings) {
- var _this = _super.call(this, settings) || this;
- /**
- * 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.
- * Beware that you have to take under consideration the origin and unitScaleFactor in your calculations! Good luck!
- */
- _this.worldSpaceToNodeLocal = function (worldPos) {
- var node = _this._worldSpaceNode;
- if (!node) {
- return;
- }
- var mtx = node.getWorldMatrix().clone();
- mtx.invert();
- var usf = _this.unitScaleFactor;
- var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
- var res = new BABYLON.Vector2(v.x, v.y);
- var size = _this.actualSize;
- res.x += (size.width / usf) * 0.5; // res is centered, make it relative to bottom/left
- res.y += (size.height / usf) * 0.5;
- res.x *= usf; // multiply by the unitScaleFactor, which defines if the canvas is nth time bigger than the original world plane
- res.y *= usf;
- return res;
- };
- /**
- * 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
- */
- _this.worldSpaceCacheChanged = function () {
- var plane = _this.worldSpaceCanvasNode;
- var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
- vd.uvs = new Float32Array(8);
- var material = plane.material;
- var tex = _this._renderableData._cacheTexture;
- if (material.diffuseTexture !== tex) {
- material.diffuseTexture = tex;
- tex.hasAlpha = true;
- }
- var nodeuv = _this._renderableData._cacheNodeUVs;
- for (var i = 0; i < 4; i++) {
- vd.uvs[i * 2 + 0] = nodeuv[i].x;
- vd.uvs[i * 2 + 1] = nodeuv[i].y;
- }
- vd.applyToMesh(plane);
- };
- _this._notifDebugMode = false;
- /**
- * Instanced Array will be create if there's at least this number of parts/prim that can fit into it
- */
- _this.minPartCountToUseInstancedArray = 5;
- _this._mapCounter = 0;
- _this._cachedCanvasGroup = null;
- _this._renderingGroupObserver = null;
- _this._beforeRenderObserver = null;
- _this._afterRenderObserver = null;
- _this._profileInfoText = null;
- BABYLON.Prim2DBase._isCanvasInit = false;
- if (!settings) {
- settings = {};
- }
- if (_this._cachingStrategy !== Canvas2D_1.CACHESTRATEGY_TOPLEVELGROUPS) {
- _this._background = new BABYLON.Rectangle2D({ parent: _this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
- _this._background.zOrder = 1.0;
- _this._background.isPickable = false;
- _this._background.origin = BABYLON.Vector2.Zero();
- _this._background.levelVisible = false;
- if (settings.backgroundRoundRadius != null) {
- _this.backgroundRoundRadius = settings.backgroundRoundRadius;
- }
- if (settings.backgroundBorder != null) {
- if (typeof (settings.backgroundBorder) === "string") {
- _this.backgroundBorder = Canvas2D_1.GetBrushFromString(settings.backgroundBorder);
- }
- else {
- _this.backgroundBorder = settings.backgroundBorder;
- }
- }
- if (settings.backgroundBorderThickNess != null) {
- _this.backgroundBorderThickness = settings.backgroundBorderThickNess;
- }
- if (settings.backgroundFill != null) {
- if (typeof (settings.backgroundFill) === "string") {
- _this.backgroundFill = Canvas2D_1.GetBrushFromString(settings.backgroundFill);
- }
- else {
- _this.backgroundFill = settings.backgroundFill;
- }
- }
- // Put a handler to resize the background whenever the canvas is resizing
- _this.propertyChanged.add(function (e, s) {
- if (e.propertyName === "size") {
- _this._background.size = _this.size;
- }
- }, BABYLON.Group2D.sizeProperty.flagId);
- _this._background._patchHierarchy(_this);
- }
- var engine = scene.getEngine();
- _this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
- _this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
- _this._capturedPointers = new BABYLON.StringDictionary();
- _this._pickStartingPosition = BABYLON.Vector2.Zero();
- _this._hierarchyLevelMaxSiblingCount = 50;
- _this._hierarchyDepth = 0;
- _this._zOrder = 0;
- _this._zMax = 1;
- _this._scene = scene;
- _this._engine = engine;
- _this._renderingSize = new BABYLON.Size(0, 0);
- _this._curHWScale = 0;
- _this._canvasLevelScale = new BABYLON.Vector2(1, 1);
- _this._designSize = settings.designSize || null;
- _this._designUseHorizAxis = settings.designUseHorizAxis === true;
- if (!_this._trackedGroups) {
- _this._trackedGroups = new Array();
- }
- _this._maxAdaptiveWorldSpaceCanvasSize = null;
- _this._groupCacheMaps = new BABYLON.StringDictionary();
- _this._patchHierarchy(_this);
- var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
- _this._fitRenderingDevice = !settings.size;
- if (!settings.size) {
- settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
- }
- // Register scene dispose to also dispose the canvas when it'll happens
- scene.onDisposeObservable.add(function (d, s) {
- _this.dispose();
- });
- if (_this._isScreenSpace) {
- if (settings.renderingPhase) {
- if (!settings.renderingPhase.camera || settings.renderingPhase.renderingGroupID == null) {
- throw Error("You have to specify a valid camera and renderingGroup");
- }
- _this._renderingGroupObserver = _this._scene.onRenderingGroupObservable.add(function (e, s) {
- if ((_this._scene.activeCamera === settings.renderingPhase.camera) && (e.renderStage === BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT)) {
- _this._engine.clear(null, false, true, true);
- BABYLON.C2DLogging._startFrameRender();
- _this._render();
- BABYLON.C2DLogging._endFrameRender();
- }
- }, Math.pow(2, settings.renderingPhase.renderingGroupID));
- }
- else {
- _this._afterRenderObserver = _this._scene.onAfterRenderObservable.add(function (d, s) {
- _this._engine.clear(null, false, true, true);
- BABYLON.C2DLogging._startFrameRender();
- _this._render();
- BABYLON.C2DLogging._endFrameRender();
- });
- }
- }
- else {
- _this._beforeRenderObserver = _this._scene.onBeforeRenderObservable.add(function (d, s) {
- BABYLON.C2DLogging._startFrameRender();
- _this._render();
- BABYLON.C2DLogging._endFrameRender();
- });
- }
- _this._supprtInstancedArray = _this._engine.getCaps().instancedArrays !== null;
- //this._supprtInstancedArray = false; // TODO REMOVE!!!
- // Setup the canvas for interaction (or not)
- _this._setupInteraction(enableInteraction);
- // Initialize the Primitive Collision Manager
- if (settings.enableCollisionManager) {
- var enableBorders = settings.collisionManagerUseBorders;
- _this._primitiveCollisionManager = (settings.customCollisionManager == null) ? BABYLON.PrimitiveCollisionManagerBase.allocBasicPCM(_this, enableBorders) : settings.customCollisionManager(_this, enableBorders);
- }
- // Register this instance
- Canvas2D_1._INSTANCES.push(_this);
- return _this;
- }
- Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
- get: function () {
- if (!this._drawCallsOpaqueCounter) {
- this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
- }
- return this._drawCallsOpaqueCounter;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
- get: function () {
- if (!this._drawCallsAlphaTestCounter) {
- this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
- }
- return this._drawCallsAlphaTestCounter;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
- get: function () {
- if (!this._drawCallsTransparentCounter) {
- this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
- }
- return this._drawCallsTransparentCounter;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
- get: function () {
- if (!this._groupRenderCounter) {
- this._groupRenderCounter = new BABYLON.PerfCounter();
- }
- return this._groupRenderCounter;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
- get: function () {
- if (!this._updateTransparentDataCounter) {
- this._updateTransparentDataCounter = new BABYLON.PerfCounter();
- }
- return this._updateTransparentDataCounter;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
- get: function () {
- if (!this._updateCachedStateCounter) {
- this._updateCachedStateCounter = new BABYLON.PerfCounter();
- }
- return this._updateCachedStateCounter;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
- get: function () {
- if (!this._updateLayoutCounter) {
- this._updateLayoutCounter = new BABYLON.PerfCounter();
- }
- return this._updateLayoutCounter;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
- get: function () {
- if (!this._updatePositioningCounter) {
- this._updatePositioningCounter = new BABYLON.PerfCounter();
- }
- return this._updatePositioningCounter;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
- get: function () {
- if (!this._updateLocalTransformCounter) {
- this._updateLocalTransformCounter = new BABYLON.PerfCounter();
- }
- return this._updateLocalTransformCounter;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
- get: function () {
- if (!this._updateGlobalTransformCounter) {
- this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
- }
- return this._updateGlobalTransformCounter;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
- get: function () {
- if (!this._boundingInfoRecomputeCounter) {
- this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
- }
- return this._boundingInfoRecomputeCounter;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "layoutBoundingInfoUpdateCounter", {
- get: function () {
- if (!this._layoutBoundingInfoUpdateCounter) {
- this._layoutBoundingInfoUpdateCounter = new BABYLON.PerfCounter();
- }
- return this._layoutBoundingInfoUpdateCounter;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "canvasRenderTimeCounter", {
- get: function () {
- if (!this._canvasRenderTimeCounter) {
- this._canvasRenderTimeCounter = new BABYLON.PerfCounter();
- }
- return this._canvasRenderTimeCounter;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D, "instances", {
- get: function () {
- return Canvas2D_1._INSTANCES;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "primitiveCollisionManager", {
- get: function () {
- return this._primitiveCollisionManager;
- },
- enumerable: true,
- configurable: true
- });
- Canvas2D.prototype._canvasPreInit = function (settings) {
- var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D_1.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
- this._cachingStrategy = cachingStrategy;
- this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
- this._hierarchyDepth = 0;
- };
- Canvas2D.prototype._setupInteraction = function (enable) {
- var _this = this;
- // No change detection
- if (enable === this._interactionEnabled) {
- return;
- }
- // Set the new state
- this._interactionEnabled = enable;
- // ScreenSpace mode
- if (this._isScreenSpace) {
- // Disable interaction
- if (!enable) {
- if (this._scenePrePointerObserver) {
- this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
- this._scenePrePointerObserver = null;
- }
- return;
- }
- // Enable Interaction
- // Register the observable
- this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
- if (_this.isVisible === false) {
- return;
- }
- _this._handlePointerEventForInteraction(e, e.localPosition, s);
- });
- }
- else {
- var scene = this.scene;
- if (enable) {
- scene.constantlyUpdateMeshUnderPointer = true;
- this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
- if (_this.isVisible === false) {
- return;
- }
- if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
- var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
- _this._handlePointerEventForInteraction(e, localPos, s);
- }
- else if (_this._actualIntersectionList && _this._actualIntersectionList.length > 0) {
- _this._handlePointerEventForInteraction(e, null, s);
- }
- });
- }
- else {
- if (this._scenePointerObserver) {
- this.scene.onPointerObservable.remove(this._scenePointerObserver);
- this._scenePointerObserver = null;
- }
- }
- }
- };
- /**
- * Internal method, you should use the Prim2DBase version instead
- */
- Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
- if (this.isPointerCaptured(pointerId)) {
- return false;
- }
- // Try to capture the pointer on the HTML side
- try {
- this.engine.getRenderingCanvas().setPointerCapture(pointerId);
- }
- catch (e) {
- //Nothing to do with the error. Execution will continue.
- }
- this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
- this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
- this._capturedPointers.add(pointerId.toString(), primitive);
- return true;
- };
- /**
- * Internal method, you should use the Prim2DBase version instead
- */
- Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
- if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
- return false;
- }
- // Try to release the pointer on the HTML side
- try {
- this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
- }
- catch (e) {
- //Nothing to do with the error. Execution will continue.
- }
- this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
- this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
- this._capturedPointers.remove(pointerId.toString());
- return true;
- };
- /**
- * Determine if the given pointer is captured or not
- * @param pointerId the Id of the pointer
- * @return true if it's captured, false otherwise
- */
- Canvas2D.prototype.isPointerCaptured = function (pointerId) {
- return this._capturedPointers.contains(pointerId.toString());
- };
- Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
- // Avoid unnecessary lookup
- if (this._capturedPointers.count === 0) {
- return null;
- }
- return this._capturedPointers.get(pointerId.toString());
- };
- Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
- // Dispose check
- if (this.isDisposed) {
- return;
- }
- // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
- if (localPosition) {
- if (!this._updatePointerInfo(eventData, localPosition)) {
- return;
- }
- }
- else {
- this._primPointerInfo.canvasPointerPos = null;
- }
- var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
- // 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.
- // 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.
- this._updateIntersectionList(localPosition ? this._primPointerInfo.canvasPointerPos : null, capturedPrim !== null, true);
- // 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
- this._updateOverStatus(true);
- // Check if we have nothing to raise
- if (!this._actualOverPrimitive && !capturedPrim) {
- return;
- }
- // Update the relatedTarget info with the over primitive or the captured one (if any)
- var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
- var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[4], targetPrim.globalTransform.m[5])) : this._actualOverPrimitive.intersectionLocation;
- this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
- // Analyze the pointer event type and fire proper events on the primitive
- var skip = false;
- if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
- skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData);
- }
- else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
- skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData);
- }
- else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
- skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData);
- }
- else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
- skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData);
- }
- eventState.skipNextObservers = skip;
- };
- Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
- var s = this._canvasLevelScale.multiplyByFloats(this.scaleX, this.scaleY);
- var pii = this._primPointerInfo;
- pii.cancelBubble = false;
- if (!pii.canvasPointerPos) {
- pii.canvasPointerPos = BABYLON.Vector2.Zero();
- }
- var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
- if (!camera || !camera.viewport) {
- return false;
- }
- var engine = this._scene.getEngine();
- if (this._isScreenSpace) {
- var cameraViewport = camera.viewport;
- var renderWidth = engine.getRenderWidth();
- var renderHeight = engine.getRenderHeight();
- // console.log(`Render Width: ${renderWidth} Height: ${renderHeight}, localX: ${localPosition.x}, localY: ${localPosition.y}`);
- var viewport = cameraViewport.toGlobal(renderWidth, renderHeight);
- // Moving coordinates to local viewport world
- var x = localPosition.x - viewport.x;
- var y = localPosition.y - viewport.y;
- pii.canvasPointerPos.x = (x - this.actualPosition.x) / s.x;
- pii.canvasPointerPos.y = (renderHeight - y - this.actualPosition.y) / s.y;
- }
- else {
- pii.canvasPointerPos.x = localPosition.x / s.x;
- pii.canvasPointerPos.y = localPosition.y / s.x;
- }
- //console.log(`UpdatePointerInfo for ${this.id}, X:${pii.canvasPointerPos.x}, Y:${pii.canvasPointerPos.y}`);
- pii.mouseWheelDelta = 0;
- if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
- var event = eventData.event;
- if (event.wheelDelta) {
- pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
- }
- else if (event.detail) {
- pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
- }
- }
- else {
- var pe = eventData.event;
- pii.ctrlKey = pe.ctrlKey;
- pii.altKey = pe.altKey;
- pii.shiftKey = pe.shiftKey;
- pii.metaKey = pe.metaKey;
- pii.button = pe.button;
- pii.buttons = pe.buttons;
- pii.pointerId = pe.pointerId;
- pii.width = pe.width;
- pii.height = pe.height;
- pii.presssure = pe.pressure;
- pii.tilt.x = pe.tiltX;
- pii.tilt.y = pe.tiltY;
- pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
- }
- return true;
- };
- Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture, force) {
- if (!force && (this.scene.getRenderId() === this._intersectionRenderId)) {
- return;
- }
- var ii = Canvas2D_1._interInfo;
- var outCase = mouseLocalPos == null;
- if (!outCase) {
- // 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
- if (!this._globalTransform) {
- this.updateCachedStates(true);
- }
- ii.pickPosition.x = mouseLocalPos.x;
- ii.pickPosition.y = mouseLocalPos.y;
- ii.findFirstOnly = false;
- // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
- if (!isCapture && !this.levelBoundingInfo.doesIntersect(ii.pickPosition)) {
- // Reset intersection info as we don't hit anything
- ii.intersectedPrimitives = new Array();
- ii.topMostIntersectedPrimitive = null;
- }
- else {
- // The pointer is inside the Canvas, do an intersection test
- this.intersect(ii);
- // Sort primitives to get them from top to bottom
- ii.intersectedPrimitives = ii.intersectedPrimitives.sort(function (a, b) { return a.prim.actualZOffset - b.prim.actualZOffset; });
- }
- }
- {
- // Update prev/actual intersection info, fire "overPrim" property change if needed
- this._previousIntersectionList = this._actualIntersectionList;
- this._actualIntersectionList = outCase ? new Array() : ii.intersectedPrimitives;
- this._previousOverPrimitive = this._actualOverPrimitive;
- this._actualOverPrimitive = outCase ? null : ii.topMostIntersectedPrimitive;
- var prev = (this._previousOverPrimitive != null) ? this._previousOverPrimitive.prim : null;
- var actual = (this._actualOverPrimitive != null) ? this._actualOverPrimitive.prim : null;
- if (prev !== actual) {
- this.onPropertyChanged("overPrim", this._previousOverPrimitive ? this._previousOverPrimitive.prim : null, this._actualOverPrimitive ? this._actualOverPrimitive.prim : null);
- }
- }
- this._intersectionRenderId = this.scene.getRenderId();
- };
- // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
- Canvas2D.prototype._updateOverStatus = function (force) {
- if ((!force && (this.scene.getRenderId() === this._hoverStatusRenderId)) || !this._actualIntersectionList) {
- return;
- }
- if (this._previousIntersectionList == null) {
- this._previousIntersectionList = [];
- }
- // Detect a change of over
- var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
- var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
- if (prevPrim !== actualPrim) {
- // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
- var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
- // See the NOTE section of: https://www.w3.org/TR/pointerevents/#setting-pointer-capture
- if (capturedPrim) {
- if (capturedPrim === prevPrim) {
- this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
- this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
- }
- else if (capturedPrim === actualPrim) {
- this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
- this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
- }
- }
- else {
- var _loop_1 = function (prev) {
- if (!BABYLON.Tools.first(this_1._actualIntersectionList, function (pii) { return pii.prim === prev.prim; })) {
- this_1._primPointerInfo.updateRelatedTarget(prev.prim, prev.intersectionLocation);
- this_1._bubbleNotifyPrimPointerObserver(prev.prim, BABYLON.PrimitivePointerInfo.PointerOut, null);
- }
- };
- var this_1 = this;
- // Check for Out & Leave
- for (var _i = 0, _a = this._previousIntersectionList; _i < _a.length; _i++) {
- var prev = _a[_i];
- _loop_1(prev);
- }
- var _loop_2 = function (actual) {
- if (!BABYLON.Tools.first(this_2._previousIntersectionList, function (pii) { return pii.prim === actual.prim; })) {
- this_2._primPointerInfo.updateRelatedTarget(actual.prim, actual.intersectionLocation);
- this_2._bubbleNotifyPrimPointerObserver(actual.prim, BABYLON.PrimitivePointerInfo.PointerOver, null);
- }
- };
- var this_2 = this;
- // Check for Over & Enter
- for (var _b = 0, _c = this._actualIntersectionList; _b < _c.length; _b++) {
- var actual = _c[_b];
- _loop_2(actual);
- }
- }
- }
- this._hoverStatusRenderId = this.scene.getRenderId();
- };
- Canvas2D.prototype._updatePrimPointerPos = function (prim) {
- if (this._primPointerInfo.isCaptured) {
- this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
- }
- else {
- for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
- var pii = _a[_i];
- if (pii.prim === prim) {
- this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
- return;
- }
- }
- }
- };
- Canvas2D.prototype._debugExecObserver = function (prim, mask) {
- if (!this._notifDebugMode) {
- return;
- }
- var debug = "";
- for (var i = 0; i < prim.hierarchyDepth; i++) {
- debug += " ";
- }
- var pii = this._primPointerInfo;
- 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;
- console.log(debug);
- };
- Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
- var ppi = this._primPointerInfo;
- var event = eventData ? eventData.event : null;
- var cur = prim;
- while (cur && !cur.isDisposed) {
- this._updatePrimPointerPos(cur);
- // For the first level we have to fire Enter or Leave for corresponding Over or Out
- if (cur === prim) {
- // Fire the proper notification
- if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
- this._debugExecObserver(prim, BABYLON.PrimitivePointerInfo.PointerEnter);
- prim._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
- }
- else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
- this._debugExecObserver(prim, BABYLON.PrimitivePointerInfo.PointerLeave);
- prim._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
- }
- }
- // Exec the observers
- this._debugExecObserver(cur, mask);
- if (!cur._pointerEventObservable.notifyObservers(ppi, mask) && eventData instanceof BABYLON.PointerInfoPre) {
- eventData.skipOnPointerObservable = true;
- return false;
- }
- this._triggerActionManager(cur, ppi, mask, event);
- // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
- // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
- if (ppi.cancelBubble) {
- return false;
- }
- // Loop to the parent
- cur = cur.parent;
- }
- return true;
- };
- Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
- var _this = this;
- // 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
- if (!this._globalTransform) {
- this.updateCachedStates(true);
- }
- // Process Trigger related to PointerDown
- if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
- // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
- this._pickStartingPosition = ppi.primitivePointerPos.clone();
- this._pickStartingTime = new Date().getTime();
- this._pickedDownPrim = null;
- if (prim.actionManager) {
- this._pickedDownPrim = prim;
- if (prim.actionManager.hasPickTriggers) {
- var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
- switch (eventData.button) {
- case 0:
- prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
- break;
- case 1:
- prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
- break;
- case 2:
- prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
- break;
- }
- prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
- }
- if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
- window.setTimeout(function () {
- var ppi = _this._primPointerInfo;
- var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
- _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null, true);
- _this._updateOverStatus(false);
- var ii = new BABYLON.IntersectInfo2D();
- ii.pickPosition = ppi.canvasPointerPos.clone();
- ii.findFirstOnly = false;
- _this.intersect(ii);
- if (ii.isPrimIntersected(prim) !== null) {
- if (prim.actionManager) {
- if (_this._pickStartingTime !== 0 && ((new Date().getTime() - _this._pickStartingTime) > BABYLON.Scene.LongPressDelay) && (Math.abs(_this._pickStartingPosition.x - ii.pickPosition.x) < BABYLON.Scene.DragMovementThreshold && Math.abs(_this._pickStartingPosition.y - ii.pickPosition.y) < BABYLON.Scene.DragMovementThreshold)) {
- _this._pickStartingTime = 0;
- prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
- }
- }
- }
- }, BABYLON.Scene.LongPressDelay);
- }
- }
- }
- else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
- this._pickStartingTime = 0;
- var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
- if (prim.actionManager) {
- // OnPickUpTrigger
- prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
- // OnPickTrigger
- if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.Scene.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.Scene.DragMovementThreshold) {
- prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
- }
- }
- // OnPickOutTrigger
- if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
- this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
- }
- }
- else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
- if (prim.actionManager) {
- var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
- prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
- }
- }
- else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
- if (prim.actionManager) {
- var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
- prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
- }
- }
- };
- /**
- * Don't forget to call the dispose method when you're done with the Canvas instance.
- * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
- */
- Canvas2D.prototype.dispose = function () {
- if (!_super.prototype.dispose.call(this)) {
- return false;
- }
- if (this._profilingCanvas) {
- this._profilingCanvas.dispose();
- this._profilingCanvas = null;
- }
- if (this.interactionEnabled) {
- this._setupInteraction(false);
- }
- if (this._renderingGroupObserver) {
- this._scene.onRenderingGroupObservable.remove(this._renderingGroupObserver);
- this._renderingGroupObserver = null;
- }
- if (this._beforeRenderObserver) {
- this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
- this._beforeRenderObserver = null;
- }
- if (this._afterRenderObserver) {
- this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
- this._afterRenderObserver = null;
- }
- if (this._groupCacheMaps) {
- this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
- this._groupCacheMaps = null;
- }
- // Unregister this instance
- var index = Canvas2D_1._INSTANCES.indexOf(this);
- if (index > -1) {
- Canvas2D_1._INSTANCES.splice(index, 1);
- }
- return true;
- };
- Object.defineProperty(Canvas2D.prototype, "scene", {
- /**
- * Accessor to the Scene that owns the Canvas
- * @returns The instance of the Scene object
- */
- get: function () {
- return this._scene;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "engine", {
- /**
- * Accessor to the Engine that drives the Scene used by this Canvas
- * @returns The instance of the Engine object
- */
- get: function () {
- return this._engine;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "renderObservable", {
- /**
- * And observable called during the Canvas rendering process.
- * This observable is called twice per render, each time with a different mask:
- * - 1: before render is executed
- * - 2: after render is executed
- */
- get: function () {
- if (!this._renderObservable) {
- this._renderObservable = new BABYLON.Observable();
- }
- return this._renderObservable;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
- /**
- * Accessor of the Caching Strategy used by this Canvas.
- * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
- * @returns the value corresponding to the used strategy.
- */
- get: function () {
- return this._cachingStrategy;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
- /**
- * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
- * @returns {}
- */
- get: function () {
- return this._isScreenSpace;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
- /**
- * Only valid for World Space Canvas, returns the scene node that displays the canvas
- */
- get: function () {
- return this._worldSpaceNode;
- },
- set: function (val) {
- this._worldSpaceNode = val;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
- /**
- * Check if the WebGL Instanced Array extension is supported or not
- */
- get: function () {
- return this._supprtInstancedArray;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
- /**
- * Property that defines the fill object used to draw the background of the Canvas.
- * Note that Canvas with a Caching Strategy of
- * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
- */
- get: function () {
- if (!this._background || !this._background.isVisible) {
- return null;
- }
- return this._background.fill;
- },
- set: function (value) {
- this.checkBackgroundAvailability();
- if (value === this._background.fill) {
- return;
- }
- this._background.fill = value;
- this._background.levelVisible = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
- /**
- * Property that defines the border object used to draw the background of the Canvas.
- * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
- */
- get: function () {
- if (!this._background || !this._background.isVisible) {
- return null;
- }
- return this._background.border;
- },
- set: function (value) {
- this.checkBackgroundAvailability();
- if (value === this._background.border) {
- return;
- }
- this._background.border = value;
- this._background.levelVisible = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
- /**
- * Property that defines the thickness of the border object used to draw the background of the Canvas.
- * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
- */
- get: function () {
- if (!this._background || !this._background.isVisible) {
- return null;
- }
- return this._background.borderThickness;
- },
- set: function (value) {
- this.checkBackgroundAvailability();
- if (value === this._background.borderThickness) {
- return;
- }
- this._background.borderThickness = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
- /**
- * You can set the roundRadius of the background
- * @returns The current roundRadius
- */
- get: function () {
- if (!this._background || !this._background.isVisible) {
- return null;
- }
- return this._background.roundRadius;
- },
- set: function (value) {
- this.checkBackgroundAvailability();
- if (value === this._background.roundRadius) {
- return;
- }
- this._background.roundRadius = value;
- this._background.levelVisible = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
- /**
- * Enable/Disable interaction for this Canvas
- * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
- */
- get: function () {
- return this._interactionEnabled;
- },
- set: function (enable) {
- this._setupInteraction(enable);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "fitRenderingDevice", {
- get: function () {
- return this._fitRenderingDevice;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "designSize", {
- get: function () {
- return this._designSize;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "designSizeUseHorizAxis", {
- get: function () {
- return this._designUseHorizAxis;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "designSizeUseHorizeAxis", {
- set: function (value) {
- this._designUseHorizAxis = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "overPrim", {
- /**
- * Return
- */
- get: function () {
- if (this._actualIntersectionList && this._actualIntersectionList.length > 0) {
- return this._actualIntersectionList[0].prim;
- }
- return null;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "_engineData", {
- /**
- * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
- * @returns {}
- */
- get: function () {
- return this.__engineData;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Canvas2D.prototype, "unitScaleFactor", {
- get: function () {
- return this._unitScaleFactor;
- },
- enumerable: true,
- configurable: true
- });
- Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
- if (this._profilingCanvas) {
- return this._profilingCanvas;
- }
- var canvas = new ScreenSpaceCanvas2D(this.scene, {
- id: "ProfileInfoCanvas", cachingStrategy: Canvas2D_1.CACHESTRATEGY_DONTCACHE, children: [
- new BABYLON.Rectangle2D({
- id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
- new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "12pt Lucida Console", fontSignedDistanceField: true })
- ]
- })
- ]
- });
- this._profileInfoText = canvas.findById("ProfileInfoText");
- this._profilingCanvas = canvas;
- return canvas;
- };
- Canvas2D.prototype.checkBackgroundAvailability = function () {
- if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_TOPLEVELGROUPS) {
- throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
- }
- };
- Canvas2D.prototype._initPerfMetrics = function () {
- this.drawCallsOpaqueCounter.fetchNewFrame();
- this.drawCallsAlphaTestCounter.fetchNewFrame();
- this.drawCallsTransparentCounter.fetchNewFrame();
- this.groupRenderCounter.fetchNewFrame();
- this.updateTransparentDataCounter.fetchNewFrame();
- this.updateCachedStateCounter.fetchNewFrame();
- this.updateLayoutCounter.fetchNewFrame();
- this.updatePositioningCounter.fetchNewFrame();
- this.updateLocalTransformCounter.fetchNewFrame();
- this.updateGlobalTransformCounter.fetchNewFrame();
- this.boundingInfoRecomputeCounter.fetchNewFrame();
- this.layoutBoundingInfoUpdateCounter.fetchNewFrame();
- this.canvasRenderTimeCounter.beginMonitoring();
- };
- Canvas2D.prototype._fetchPerfMetrics = function () {
- this.drawCallsOpaqueCounter.addCount(0, true);
- this.drawCallsAlphaTestCounter.addCount(0, true);
- this.drawCallsTransparentCounter.addCount(0, true);
- this.groupRenderCounter.addCount(0, true);
- this.updateTransparentDataCounter.addCount(0, true);
- this.updateCachedStateCounter.addCount(0, true);
- this.updateLayoutCounter.addCount(0, true);
- this.updatePositioningCounter.addCount(0, true);
- this.updateLocalTransformCounter.addCount(0, true);
- this.updateGlobalTransformCounter.addCount(0, true);
- this.boundingInfoRecomputeCounter.addCount(0, true);
- this.layoutBoundingInfoUpdateCounter.addCount(0, true);
- this.canvasRenderTimeCounter.endMonitoring(true);
- };
- Canvas2D.prototype._updateProfileCanvas = function () {
- if (this._profileInfoText == null) {
- return;
- }
- var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
- var p = "Render Time: avg:" + format(this.canvasRenderTimeCounter.lastSecAverage) + "ms " + format(this.canvasRenderTimeCounter.current) + "ms\n" +
- "Draw Calls:\n" +
- (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
- (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
- (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
- ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
- ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
- ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
- (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
- (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
- (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
- (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
- (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n") +
- (" - LayoutBoundingInfo Recompute: " + this.layoutBoundingInfoUpdateCounter.current + ", (avg:" + format(this.layoutBoundingInfoUpdateCounter.lastSecAverage) + ", t:" + format(this.layoutBoundingInfoUpdateCounter.total) + ")");
- this._profileInfoText.text = p;
- };
- Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
- switch (renderMode) {
- case BABYLON.Render2DContext.RenderModeOpaque:
- this._drawCallsOpaqueCounter.addCount(count, false);
- return;
- case BABYLON.Render2DContext.RenderModeAlphaTest:
- this._drawCallsAlphaTestCounter.addCount(count, false);
- return;
- case BABYLON.Render2DContext.RenderModeTransparent:
- this._drawCallsTransparentCounter.addCount(count, false);
- return;
- }
- };
- Canvas2D.prototype._addGroupRenderCount = function (count) {
- if (this._groupRenderCounter) {
- this._groupRenderCounter.addCount(count, false);
- }
- };
- Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
- if (this._updateTransparentDataCounter) {
- this._updateTransparentDataCounter.addCount(count, false);
- }
- };
- Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
- if (this._updateCachedStateCounter) {
- this._updateCachedStateCounter.addCount(count, false);
- }
- };
- Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
- if (this._updateLayoutCounter) {
- this._updateLayoutCounter.addCount(count, false);
- }
- };
- Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
- if (this._updatePositioningCounter) {
- this._updatePositioningCounter.addCount(count, false);
- }
- };
- Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
- if (this._updateLocalTransformCounter) {
- this._updateLocalTransformCounter.addCount(count, false);
- }
- };
- Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
- if (this._updateGlobalTransformCounter) {
- this._updateGlobalTransformCounter.addCount(count, false);
- }
- };
- Canvas2D.prototype.addLayoutBoundingInfoUpdateCounter = function (count) {
- if (this._layoutBoundingInfoUpdateCounter) {
- this._layoutBoundingInfoUpdateCounter.addCount(count, false);
- }
- };
- Canvas2D.prototype._updateTrackedNodes = function () {
- // Get the used camera
- var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
- // Compute some matrix stuff
- cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D_1._m);
- var rh = this.engine.getRenderHeight();
- var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
- var tmpVec3 = Canvas2D_1._tmpVec3;
- var tmpMtx = Canvas2D_1._tmpMtx;
- // Compute the screen position of each group that track a given scene node
- for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
- var group = _a[_i];
- if (group.isDisposed) {
- continue;
- }
- var node = group.trackedNode;
- var worldMtx = node.getWorldMatrix();
- if (group.trackedNodeOffset) {
- BABYLON.Vector3.TransformCoordinatesToRef(group.trackedNodeOffset, worldMtx, tmpVec3);
- tmpMtx.copyFrom(worldMtx);
- worldMtx = tmpMtx;
- worldMtx.setTranslation(tmpVec3);
- }
- var proj = BABYLON.Vector3.Project(Canvas2D_1._v, worldMtx, Canvas2D_1._m, v);
- // Set the visibility state accordingly, if the position is outside the frustum (well on the Z planes only...) set the group to hidden
- group.levelVisible = proj.z >= 0 && proj.z < 1.0;
- var s = this.scale;
- group.x = Math.round(proj.x / s);
- group.y = Math.round((rh - proj.y) / s);
- }
- // If it's a WorldSpaceCanvas and it's tracking a node, let's update the WSC transformation data
- if (this._trackNode) {
- var rot = null;
- var scale = null;
- var worldmtx = this._trackNode.getWorldMatrix();
- var pos = worldmtx.getTranslation().add(this._trackNodeOffset);
- var wsc = this;
- var wsn = wsc.worldSpaceCanvasNode;
- if (this._trackNodeBillboard) {
- var viewMtx = cam.getViewMatrix().clone().invert();
- viewMtx.decompose(Canvas2D_1.tS, Canvas2D_1.tR, Canvas2D_1.tT);
- rot = Canvas2D_1.tR.clone();
- }
- worldmtx.decompose(Canvas2D_1.tS, Canvas2D_1.tR, Canvas2D_1.tT);
- var mtx = BABYLON.Matrix.Compose(Canvas2D_1.tS, Canvas2D_1.tR, BABYLON.Vector3.Zero());
- pos = worldmtx.getTranslation().add(BABYLON.Vector3.TransformCoordinates(this._trackNodeOffset, mtx));
- if (Canvas2D_1.tS.lengthSquared() !== 1) {
- scale = Canvas2D_1.tS.clone();
- }
- if (!this._trackNodeBillboard) {
- rot = Canvas2D_1.tR.clone();
- }
- if (wsn instanceof BABYLON.AbstractMesh) {
- wsn.position = pos;
- wsn.rotationQuaternion = rot;
- if (scale) {
- wsn.scaling = scale;
- }
- }
- else {
- throw new Error("Can't Track another Scene Node Type than AbstractMesh right now, call me lazy!");
- }
- }
- };
- /**
- * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
- */
- Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
- this._updateCanvasState(forceRecompute);
- };
- Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
- if (this._globalTransformStep < 2) {
- return;
- }
- var n = this.worldSpaceCanvasNode;
- var bi = n.getBoundingInfo().boundingBox;
- var v = bi.vectorsWorld;
- var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
- cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D_1._m);
- if (Canvas2D_1._m.m[15] < BABYLON.Epsilon && Canvas2D_1._m.m[15] >= 0) {
- Canvas2D_1._m.m[15] = BABYLON.Epsilon;
- }
- else if (Canvas2D_1._m.m[15] > -BABYLON.Epsilon && Canvas2D_1._m.m[15] <= 0) {
- Canvas2D_1._m.m[15] = -BABYLON.Epsilon;
- }
- var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
- var projPoints = new Array(4);
- for (var i = 0; i < 4; i++) {
- projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D_1._mI, Canvas2D_1._m, vp);
- }
- var left = projPoints[3].subtract(projPoints[0]).length();
- var top = projPoints[3].subtract(projPoints[1]).length();
- var right = projPoints[1].subtract(projPoints[2]).length();
- var bottom = projPoints[2].subtract(projPoints[0]).length();
- var w = Math.round(Math.max(top, bottom));
- var h = Math.round(Math.max(right, left));
- var isW = w > h;
- // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
- var edge = Math.max(w, h);
- if (edge < 256) {
- edge = 256;
- }
- else {
- edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
- }
- // Clip values if needed
- edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize - 4); // -4 is to consider the border of 2 pixels, other we couldn't allocate a rect
- var newScale = edge / ((isW) ? this.size.width : this.size.height);
- if (newScale !== this._renderableData._renderingScale) {
- var scale = newScale;
- //console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
- this._setRenderingScale(scale);
- }
- };
- Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
- // Check if the update has already been made for this render Frame
- if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
- return;
- }
- // Detect a change of HWRendering scale
- var hwsl = this.engine.getHardwareScalingLevel();
- this._curHWScale = hwsl;
- // Detect a change of rendering size
- var renderingSizeChanged = false;
- var newWidth = this.engine.getRenderWidth() * hwsl;
- if (newWidth !== this._renderingSize.width) {
- renderingSizeChanged = true;
- }
- this._renderingSize.width = newWidth;
- var newHeight = this.engine.getRenderHeight() * hwsl;
- if (newHeight !== this._renderingSize.height) {
- renderingSizeChanged = true;
- }
- this._renderingSize.height = newHeight;
- var prevCLS = Canvas2D_1._pCLS;
- prevCLS.copyFrom(this._canvasLevelScale);
- // If there's a design size, update the scale according to the renderingSize
- if (this._designSize) {
- var scale = void 0;
- if (this._designUseHorizAxis) {
- scale = this._renderingSize.width / (this._designSize.width * hwsl);
- }
- else {
- scale = this._renderingSize.height / (this._designSize.height * hwsl);
- }
- this.size = this._designSize.clone();
- this._canvasLevelScale.copyFromFloats(scale, scale);
- }
- else {
- var ratio = 1 / this._curHWScale;
- this._canvasLevelScale.copyFromFloats(ratio, ratio);
- }
- if (!prevCLS.equals(this._canvasLevelScale)) {
- for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
- var child = _a[_i];
- child._setFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
- }
- this._setLayoutDirty();
- }
- // If the canvas fit the rendering size and it changed, update
- if (!this._designSize && renderingSizeChanged && this._fitRenderingDevice) {
- this.size = this._renderingSize.clone();
- if (this._background) {
- this._background.size = this.size;
- }
- // Dirty the Layout at the Canvas level to recompute as the size changed
- this._setLayoutDirty();
- }
- var context = new BABYLON.PrepareRender2DContext();
- ++this._globalTransformProcessStep;
- this._setFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
- this.updateCachedStates(false);
- this._prepareGroupRender(context);
- this._updateRenderId = this.scene.getRenderId();
- };
- /**
- * Method that renders the Canvas, you should not invoke
- */
- Canvas2D.prototype._render = function () {
- this._initPerfMetrics();
- if (this._renderObservable && this._renderObservable.hasObservers()) {
- this._renderObservable.notifyObservers(this, Canvas2D_1.RENDEROBSERVABLE_PRE);
- }
- this._updateTrackedNodes();
- this._updateCanvasState(false);
- // Nothing to do is the Canvas is not visible
- if (this.isVisible === false) {
- return;
- }
- if (!this._isScreenSpace) {
- this._updateAdaptiveSizeWorldCanvas();
- }
- this._updateCanvasState(false);
- if (this._primitiveCollisionManager) {
- this._primitiveCollisionManager._update();
- }
- if (this._primPointerInfo.canvasPointerPos) {
- this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false, false);
- this._updateOverStatus(false);
- }
- this.engine.setState(false, undefined, true);
- this._groupRender();
- if (!this._isScreenSpace) {
- if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
- this.worldSpaceCacheChanged();
- this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
- }
- }
- // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
- if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
- this._cachedCanvasGroup._renderCachedCanvas();
- }
- this._fetchPerfMetrics();
- this._updateProfileCanvas();
- if (this._renderObservable && this._renderObservable.hasObservers()) {
- this._renderObservable.notifyObservers(this, Canvas2D_1.RENDEROBSERVABLE_POST);
- }
- };
- /**
- * Internal method that allocate a cache for the given group.
- * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
- * @param group The group to allocate the cache of.
- * @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.
- */
- Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
- if (useMipMap === void 0) { useMipMap = false; }
- if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
- var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
- var rd = group._renderableData;
- var rs = rd._renderingScale;
- var noResizeScale = rd._noResizeOnScale;
- var isCanvas = parent == null;
- var scale;
- if (noResizeScale) {
- scale = isCanvas ? Canvas2D_1._unS : group.parent.actualScale.multiply(this._canvasLevelScale);
- }
- else {
- scale = group.actualScale.multiply(this._canvasLevelScale);
- }
- scale.x *= rs;
- scale.y *= rs;
- // Determine size
- var size = group.actualSize;
- var scaledSize = new BABYLON.Size(size.width * scale.x, size.height * scale.y);
- var roundedScaledSize = new BABYLON.Size(Math.ceil(scaledSize.width), Math.ceil(scaledSize.height));
- var originalSize = scaledSize.clone();
- if (minSize) {
- roundedScaledSize.width = Math.max(minSize.width, roundedScaledSize.width);
- roundedScaledSize.height = Math.max(minSize.height, roundedScaledSize.height);
- }
- var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
- // Try to find a spot in one of the cached texture
- var res = null;
- var map;
- for (var _i = 0, mapArray_1 = mapArray; _i < mapArray_1.length; _i++) {
- var _map = mapArray_1[_i];
- map = _map;
- var node = map.allocateRect(roundedScaledSize);
- if (node) {
- res = { node: node, texture: map };
- break;
- }
- }
- // Couldn't find a map that could fit the rect, create a new map for it
- if (!res) {
- var mapSize = new BABYLON.Size(Canvas2D_1._groupTextureCacheSize, Canvas2D_1._groupTextureCacheSize);
- // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
- if (roundedScaledSize.width > mapSize.width || roundedScaledSize.height > mapSize.height) {
- mapSize.width = Math.pow(2, Math.ceil(Math.log(roundedScaledSize.width) / Math.log(2)));
- mapSize.height = Math.pow(2, Math.ceil(Math.log(roundedScaledSize.height) / Math.log(2)));
- }
- var id = "groupsMapChache" + this._mapCounter++ + "forCanvas" + this.id;
- map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap, 2);
- map.hasAlpha = true;
- map.anisotropicFilteringLevel = 4;
- mapArray.splice(0, 0, map);
- //let debug = false;
- //if (debug) {
- // let sprite = new Sprite2D(map, { parent: this, x: 10, y: 10, id: "__cachedSpriteOfGroup__Debug", alignToPixel: true });
- //}
- var node = map.allocateRect(roundedScaledSize);
- res = { node: node, texture: map };
- }
- // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
- // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
- if (group !== this || this._isScreenSpace) {
- var node = res.node;
- var pos = Canvas2D_1._cv1;
- node.getInnerPosToRef(pos);
- // 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
- var sprite = void 0;
- if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_CANVAS) {
- if (this._cachedCanvasGroup) {
- this._cachedCanvasGroup.dispose();
- }
- this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
- sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: originalSize, size: size, alignToPixel: true, spriteLocation: pos });
- sprite.zOrder = 1;
- sprite.origin = BABYLON.Vector2.Zero();
- }
- else {
- sprite = new BABYLON.Sprite2D(map, { parent: parent, id: "__cachedSpriteOfGroup__" + group.id, x: group.x, y: group.y, spriteSize: originalSize, size: size, spriteLocation: pos, alignToPixel: true, dontInheritParentScale: true });
- sprite.origin = group.origin.clone();
- sprite.addExternalData("__cachedGroup__", group);
- sprite.pointerEventObservable.add(function (e, s) {
- if (group.pointerEventObservable !== null) {
- group.pointerEventObservable.notifyObservers(e, s.mask);
- }
- });
- res.sprite = sprite;
- }
- if (sprite && noResizeScale) {
- var relScale = isCanvas ? group.actualScale : group.actualScale.divide(group.parent.actualScale);
- sprite.scaleX = relScale.x;
- sprite.scaleY = relScale.y;
- }
- }
- return res;
- };
- /**
- * Internal method used to register a Scene Node to track position for the given group
- * Do not invoke this method, for internal purpose only.
- * @param group the group to track its associated Scene Node
- */
- Canvas2D.prototype._registerTrackedNode = function (group) {
- if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
- return;
- }
- if (!this._trackedGroups) {
- this._trackedGroups = new Array();
- }
- this._trackedGroups.push(group);
- group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
- };
- /**
- * Internal method used to unregister a tracked Scene Node
- * Do not invoke this method, it's for internal purpose only.
- * @param group the group to unregister its tracked Scene Node from.
- */
- Canvas2D.prototype._unregisterTrackedNode = function (group) {
- if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
- return;
- }
- var i = this._trackedGroups.indexOf(group);
- if (i !== -1) {
- this._trackedGroups.splice(i, 1);
- }
- group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
- };
- /**
- * Get a Solid Color Brush instance matching the given color.
- * @param color The color to retrieve
- * @return A shared instance of the SolidColorBrush2D class that use the given color
- */
- Canvas2D.GetSolidColorBrush = function (color) {
- return Canvas2D_1._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
- };
- /**
- * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
- * @param color The color to retrieve
- * @return A shared instance of the SolidColorBrush2D class that uses the given color
- */
- Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
- return Canvas2D_1._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
- };
- /**
- * Get a Gradient Color Brush
- * @param color1 starting color
- * @param color2 engine color
- * @param translation translation vector to apply. default is [0;0]
- * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
- * @param scale scaling factor to apply. default is 1.
- */
- Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
- if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
- if (rotation === void 0) { rotation = 0; }
- if (scale === void 0) { scale = 1; }
- return Canvas2D_1._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
- };
- /**
- * Create a solid or gradient brush from a string value.
- * @param brushString should be either
- * - "solid: #RRGGBBAA" or "#RRGGBBAA"
- * - "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.
- */
- Canvas2D.GetBrushFromString = function (brushString) {
- // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
- brushString = brushString.trim();
- var split = brushString.split(",");
- // Solid, formatted as: "[solid:]#FF808080"
- if (split.length === 1) {
- var value = null;
- if (brushString.indexOf("solid:") === 0) {
- value = brushString.substr(6).trim();
- }
- else if (brushString.indexOf("#") === 0) {
- value = brushString;
- }
- else {
- return null;
- }
- return Canvas2D_1.GetSolidColorBrushFromHex(value);
- }
- else {
- if (split[0].indexOf("gradient:") === 0) {
- split[0] = split[0].substr(9).trim();
- }
- try {
- var start = BABYLON.Color4.FromHexString(split[0].trim());
- var end = BABYLON.Color4.FromHexString(split[1].trim());
- var t = BABYLON.Vector2.Zero();
- if (split.length > 2) {
- var v = split[2].trim();
- if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
- return null;
- }
- var sep = v.indexOf(":");
- var x = parseFloat(v.substr(1, sep));
- var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
- t = new BABYLON.Vector2(x, y);
- }
- var r = 0;
- if (split.length > 3) {
- r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
- }
- var s = 1;
- if (split.length > 4) {
- s = parseFloat(split[4].trim());
- }
- return Canvas2D_1.GetGradientColorBrush(start, end, t, r, s);
- }
- catch (e) {
- return null;
- }
- }
- };
- return Canvas2D;
- }(BABYLON.Group2D));
- /**
- * 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.
- * This strategy doesn't allow primitives added directly as children of the Canvas.
- * 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.
- */
- Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
- /**
- * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
- * 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.
- * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
- * 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.
- */
- Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
- /**
- * 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).
- */
- Canvas2D.CACHESTRATEGY_CANVAS = 3;
- /**
- * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
- * 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).
- * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
- */
- Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
- /**
- * Observable Mask to be notified before rendering is made
- */
- Canvas2D.RENDEROBSERVABLE_PRE = 1;
- /**
- * Observable Mask to be notified after rendering is made
- */
- Canvas2D.RENDEROBSERVABLE_POST = 2;
- Canvas2D._INSTANCES = [];
- Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
- Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
- Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
- Canvas2D._cv1 = BABYLON.Vector2.Zero(); // Must stay zero
- Canvas2D._m = BABYLON.Matrix.Identity();
- Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
- Canvas2D.tS = BABYLON.Vector3.Zero();
- Canvas2D.tT = BABYLON.Vector3.Zero();
- Canvas2D.tR = BABYLON.Quaternion.Identity();
- Canvas2D._tmpMtx = BABYLON.Matrix.Identity();
- Canvas2D._tmpVec3 = BABYLON.Vector3.Zero();
- Canvas2D._pCLS = BABYLON.Vector2.Zero();
- /**
- * Define the default size used for both the width and height of a MapTexture to allocate.
- * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
- */
- Canvas2D._groupTextureCacheSize = 1024;
- Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
- Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
- __decorate([
- BABYLON.logMethod("==========CANVAS RENDER===============")
- ], Canvas2D.prototype, "_render", null);
- Canvas2D = Canvas2D_1 = __decorate([
- BABYLON.className("Canvas2D", "BABYLON")
- /**
- * The Canvas2D main class.
- * This class is extended in both ScreenSpaceCanvas2D and WorldSpaceCanvas2D which are designed only for semantic use.
- * User creates a Screen or WorldSpace canvas which is a 2D surface area that will draw the primitives that were added as children.
- */
- ], Canvas2D);
- BABYLON.Canvas2D = Canvas2D;
- var WorldSpaceCanvas2D = (function (_super) {
- __extends(WorldSpaceCanvas2D, _super);
- /**
- * 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.
- * 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.
- * @param scene the Scene that owns the Canvas
- * @param size the dimension of the Canvas in World Space
- * @param settings a combination of settings, possible ones are
- * - children: an array of direct children primitives
- * - id: a text identifier, for information purpose only, default is null.
- * - 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).
- * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
- * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
- * - 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
- * - trackNodeOffset: if you use trackNode you may want to specify a 3D Offset to apply to shift the Canvas
- * - trackNodeBillboard: if true the WorldSpaceCanvas will always face the screen
- * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
- * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
- * - 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).
- * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
- * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
- * - 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.
- * - 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.
- * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
- * - 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.
- * - 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.
- * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
- * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
- */
- function WorldSpaceCanvas2D(scene, size, settings) {
- var _this = this;
- BABYLON.Prim2DBase._isCanvasInit = true;
- var s = settings;
- s.isScreenSpace = false;
- if (settings.unitScaleFactor != null) {
- s.size = size.multiplyByFloats(settings.unitScaleFactor, settings.unitScaleFactor);
- }
- else {
- s.size = size.clone();
- }
- settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
- if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
- throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
- }
- _this = _super.call(this, scene, settings) || this;
- BABYLON.Prim2DBase._isCanvasInit = false;
- _this._unitScaleFactor = (settings.unitScaleFactor != null) ? settings.unitScaleFactor : 1;
- _this._renderableData._useMipMap = true;
- _this._renderableData._anisotropicLevel = 8;
- //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
- // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
- //}
- _this._trackNode = (settings.trackNode != null) ? settings.trackNode : null;
- _this._trackNodeOffset = (settings.trackNodeOffset != null) ? settings.trackNodeOffset : BABYLON.Vector3.Zero();
- _this._trackNodeBillboard = (settings.trackNodeBillboard != null) ? settings.trackNodeBillboard : true;
- var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
- _this._customWorldSpaceNode = !createWorldSpaceNode;
- var id = settings ? settings.id || null : null;
- // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
- var capMaxTextSize = _this.engine.getCaps().maxRenderTextureSize;
- var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 1K if allowed otherwise the max allowed
- if (settings.maxAdaptiveCanvasSize == null) {
- _this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
- }
- else {
- // We still clip the given value with the max allowed, the user may not be aware of these limitations
- _this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
- }
- if (createWorldSpaceNode) {
- var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, _this);
- var vertexData = BABYLON.VertexData.CreatePlane({
- width: size.width,
- height: size.height,
- sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
- });
- var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
- _this.applyCachedTexture(vertexData, mtl);
- vertexData.applyToMesh(plane, true);
- mtl.specularColor = new BABYLON.Color3(0, 0, 0);
- mtl.disableLighting = true;
- mtl.useAlphaFromDiffuseTexture = true;
- if (settings && settings.sideOrientation) {
- mtl.backFaceCulling = (settings.sideOrientation === BABYLON.Mesh.DEFAULTSIDE || settings.sideOrientation === BABYLON.Mesh.FRONTSIDE);
- }
- plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
- plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
- plane.material = mtl;
- _this._worldSpaceNode = plane;
- }
- else {
- _this._worldSpaceNode = settings.customWorldSpaceNode;
- _this.applyCachedTexture(null, null);
- }
- _this.propertyChanged.add(function (e, st) {
- if (e.propertyName !== "isVisible") {
- return;
- }
- var mesh = _this._worldSpaceNode;
- if (mesh) {
- mesh.isVisible = e.newValue;
- }
- }, BABYLON.Prim2DBase.isVisibleProperty.flagId);
- return _this;
- }
- WorldSpaceCanvas2D.prototype.dispose = function () {
- if (!_super.prototype.dispose.call(this)) {
- return false;
- }
- if (!this._customWorldSpaceNode && this._worldSpaceNode) {
- this._worldSpaceNode.dispose();
- this._worldSpaceNode = null;
- }
- };
- Object.defineProperty(WorldSpaceCanvas2D.prototype, "trackNode", {
- get: function () {
- return this._trackNode;
- },
- set: function (value) {
- if (this._trackNode === value) {
- return;
- }
- this._trackNode = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(WorldSpaceCanvas2D.prototype, "trackNodeOffset", {
- get: function () {
- return this._trackNodeOffset;
- },
- set: function (value) {
- if (!this._trackNodeOffset) {
- this._trackNodeOffset = value.clone();
- }
- else {
- this._trackNodeOffset.copyFrom(value);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(WorldSpaceCanvas2D.prototype, "trackNodeBillboard", {
- get: function () {
- return this._trackNodeBillboard;
- },
- set: function (value) {
- this._trackNodeBillboard = value;
- },
- enumerable: true,
- configurable: true
- });
- return WorldSpaceCanvas2D;
- }(Canvas2D));
- WorldSpaceCanvas2D = __decorate([
- BABYLON.className("WorldSpaceCanvas2D", "BABYLON")
- /**
- * Class to create a WorldSpace Canvas2D.
- */
- ], WorldSpaceCanvas2D);
- BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
- var ScreenSpaceCanvas2D = (function (_super) {
- __extends(ScreenSpaceCanvas2D, _super);
- /**
- * 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.
- * 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.
- * All caching strategies will be available.
- * 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]
- * @param scene the Scene that owns the Canvas
- * @param settings a combination of settings, possible ones are
- * - children: an array of direct children primitives
- * - id: a text identifier, for information purpose only
- * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
- * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
- * - 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]
- * - width: the width of the Canvas. you can alternatively use the size setting.
- * - height: the height of the Canvas. you can alternatively use the size setting.
- * - 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
- * - 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.
- * - 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.
- * - 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.
- * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
- * - 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.
- * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
- * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
- * - 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.
- * - 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.
- * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
- * - 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.
- * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
- * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
- * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
- * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
- * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
- */
- function ScreenSpaceCanvas2D(scene, settings) {
- var _this = this;
- BABYLON.Prim2DBase._isCanvasInit = true;
- _this = _super.call(this, scene, settings) || this;
- return _this;
- }
- return ScreenSpaceCanvas2D;
- }(Canvas2D));
- ScreenSpaceCanvas2D = __decorate([
- BABYLON.className("ScreenSpaceCanvas2D", "BABYLON")
- /**
- * Class to create a ScreenSpace Canvas2D
- */
- ], ScreenSpaceCanvas2D);
- BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
- var Canvas2D_1;
- })(BABYLON || (BABYLON = {}));
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var BABYLON;
- (function (BABYLON) {
- /**
- * This is the class that is used to display a World Space Canvas into a 3D scene
- */
- var WorldSpaceCanvas2DNode = (function (_super) {
- __extends(WorldSpaceCanvas2DNode, _super);
- function WorldSpaceCanvas2DNode(name, scene, canvas) {
- var _this = _super.call(this, name, scene) || this;
- _this._canvas = canvas;
- return _this;
- }
- WorldSpaceCanvas2DNode.prototype.dispose = function () {
- _super.prototype.dispose.call(this);
- if (this._canvas) {
- this._canvas.dispose();
- this._canvas = null;
- }
- };
- return WorldSpaceCanvas2DNode;
- }(BABYLON.Mesh));
- BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
- })(BABYLON || (BABYLON = {}));
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var Command = (function () {
- function Command(execute, canExecute) {
- if (!execute) {
- throw Error("At least an execute lambda must be given at Command creation time");
- }
- this._canExecuteChanged = null;
- this._lastCanExecuteResult = null;
- this.execute = execute;
- this.canExecute = canExecute;
- }
- Command.prototype.canExecute = function (parameter) {
- var res = true;
- if (this._canExecute) {
- res = this._canExecute(parameter);
- }
- if (res !== this._lastCanExecuteResult) {
- if (this._canExecuteChanged && this._canExecuteChanged.hasObservers()) {
- this._canExecuteChanged.notifyObservers(null);
- }
- this._lastCanExecuteResult = res;
- }
- return res;
- };
- Command.prototype.execute = function (parameter) {
- this._execute(parameter);
- };
- Object.defineProperty(Command.prototype, "canExecuteChanged", {
- get: function () {
- if (!this._canExecuteChanged) {
- this._canExecuteChanged = new BABYLON.Observable();
- }
- return this._canExecuteChanged;
- },
- enumerable: true,
- configurable: true
- });
- return Command;
- }());
- BABYLON.Command = Command;
- var UIElement = (function (_super) {
- __extends(UIElement, _super);
- function UIElement(settings) {
- var _this = _super.call(this) || this;
- if (!settings) {
- throw Error("A settings object must be passed with at least either a parent or owner parameter");
- }
- var type = BABYLON.Tools.getFullClassName(_this);
- _this._ownerWindow = null;
- _this._parent = null;
- _this._visualPlaceholder = null;
- _this._visualTemplateRoot = null;
- _this._visualChildrenPlaceholder = null;
- _this._hierarchyDepth = 0;
- _this._renderingTemplateName = (settings.templateName != null) ? settings.templateName : GUIManager.DefaultTemplateName;
- _this._style = (settings.styleName != null) ? GUIManager.getStyle(type, settings.styleName) : null;
- _this._flags = 0;
- _this._id = (settings.id != null) ? settings.id : null;
- _this._uid = null;
- _this._width = (settings.width != null) ? settings.width : null;
- _this._height = (settings.height != null) ? settings.height : null;
- _this._minWidth = (settings.minWidth != null) ? settings.minWidth : 0;
- _this._minHeight = (settings.minHeight != null) ? settings.minHeight : 0;
- _this._maxWidth = (settings.maxWidth != null) ? settings.maxWidth : Number.MAX_VALUE;
- _this._maxHeight = (settings.maxHeight != null) ? settings.maxHeight : Number.MAX_VALUE;
- _this._margin = null;
- _this._padding = null;
- _this._marginAlignment = null;
- _this._setFlags(UIElement.flagIsVisible | UIElement.flagIsEnabled);
- // Default Margin Alignment for UIElement is stretch for horizontal/vertical and not left/bottom (which is the default for Canvas2D Primitives)
- //this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
- //this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
- // Set the layout/margin stuffs
- if (settings.marginTop) {
- _this.margin.setTop(settings.marginTop);
- }
- if (settings.marginLeft) {
- _this.margin.setLeft(settings.marginLeft);
- }
- if (settings.marginRight) {
- _this.margin.setRight(settings.marginRight);
- }
- if (settings.marginBottom) {
- _this.margin.setBottom(settings.marginBottom);
- }
- if (settings.margin) {
- if (typeof settings.margin === "string") {
- _this.margin.fromString(settings.margin);
- }
- else {
- _this.margin.fromUniformPixels(settings.margin);
- }
- }
- if (settings.marginHAlignment) {
- _this.marginAlignment.horizontal = settings.marginHAlignment;
- }
- if (settings.marginVAlignment) {
- _this.marginAlignment.vertical = settings.marginVAlignment;
- }
- if (settings.marginAlignment) {
- _this.marginAlignment.fromString(settings.marginAlignment);
- }
- if (settings.paddingTop) {
- _this.padding.setTop(settings.paddingTop);
- }
- if (settings.paddingLeft) {
- _this.padding.setLeft(settings.paddingLeft);
- }
- if (settings.paddingRight) {
- _this.padding.setRight(settings.paddingRight);
- }
- if (settings.paddingBottom) {
- _this.padding.setBottom(settings.paddingBottom);
- }
- if (settings.padding) {
- _this.padding.fromString(settings.padding);
- }
- if (settings.paddingHAlignment) {
- _this.paddingAlignment.horizontal = settings.paddingHAlignment;
- }
- if (settings.paddingVAlignment) {
- _this.paddingAlignment.vertical = settings.paddingVAlignment;
- }
- if (settings.paddingAlignment) {
- _this.paddingAlignment.fromString(settings.paddingAlignment);
- }
- if (settings.parent != null) {
- _this._parent = settings.parent;
- _this._hierarchyDepth = _this._parent._hierarchyDepth + 1;
- }
- return _this;
- }
- Object.defineProperty(UIElement, "enabledState", {
- get: function () {
- return UIElement._enableState;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement, "disabledState", {
- get: function () {
- return UIElement._disabledState;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement, "mouseOverState", {
- get: function () {
- return UIElement._mouseOverState;
- },
- enumerable: true,
- configurable: true
- });
- UIElement.prototype.dispose = function () {
- if (this.isDisposed) {
- return false;
- }
- if (this._renderingTemplate) {
- this._renderingTemplate.detach();
- this._renderingTemplate = null;
- }
- _super.prototype.dispose.call(this);
- // Don't set to null, it may upset somebody...
- this.animations.splice(0);
- return true;
- };
- /**
- * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
- * Look at Sprite2D for more information
- */
- UIElement.prototype.getAnimatables = function () {
- return new Array();
- };
- // TODO
- // PROPERTIES
- // Style
- // Id
- // Parent/Children
- // ActualWidth/Height, MinWidth/Height, MaxWidth/Height,
- // Alignment/Margin
- // Visibility, IsVisible
- // IsEnabled (is false, control is disabled, no interaction and a specific render state)
- // CacheMode of Visual Elements
- // Focusable/IsFocused
- // IsPointerCaptured, CapturePointer, IsPointerDirectlyOver, IsPointerOver. De-correlate mouse, stylus, touch?
- // ContextMenu
- // Cursor
- // DesiredSize
- // IsInputEnable ?
- // Opacity, OpacityMask ?
- // SnapToDevicePixels
- // Tag
- // ToolTip
- // METHODS
- // BringIntoView (for scrollable content, to move the scroll to bring the given element visible in the parent's area)
- // Capture/ReleaseCapture (mouse, touch, stylus)
- // Focus
- // PointFrom/ToScreen to translate coordinates
- // EVENTS
- // ContextMenuOpening/Closing/Changed
- // DragEnter/LeaveOver, Drop
- // Got/LostFocus
- // IsEnabledChanged
- // IsPointerOver/DirectlyOverChanged
- // IsVisibleChanged
- // KeyDown/Up
- // LayoutUpdated ?
- // Pointer related events
- // SizeChanged
- // ToolTipOpening/Closing
- UIElement.prototype.findById = function (id) {
- if (this._id === id) {
- return this;
- }
- var children = this._getChildren();
- for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
- var child = children_1[_i];
- var r = child.findById(id);
- if (r != null) {
- return r;
- }
- }
- };
- Object.defineProperty(UIElement.prototype, "ownerWindow", {
- get: function () {
- return this._ownerWindow;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "style", {
- get: function () {
- if (!this.style) {
- return GUIManager.DefaultStyleName;
- }
- return this._style.name;
- },
- set: function (value) {
- if (this._style && (this._style.name === value)) {
- return;
- }
- var newStyle = null;
- if (value) {
- newStyle = GUIManager.getStyle(BABYLON.Tools.getFullClassName(this), value);
- if (!newStyle) {
- throw Error("Couldn't find Style " + value + " for UIElement " + BABYLON.Tools.getFullClassName(this));
- }
- }
- if (this._style) {
- this._style.removeStyle(this);
- }
- if (newStyle) {
- newStyle.applyStyle(this);
- }
- this._style = newStyle;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "id", {
- /**
- * A string that identifies the UIElement.
- * The id is optional and there's possible collision with other UIElement's id as the uniqueness is not supported.
- */
- get: function () {
- return this._id;
- },
- set: function (value) {
- if (this._id === value) {
- return;
- }
- this._id = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "uid", {
- /**
- * Return a unique id automatically generated.
- * This property is mainly used for serialization to ensure a perfect way of identifying a UIElement
- */
- get: function () {
- if (!this._uid) {
- this._uid = BABYLON.Tools.RandomId();
- }
- return this._uid;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "hierarchyDepth", {
- get: function () {
- return this._hierarchyDepth;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "parent", {
- get: function () {
- return this._parent;
- },
- set: function (value) {
- this._parent = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "width", {
- get: function () {
- return this._width;
- },
- set: function (value) {
- this._width = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "height", {
- get: function () {
- return this._height;
- },
- set: function (value) {
- this._height = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "minWidth", {
- get: function () {
- return this._minWidth;
- },
- set: function (value) {
- this._minWidth = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "minHheight", {
- get: function () {
- return this._minHeight;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "minHeight", {
- set: function (value) {
- this._minHeight = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "maxWidth", {
- get: function () {
- return this._maxWidth;
- },
- set: function (value) {
- this._maxWidth = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "maxHeight", {
- get: function () {
- return this._maxHeight;
- },
- set: function (value) {
- this._maxHeight = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "actualWidth", {
- get: function () {
- return this._actualWidth;
- },
- set: function (value) {
- this._actualWidth = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "actualHeight", {
- get: function () {
- return this._actualHeight;
- },
- set: function (value) {
- this._actualHeight = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "margin", {
- get: function () {
- var _this = this;
- if (!this._margin) {
- this._margin = new BABYLON.PrimitiveThickness(function () {
- if (!_this.parent) {
- return null;
- }
- return _this.parent.margin;
- });
- }
- return this._margin;
- },
- set: function (value) {
- this.margin.copyFrom(value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "_hasMargin", {
- get: function () {
- return (this._margin !== null && !this._margin.isDefault) || (this._marginAlignment !== null && !this._marginAlignment.isDefault);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "padding", {
- get: function () {
- var _this = this;
- if (!this._padding) {
- this._padding = new BABYLON.PrimitiveThickness(function () {
- if (!_this.parent) {
- return null;
- }
- return _this.parent.padding;
- });
- }
- return this._padding;
- },
- set: function (value) {
- this.padding.copyFrom(value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "_hasPadding", {
- get: function () {
- return this._padding !== null && !this._padding.isDefault;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "marginAlignment", {
- get: function () {
- if (!this._marginAlignment) {
- this._marginAlignment = new BABYLON.PrimitiveAlignment();
- }
- return this._marginAlignment;
- },
- set: function (value) {
- this.marginAlignment.copyFrom(value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "_hasMarginAlignment", {
- /**
- * Check if there a marginAlignment specified (non null and not default)
- */
- get: function () {
- return (this._marginAlignment !== null && !this._marginAlignment.isDefault);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "paddingAlignment", {
- get: function () {
- if (!this._paddingAlignment) {
- this._paddingAlignment = new BABYLON.PrimitiveAlignment();
- }
- return this._paddingAlignment;
- },
- set: function (value) {
- this.paddingAlignment.copyFrom(value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "_hasPaddingAlignment", {
- /**
- * Check if there a marginAlignment specified (non null and not default)
- */
- get: function () {
- return (this._paddingAlignment !== null && !this._paddingAlignment.isDefault);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "isVisible", {
- get: function () {
- return this._isFlagSet(UIElement.flagIsVisible);
- },
- set: function (value) {
- if (this.isVisible === value) {
- return;
- }
- this._visualPlaceholder.levelVisible = value;
- this._changeFlags(UIElement.flagIsVisible, value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "isEnabled", {
- get: function () {
- return this._isFlagSet(UIElement.flagIsEnabled);
- },
- set: function (value) {
- this._changeFlags(UIElement.flagIsEnabled, value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "isFocused", {
- get: function () {
- return this._isFlagSet(UIElement.flagIsFocus);
- },
- set: function (value) {
- // If the UIElement doesn't accept focus, set it on its parent
- if (!this.isFocusable) {
- var p = this.parent;
- if (!p) {
- return;
- }
- p.isFocused = value;
- }
- // If the focus is being set, notify the Focus Manager
- if (value) {
- this.ownerWindow.focusManager.setFocusOn(this, this.getFocusScope());
- }
- this._changeFlags(UIElement.flagIsFocus, value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "isMouseOver", {
- get: function () {
- return this._isFlagSet(UIElement.flagIsMouseOver);
- },
- set: function (value) {
- this._changeFlags(UIElement.flagIsMouseOver, value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "isFocusScope", {
- get: function () {
- return this._isFlagSet(UIElement.flagIsFocusScope);
- },
- set: function (value) {
- this._changeFlags(UIElement.flagIsFocusScope, value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "isFocusable", {
- get: function () {
- return this._isFlagSet(UIElement.flagIsFocusable);
- },
- set: function (value) {
- this._changeFlags(UIElement.flagIsFocusable, value);
- },
- enumerable: true,
- configurable: true
- });
- // 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)
- UIElement.prototype.getFocusScope = function () {
- if (this.isFocusScope) {
- return this;
- }
- var p = this.parent;
- if (!p) {
- return null;
- }
- return p.getFocusScope();
- };
- /**
- * Check if a given flag is set
- * @param flag the flag value
- * @return true if set, false otherwise
- */
- UIElement.prototype._isFlagSet = function (flag) {
- return (this._flags & flag) !== 0;
- };
- /**
- * Check if all given flags are set
- * @param flags the flags ORed
- * @return true if all the flags are set, false otherwise
- */
- UIElement.prototype._areAllFlagsSet = function (flags) {
- return (this._flags & flags) === flags;
- };
- /**
- * Check if at least one flag of the given flags is set
- * @param flags the flags ORed
- * @return true if at least one flag is set, false otherwise
- */
- UIElement.prototype._areSomeFlagsSet = function (flags) {
- return (this._flags & flags) !== 0;
- };
- /**
- * Clear the given flags
- * @param flags the flags to clear
- */
- UIElement.prototype._clearFlags = function (flags) {
- this._flags &= ~flags;
- };
- /**
- * Set the given flags to true state
- * @param flags the flags ORed to set
- * @return the flags state before this call
- */
- UIElement.prototype._setFlags = function (flags) {
- var cur = this._flags;
- this._flags |= flags;
- return cur;
- };
- /**
- * Change the state of the given flags
- * @param flags the flags ORed to change
- * @param state true to set them, false to clear them
- */
- UIElement.prototype._changeFlags = function (flags, state) {
- if (state) {
- this._flags |= flags;
- }
- else {
- this._flags &= ~flags;
- }
- };
- UIElement.prototype._assignTemplate = function (templateName) {
- if (!templateName) {
- templateName = GUIManager.DefaultTemplateName;
- }
- var className = BABYLON.Tools.getFullClassName(this);
- if (!className) {
- throw Error("Couldn't access class name of this UIElement, you have to decorate the type with the className decorator");
- }
- var factory = GUIManager.getRenderingTemplate(className, templateName);
- if (!factory) {
- throw Error("Couldn't get the renderingTemplate " + templateName + " of class " + className);
- }
- this._renderingTemplateName = templateName;
- this._renderingTemplate = factory();
- this._renderingTemplate.attach(this);
- };
- UIElement.prototype._createVisualTree = function () {
- var parentPrim = this.ownerWindow.canvas;
- if (this.parent) {
- parentPrim = this.parent.visualChildrenPlaceholder;
- }
- if (!this._renderingTemplate) {
- this._assignTemplate(this._renderingTemplateName);
- }
- this._visualPlaceholder = new BABYLON.Group2D({ parent: parentPrim, id: "GUI " + BABYLON.Tools.getClassName(this) + " RootGroup of " + this.id });
- var p = this._visualPlaceholder;
- p.addExternalData("_GUIOwnerElement_", this);
- p.dataSource = this;
- p.createSimpleDataBinding(BABYLON.Prim2DBase.widthProperty, "width", BABYLON.DataBinding.MODE_ONEWAY);
- p.createSimpleDataBinding(BABYLON.Prim2DBase.heightProperty, "height", BABYLON.DataBinding.MODE_ONEWAY);
- p.createSimpleDataBinding(BABYLON.Prim2DBase.actualWidthProperty, "actualWidth", BABYLON.DataBinding.MODE_ONEWAYTOSOURCE);
- p.createSimpleDataBinding(BABYLON.Prim2DBase.actualHeightProperty, "actualHeight", BABYLON.DataBinding.MODE_ONEWAYTOSOURCE);
- p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "margin", BABYLON.DataBinding.MODE_ONEWAY);
- p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "marginAlignment", BABYLON.DataBinding.MODE_ONEWAY);
- this.createVisualTree();
- };
- UIElement.prototype._patchUIElement = function (ownerWindow, parent) {
- if (ownerWindow) {
- if (!this._ownerWindow) {
- ownerWindow._registerVisualToBuild(this);
- }
- this._ownerWindow = ownerWindow;
- }
- this._parent = parent;
- if (parent) {
- this._hierarchyDepth = parent.hierarchyDepth + 1;
- }
- var children = this._getChildren();
- if (children) {
- for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
- var curChild = children_2[_i];
- curChild._patchUIElement(ownerWindow, this);
- }
- }
- };
- // 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.
- UIElement.prototype._getDataSource = function () {
- var levelDS = _super.prototype._getDataSource.call(this);
- if (levelDS != null) {
- return levelDS;
- }
- var p = this.parent;
- if (p != null) {
- return p.dataSource;
- }
- return null;
- };
- UIElement.prototype.createVisualTree = function () {
- var res = this._renderingTemplate.createVisualTree(this, this._visualPlaceholder);
- this._visualTemplateRoot = res.root;
- this._visualChildrenPlaceholder = res.contentPlaceholder;
- };
- Object.defineProperty(UIElement.prototype, "visualPlaceholder", {
- get: function () {
- return this._visualPlaceholder;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "visualTemplateRoot", {
- get: function () {
- return this._visualTemplateRoot;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "visualChildrenPlaceholder", {
- get: function () {
- return this._visualChildrenPlaceholder;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UIElement.prototype, "_position", {
- get: function () { return null; } // TODO use abstract keyword when TS 2.0 will be approved
- ,
- enumerable: true,
- configurable: true
- });
- return UIElement;
- }(BABYLON.SmartPropertyBase));
- UIElement.UIELEMENT_PROPCOUNT = 16;
- UIElement.flagVisualToBuild = 0x0000001;
- UIElement.flagIsVisible = 0x0000002;
- UIElement.flagIsFocus = 0x0000004;
- UIElement.flagIsFocusScope = 0x0000008;
- UIElement.flagIsFocusable = 0x0000010;
- UIElement.flagIsEnabled = 0x0000020;
- UIElement.flagIsMouseOver = 0x0000040;
- UIElement._enableState = "Enabled";
- UIElement._disabledState = "Disabled";
- UIElement._mouseOverState = "MouseOver";
- __decorate([
- BABYLON.dependencyProperty(0, function (pi) { return UIElement.parentProperty = pi; })
- ], UIElement.prototype, "parent", null);
- __decorate([
- BABYLON.dependencyProperty(1, function (pi) { return UIElement.widthProperty = pi; })
- ], UIElement.prototype, "width", null);
- __decorate([
- BABYLON.dependencyProperty(2, function (pi) { return UIElement.heightProperty = pi; })
- ], UIElement.prototype, "height", null);
- __decorate([
- BABYLON.dependencyProperty(3, function (pi) { return UIElement.minWidthProperty = pi; })
- ], UIElement.prototype, "minWidth", null);
- __decorate([
- BABYLON.dependencyProperty(4, function (pi) { return UIElement.minHeightProperty = pi; })
- ], UIElement.prototype, "minHheight", null);
- __decorate([
- BABYLON.dependencyProperty(5, function (pi) { return UIElement.maxWidthProperty = pi; })
- ], UIElement.prototype, "maxWidth", null);
- __decorate([
- BABYLON.dependencyProperty(6, function (pi) { return UIElement.maxHeightProperty = pi; })
- ], UIElement.prototype, "maxHeight", null);
- __decorate([
- BABYLON.dependencyProperty(7, function (pi) { return UIElement.actualWidthProperty = pi; })
- ], UIElement.prototype, "actualWidth", null);
- __decorate([
- BABYLON.dependencyProperty(8, function (pi) { return UIElement.actualHeightProperty = pi; })
- ], UIElement.prototype, "actualHeight", null);
- __decorate([
- BABYLON.dynamicLevelProperty(9, function (pi) { return UIElement.marginProperty = pi; })
- /**
- * You can get/set a margin on the primitive through this property
- * @returns the margin object, if there was none, a default one is created and returned
- */
- ], UIElement.prototype, "margin", null);
- __decorate([
- BABYLON.dynamicLevelProperty(10, function (pi) { return UIElement.paddingProperty = pi; })
- /**
- * You can get/set a margin on the primitive through this property
- * @returns the margin object, if there was none, a default one is created and returned
- */
- ], UIElement.prototype, "padding", null);
- __decorate([
- BABYLON.dynamicLevelProperty(11, function (pi) { return UIElement.marginAlignmentProperty = pi; })
- /**
- * You can get/set the margin alignment through this property
- */
- ], UIElement.prototype, "marginAlignment", null);
- __decorate([
- BABYLON.dynamicLevelProperty(12, function (pi) { return UIElement.paddingAlignmentProperty = pi; })
- /**
- * You can get/set the margin alignment through this property
- */
- ], UIElement.prototype, "paddingAlignment", null);
- __decorate([
- BABYLON.dynamicLevelProperty(13, function (pi) { return UIElement.isEnabledProperty = pi; })
- /**
- * True if the UIElement is enabled, false if it's disabled.
- * User interaction is not possible if the UIElement is not enabled
- */
- ], UIElement.prototype, "isEnabled", null);
- __decorate([
- BABYLON.dynamicLevelProperty(14, function (pi) { return UIElement.isFocusedProperty = pi; })
- /**
- * True if the UIElement has the focus, false if it doesn't
- */
- ], UIElement.prototype, "isFocused", null);
- __decorate([
- BABYLON.dynamicLevelProperty(15, function (pi) { return UIElement.isMouseOverProperty = pi; })
- /**
- * True if the UIElement has the mouse over it
- */
- ], UIElement.prototype, "isMouseOver", null);
- BABYLON.UIElement = UIElement;
- var UIElementStyle = (function () {
- function UIElementStyle() {
- }
- Object.defineProperty(UIElementStyle.prototype, "name", {
- get: function () { return null; } // TODO use abstract keyword when TS 2.0 will be approved
- ,
- enumerable: true,
- configurable: true
- });
- return UIElementStyle;
- }());
- BABYLON.UIElementStyle = UIElementStyle;
- var GUIManager = (function () {
- function GUIManager() {
- }
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- // DATA TEMPLATE MANAGER
- GUIManager.registerDataTemplate = function (className, factory) {
- };
- // DATA TEMPLATE MANAGER
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- // STYLE MANAGER
- GUIManager.getStyle = function (uiElType, styleName) {
- var styles = GUIManager.stylesByUIElement.get(uiElType);
- if (!styles) {
- throw Error("The type " + uiElType + " is unknown, no style were registered for it.");
- }
- var style = styles.get(styleName);
- if (!style) {
- throw Error("Couldn't find Template " + styleName + " of UIElement type " + uiElType);
- }
- return style;
- };
- GUIManager.registerStyle = function (uiElType, templateName, style) {
- var templates = GUIManager.stylesByUIElement.getOrAddWithFactory(uiElType, function () { return new BABYLON.StringDictionary(); });
- if (templates.contains(templateName)) {
- templates[templateName] = style;
- }
- else {
- templates.add(templateName, style);
- }
- };
- Object.defineProperty(GUIManager, "DefaultStyleName", {
- get: function () {
- return GUIManager._defaultStyleName;
- },
- set: function (value) {
- GUIManager._defaultStyleName = value;
- },
- enumerable: true,
- configurable: true
- });
- // STYLE MANAGER
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- // RENDERING TEMPLATE MANAGER
- GUIManager.getRenderingTemplate = function (uiElType, templateName) {
- var templates = GUIManager.renderingTemplatesByUIElement.get(uiElType);
- if (!templates) {
- throw Error("The type " + uiElType + " is unknown, no Rendering Template were registered for it.");
- }
- var templateFactory = templates.get(templateName);
- if (!templateFactory) {
- throw Error("Couldn't find Template " + templateName + " of UI Element type " + uiElType);
- }
- return templateFactory;
- };
- GUIManager.registerRenderingTemplate = function (uiElType, templateName, factory) {
- var templates = GUIManager.renderingTemplatesByUIElement.getOrAddWithFactory(uiElType, function () { return new BABYLON.StringDictionary(); });
- if (templates.contains(templateName)) {
- templates[templateName] = factory;
- }
- else {
- templates.add(templateName, factory);
- }
- };
- Object.defineProperty(GUIManager, "DefaultTemplateName", {
- get: function () {
- return GUIManager._defaultTemplateName;
- },
- set: function (value) {
- GUIManager._defaultTemplateName = value;
- },
- enumerable: true,
- configurable: true
- });
- return GUIManager;
- }());
- GUIManager.stylesByUIElement = new BABYLON.StringDictionary();
- GUIManager.renderingTemplatesByUIElement = new BABYLON.StringDictionary();
- // RENDERING TEMPLATE MANAGER
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- GUIManager._defaultTemplateName = "Default";
- GUIManager._defaultStyleName = "Default";
- BABYLON.GUIManager = GUIManager;
- var UIElementRenderingTemplateBase = (function () {
- function UIElementRenderingTemplateBase() {
- }
- UIElementRenderingTemplateBase.prototype.attach = function (owner) {
- this._owner = owner;
- };
- UIElementRenderingTemplateBase.prototype.detach = function () {
- };
- Object.defineProperty(UIElementRenderingTemplateBase.prototype, "owner", {
- get: function () {
- return this._owner;
- },
- enumerable: true,
- configurable: true
- });
- return UIElementRenderingTemplateBase;
- }());
- BABYLON.UIElementRenderingTemplateBase = UIElementRenderingTemplateBase;
- function registerWindowRenderingTemplate(uiElType, templateName, factory) {
- return function () {
- GUIManager.registerRenderingTemplate(uiElType, templateName, factory);
- };
- }
- BABYLON.registerWindowRenderingTemplate = registerWindowRenderingTemplate;
- })(BABYLON || (BABYLON = {}));
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var StackPanel = StackPanel_1 = (function (_super) {
- __extends(StackPanel, _super);
- function StackPanel(settings) {
- var _this = this;
- if (!settings) {
- settings = {};
- }
- _this = _super.call(this, settings) || this;
- _this.isOrientationHorizontal = (settings.isOrientationHorizontal == null) ? true : settings.isOrientationHorizontal;
- _this._children = new Array();
- if (settings.children != null) {
- for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
- var child = _a[_i];
- _this._children.push(child);
- }
- }
- return _this;
- }
- Object.defineProperty(StackPanel.prototype, "isOrientationHorizontal", {
- get: function () {
- return this._isOrientationHorizontal;
- },
- set: function (value) {
- this._isOrientationHorizontal = value;
- },
- enumerable: true,
- configurable: true
- });
- StackPanel.prototype.createVisualTree = function () {
- _super.prototype.createVisualTree.call(this);
- // A StackPanel Control has a Group2D, child of the visualPlaceHolder, which is the Children placeholder.
- // The Children UIElement Tree will be create inside this placeholder.
- this._childrenPlaceholder = new BABYLON.Group2D({ parent: this._visualPlaceholder, id: "StackPanel Children Placeholder of " + this.id });
- var p = this._childrenPlaceholder;
- p.layoutEngine = this.isOrientationHorizontal ? BABYLON.StackPanelLayoutEngine.Horizontal : BABYLON.StackPanelLayoutEngine.Vertical;
- // 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.
- p.dataSource = this;
- p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "padding", BABYLON.DataBinding.MODE_ONEWAY);
- p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "paddingAlignment", BABYLON.DataBinding.MODE_ONEWAY);
- // The UIElement set the childrenPlaceholder with the visual returned by the renderingTemplate.
- // But it's not the case for a StackPanel, the placeholder of UIElement Children (the content)
- this._visualChildrenPlaceholder = this._childrenPlaceholder;
- };
- Object.defineProperty(StackPanel.prototype, "children", {
- get: function () {
- return this._children;
- },
- enumerable: true,
- configurable: true
- });
- StackPanel.prototype._getChildren = function () {
- return this.children;
- };
- return StackPanel;
- }(BABYLON.UIElement));
- StackPanel.STACKPANEL_PROPCOUNT = BABYLON.UIElement.UIELEMENT_PROPCOUNT + 3;
- __decorate([
- BABYLON.dependencyProperty(StackPanel_1.STACKPANEL_PROPCOUNT + 0, function (pi) { return StackPanel_1.orientationHorizontalProperty = pi; })
- ], StackPanel.prototype, "isOrientationHorizontal", null);
- StackPanel = StackPanel_1 = __decorate([
- BABYLON.className("StackPanel", "BABYLON")
- ], StackPanel);
- BABYLON.StackPanel = StackPanel;
- var DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate_1 = (function (_super) {
- __extends(DefaultStackPanelRenderingTemplate, _super);
- function DefaultStackPanelRenderingTemplate() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- DefaultStackPanelRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
- return { root: visualPlaceholder, contentPlaceholder: visualPlaceholder };
- };
- DefaultStackPanelRenderingTemplate.prototype.attach = function (owner) {
- _super.prototype.attach.call(this, owner);
- };
- return DefaultStackPanelRenderingTemplate;
- }(BABYLON.UIElementRenderingTemplateBase));
- DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate_1 = __decorate([
- BABYLON.registerWindowRenderingTemplate("BABYLON.StackPanel", "Default", function () { return new DefaultStackPanelRenderingTemplate_1(); })
- ], DefaultStackPanelRenderingTemplate);
- BABYLON.DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate;
- var StackPanel_1, DefaultStackPanelRenderingTemplate_1;
- })(BABYLON || (BABYLON = {}));
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var Control = Control_1 = (function (_super) {
- __extends(Control, _super);
- function Control(settings) {
- return _super.call(this, settings) || this;
- }
- Object.defineProperty(Control.prototype, "background", {
- get: function () {
- if (!this._background) {
- this._background = new BABYLON.ObservableStringDictionary(false);
- }
- return this._background;
- },
- set: function (value) {
- this.background.copyFrom(value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Control.prototype, "border", {
- get: function () {
- return this._border;
- },
- set: function (value) {
- this._border = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Control.prototype, "borderThickness", {
- get: function () {
- return this._borderThickness;
- },
- set: function (value) {
- this._borderThickness = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Control.prototype, "fontName", {
- get: function () {
- return this._fontName;
- },
- set: function (value) {
- this._fontName = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Control.prototype, "foreground", {
- get: function () {
- return this._foreground;
- },
- set: function (value) {
- this._foreground = value;
- },
- enumerable: true,
- configurable: true
- });
- return Control;
- }(BABYLON.UIElement));
- Control.CONTROL_PROPCOUNT = BABYLON.UIElement.UIELEMENT_PROPCOUNT + 5;
- __decorate([
- BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 0, function (pi) { return Control_1.backgroundProperty = pi; })
- ], Control.prototype, "background", null);
- __decorate([
- BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 1, function (pi) { return Control_1.borderProperty = pi; })
- ], Control.prototype, "border", null);
- __decorate([
- BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 2, function (pi) { return Control_1.borderThicknessProperty = pi; })
- ], Control.prototype, "borderThickness", null);
- __decorate([
- BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 3, function (pi) { return Control_1.fontNameProperty = pi; })
- ], Control.prototype, "fontName", null);
- __decorate([
- BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 4, function (pi) { return Control_1.foregroundProperty = pi; })
- ], Control.prototype, "foreground", null);
- Control = Control_1 = __decorate([
- BABYLON.className("Control", "BABYLON")
- ], Control);
- BABYLON.Control = Control;
- var Control_1;
- })(BABYLON || (BABYLON = {}));
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var ContentControl = ContentControl_1 = (function (_super) {
- __extends(ContentControl, _super);
- function ContentControl(settings) {
- var _this = this;
- if (!settings) {
- settings = {};
- }
- _this = _super.call(this, settings) || this;
- if (settings.content != null) {
- _this._content = settings.content;
- }
- return _this;
- }
- ContentControl.prototype.dispose = function () {
- if (this.isDisposed) {
- return false;
- }
- if (this.content && this.content.dispose) {
- this.content.dispose();
- this.content = null;
- }
- if (this.__contentUIElement) {
- this.__contentUIElement.dispose();
- this.__contentUIElement = null;
- }
- _super.prototype.dispose.call(this);
- return true;
- };
- Object.defineProperty(ContentControl.prototype, "content", {
- get: function () {
- return this._content;
- },
- set: function (value) {
- this._content = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ContentControl.prototype, "_contentUIElement", {
- get: function () {
- if (!this.__contentUIElement) {
- this._buildContentUIElement();
- }
- return this.__contentUIElement;
- },
- enumerable: true,
- configurable: true
- });
- ContentControl.prototype._createVisualTree = function () {
- // Base implementation will create the Group2D for the Visual Placeholder and its Visual Tree
- _super.prototype._createVisualTree.call(this);
- // A Content Control has a Group2D, child of the visualPlaceHolder, which is the Content placeholder.
- // The Content UIElement Tree will be create inside this placeholder.
- this._contentPlaceholder = new BABYLON.Group2D({ parent: this._visualPlaceholder, id: "ContentControl Content Placeholder of " + this.id });
- var p = this._contentPlaceholder;
- // 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.
- p.dataSource = this;
- p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "padding", BABYLON.DataBinding.MODE_ONEWAY);
- p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "paddingAlignment", BABYLON.DataBinding.MODE_ONEWAY);
- // The UIElement set the childrenPlaceholder with the visual returned by the renderingTemplate.
- // But it's not the case for a ContentControl, the placeholder of UIElement Children (the content)
- this._visualChildrenPlaceholder = this._contentPlaceholder;
- };
- ContentControl.prototype._buildContentUIElement = function () {
- var c = this._content;
- this.__contentUIElement = null;
- // Already a UIElement
- if (c instanceof BABYLON.UIElement) {
- this.__contentUIElement = c;
- }
- else if ((typeof c === "string") || (typeof c === "boolean") || (typeof c === "number")) {
- var l = new BABYLON.Label({ parent: this, id: "Content of " + this.id });
- var binding = new BABYLON.DataBinding();
- binding.propertyPathName = "content";
- binding.stringFormat = function (v) { return "" + v; };
- binding.dataSource = this;
- l.createDataBinding(BABYLON.Label.textProperty, binding);
- this.__contentUIElement = l;
- }
- else {
- // TODO: DataTemplate lookup and create instance
- }
- if (this.__contentUIElement) {
- this.__contentUIElement._patchUIElement(this.ownerWindow, this);
- }
- };
- ContentControl.prototype._getChildren = function () {
- var children = new Array();
- if (this.content) {
- children.push(this._contentUIElement);
- }
- return children;
- };
- return ContentControl;
- }(BABYLON.Control));
- ContentControl.CONTENTCONTROL_PROPCOUNT = BABYLON.Control.CONTROL_PROPCOUNT + 2;
- __decorate([
- BABYLON.dependencyProperty(BABYLON.Control.CONTROL_PROPCOUNT + 0, function (pi) { return ContentControl_1.contentProperty = pi; })
- ], ContentControl.prototype, "content", null);
- ContentControl = ContentControl_1 = __decorate([
- BABYLON.className("ContentControl", "BABYLON")
- ], ContentControl);
- BABYLON.ContentControl = ContentControl;
- var ContentControl_1;
- })(BABYLON || (BABYLON = {}));
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var FocusScopeData = (function () {
- function FocusScopeData(focusScope) {
- this.focusScope = focusScope;
- this.focusedElement = null;
- }
- return FocusScopeData;
- }());
- var FocusManager = (function () {
- function FocusManager() {
- this._focusScopes = new BABYLON.StringDictionary();
- this._rootScope = new FocusScopeData(null);
- this._activeScope = null;
- }
- FocusManager.prototype.setFocusOn = function (el, focusScope) {
- var fsd = (focusScope != null) ? this._focusScopes.getOrAddWithFactory(focusScope.uid, function (k) { return new FocusScopeData(focusScope); }) : this._rootScope;
- if (fsd.focusedElement !== el) {
- // Remove focus from current
- if (fsd.focusedElement) {
- fsd.focusedElement.isFocused = false;
- }
- fsd.focusedElement = el;
- }
- if (this._activeScope !== fsd) {
- this._activeScope = fsd;
- }
- };
- return FocusManager;
- }());
- BABYLON.FocusManager = FocusManager;
- var GUISceneData = (function () {
- function GUISceneData(scene) {
- this.scene = scene;
- this.screenSpaceCanvas = new BABYLON.ScreenSpaceCanvas2D(scene, { id: "GUI Canvas", cachingStrategy: BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE });
- this.focusManager = new FocusManager();
- }
- return GUISceneData;
- }());
- var Window = Window_1 = (function (_super) {
- __extends(Window, _super);
- function Window(scene, settings) {
- var _this = this;
- if (!settings) {
- settings = {};
- }
- _this = _super.call(this, settings) || this;
- // Per default a Window is focus scope
- _this.isFocusScope = true;
- _this.isActive = false;
- if (!_this._UIElementVisualToBuildList) {
- _this._UIElementVisualToBuildList = new Array();
- }
- // Patch the owner and also the parent property through the whole tree
- _this._patchUIElement(_this, null);
- // Screen Space UI
- if (!settings.worldPosition && !settings.worldRotation) {
- _this._sceneData = Window_1.getSceneData(scene);
- _this._canvas = _this._sceneData.screenSpaceCanvas;
- _this._isWorldSpaceCanvas = false;
- _this._left = (settings.left != null) ? settings.left : 0;
- _this._bottom = (settings.bottom != null) ? settings.bottom : 0;
- }
- else {
- var w = (settings.width == null) ? 100 : settings.width;
- var h = (settings.height == null) ? 100 : settings.height;
- var wpos = (settings.worldPosition == null) ? BABYLON.Vector3.Zero() : settings.worldPosition;
- var wrot = (settings.worldRotation == null) ? BABYLON.Quaternion.Identity() : settings.worldRotation;
- _this._canvas = new BABYLON.WorldSpaceCanvas2D(scene, new BABYLON.Size(w, h), { id: "GUI Canvas", cachingStrategy: BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE, worldPosition: wpos, worldRotation: wrot });
- _this._isWorldSpaceCanvas = true;
- }
- _this._renderObserver = _this._canvas.renderObservable.add(function (e, s) { return _this._canvasPreRender(); }, BABYLON.Canvas2D.RENDEROBSERVABLE_PRE);
- _this._disposeObserver = _this._canvas.disposeObservable.add(function (e, s) { return _this._canvasDisposed(); });
- _this._canvas.propertyChanged.add(function (e, s) {
- if (e.propertyName === "overPrim") {
- _this._overPrimChanged(e.oldValue, e.newValue);
- }
- });
- _this._mouseOverUIElement = null;
- return _this;
- }
- Object.defineProperty(Window.prototype, "canvas", {
- get: function () {
- return this._canvas;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Window.prototype, "left", {
- get: function () {
- return this._left;
- },
- set: function (value) {
- var old = new BABYLON.Vector2(this._left, this._bottom);
- this._left = value;
- this.onPropertyChanged("_position", old, this._position);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Window.prototype, "bottom", {
- get: function () {
- return this._bottom;
- },
- set: function (value) {
- var old = new BABYLON.Vector2(this._left, this._bottom);
- this._bottom = value;
- this.onPropertyChanged("_position", old, this._position);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Window.prototype, "position", {
- get: function () {
- return this._position;
- },
- set: function (value) {
- this._left = value.x;
- this._bottom = value.y;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Window.prototype, "isActive", {
- get: function () {
- return this._isActive;
- },
- set: function (value) {
- this._isActive = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Window.prototype, "focusManager", {
- get: function () {
- return this._sceneData.focusManager;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Window.prototype, "_position", {
- get: function () {
- return new BABYLON.Vector2(this.left, this.bottom);
- },
- enumerable: true,
- configurable: true
- });
- Window.prototype.createVisualTree = function () {
- _super.prototype.createVisualTree.call(this);
- var p = this._visualPlaceholder;
- p.createSimpleDataBinding(BABYLON.Group2D.positionProperty, "position");
- };
- Window.prototype._registerVisualToBuild = function (uiel) {
- if (uiel._isFlagSet(BABYLON.UIElement.flagVisualToBuild)) {
- return;
- }
- if (!this._UIElementVisualToBuildList) {
- this._UIElementVisualToBuildList = new Array();
- }
- this._UIElementVisualToBuildList.push(uiel);
- uiel._setFlags(BABYLON.UIElement.flagVisualToBuild);
- };
- Window.prototype._overPrimChanged = function (oldPrim, newPrim) {
- var curOverEl = this._mouseOverUIElement;
- var newOverEl = null;
- var curGroup = newPrim ? newPrim.traverseUp(function (p) { return p instanceof BABYLON.Group2D; }) : null;
- while (curGroup) {
- var uiel = curGroup.getExternalData("_GUIOwnerElement_");
- if (uiel) {
- newOverEl = uiel;
- break;
- }
- curGroup = curGroup.parent ? curGroup.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D; }) : null;
- }
- if (curOverEl === newOverEl) {
- return;
- }
- if (curOverEl) {
- curOverEl.isMouseOver = false;
- }
- if (newOverEl) {
- newOverEl.isMouseOver = true;
- }
- this._mouseOverUIElement = newOverEl;
- };
- Window.prototype._canvasPreRender = function () {
- // Check if we have visual to create
- if (this._UIElementVisualToBuildList.length > 0) {
- // Sort the UI Element to get the highest (so lowest hierarchy depth) in the hierarchy tree first
- var sortedElementList = this._UIElementVisualToBuildList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
- for (var _i = 0, sortedElementList_1 = sortedElementList; _i < sortedElementList_1.length; _i++) {
- var el = sortedElementList_1[_i];
- el._createVisualTree();
- }
- this._UIElementVisualToBuildList.splice(0);
- }
- };
- Window.prototype._canvasDisposed = function () {
- this._canvas.disposeObservable.remove(this._disposeObserver);
- this._canvas.renderObservable.remove(this._renderObserver);
- };
- Window.getSceneData = function (scene) {
- return Window_1._sceneData.getOrAddWithFactory(scene.uid, function (k) { return new GUISceneData(scene); });
- };
- return Window;
- }(BABYLON.ContentControl));
- Window.WINDOW_PROPCOUNT = BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 4;
- Window._sceneData = new BABYLON.StringDictionary();
- __decorate([
- BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 0, function (pi) { return Window_1.leftProperty = pi; })
- ], Window.prototype, "left", null);
- __decorate([
- BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 1, function (pi) { return Window_1.bottomProperty = pi; })
- ], Window.prototype, "bottom", null);
- __decorate([
- BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 2, function (pi) { return Window_1.positionProperty = pi; })
- ], Window.prototype, "position", null);
- __decorate([
- BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 3, function (pi) { return Window_1.isActiveProperty = pi; })
- ], Window.prototype, "isActive", null);
- Window = Window_1 = __decorate([
- BABYLON.className("Window", "BABYLON")
- ], Window);
- BABYLON.Window = Window;
- var DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate_1 = (function (_super) {
- __extends(DefaultWindowRenderingTemplate, _super);
- function DefaultWindowRenderingTemplate() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- DefaultWindowRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
- var r = new BABYLON.Rectangle2D({ parent: visualPlaceholder, fill: "#808080FF" });
- return { root: r, contentPlaceholder: r };
- };
- return DefaultWindowRenderingTemplate;
- }(BABYLON.UIElementRenderingTemplateBase));
- DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate_1 = __decorate([
- BABYLON.registerWindowRenderingTemplate("BABYLON.Window", "Default", function () { return new DefaultWindowRenderingTemplate_1(); })
- ], DefaultWindowRenderingTemplate);
- BABYLON.DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate;
- var Window_1, DefaultWindowRenderingTemplate_1;
- })(BABYLON || (BABYLON = {}));
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var Label = Label_1 = (function (_super) {
- __extends(Label, _super);
- function Label(settings) {
- var _this = this;
- if (!settings) {
- settings = {};
- }
- _this = _super.call(this, settings) || this;
- if (settings.text != null) {
- _this.text = settings.text;
- }
- return _this;
- }
- Object.defineProperty(Label.prototype, "_position", {
- get: function () {
- return BABYLON.Vector2.Zero();
- },
- enumerable: true,
- configurable: true
- });
- Label.prototype._getChildren = function () {
- return Label_1._emptyArray;
- };
- Label.prototype.createVisualTree = function () {
- _super.prototype.createVisualTree.call(this);
- var p = this._visualChildrenPlaceholder;
- };
- Object.defineProperty(Label.prototype, "text", {
- get: function () {
- return this._text;
- },
- set: function (value) {
- this._text = value;
- },
- enumerable: true,
- configurable: true
- });
- return Label;
- }(BABYLON.Control));
- Label._emptyArray = new Array();
- __decorate([
- BABYLON.dependencyProperty(BABYLON.Control.CONTROL_PROPCOUNT + 0, function (pi) { return Label_1.textProperty = pi; })
- ], Label.prototype, "text", null);
- Label = Label_1 = __decorate([
- BABYLON.className("Label", "BABYLON")
- ], Label);
- BABYLON.Label = Label;
- var DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate_1 = (function (_super) {
- __extends(DefaultLabelRenderingTemplate, _super);
- function DefaultLabelRenderingTemplate() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- DefaultLabelRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
- var r = new BABYLON.Text2D("", { parent: visualPlaceholder });
- r.createSimpleDataBinding(BABYLON.Text2D.textProperty, "text");
- r.dataSource = owner;
- return { root: r, contentPlaceholder: r };
- };
- return DefaultLabelRenderingTemplate;
- }(BABYLON.UIElementRenderingTemplateBase));
- DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate_1 = __decorate([
- BABYLON.registerWindowRenderingTemplate("BABYLON.Label", "Default", function () { return new DefaultLabelRenderingTemplate_1(); })
- ], DefaultLabelRenderingTemplate);
- BABYLON.DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate;
- var Label_1, DefaultLabelRenderingTemplate_1;
- })(BABYLON || (BABYLON = {}));
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var BABYLON;
- (function (BABYLON) {
- var Button = Button_1 = (function (_super) {
- __extends(Button, _super);
- function Button(settings) {
- var _this = this;
- if (!settings) {
- settings = {};
- }
- _this = _super.call(this, settings) || this;
- if (settings.paddingAlignment == null) {
- _this.paddingAlignment.horizontal = BABYLON.PrimitiveAlignment.AlignCenter;
- _this.paddingAlignment.vertical = BABYLON.PrimitiveAlignment.AlignCenter;
- }
- _this._normalStateBackground = new BABYLON.ObservableStringDictionary(false);
- _this._normalStateBorder = new BABYLON.ObservableStringDictionary(false);
- _this._defaultStateBackground = new BABYLON.ObservableStringDictionary(false);
- _this._defaultStateBorder = new BABYLON.ObservableStringDictionary(false);
- _this._normalStateBackground.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#337AB7FF"));
- _this._normalStateBackground.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#7BA9D0FF"));
- _this._normalStateBackground.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#286090FF"));
- _this._normalStateBackground.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#1E496EFF"));
- _this._normalStateBorder.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#2E6DA4FF"));
- _this._normalStateBorder.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#77A0C4FF"));
- _this._normalStateBorder.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#204D74FF"));
- _this._normalStateBorder.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#2E5D9EFF"));
- _this._defaultStateBackground.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"));
- _this._defaultStateBackground.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"));
- _this._defaultStateBackground.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#E6E6E6FF"));
- _this._defaultStateBackground.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#D4D4D4FF"));
- _this._defaultStateBorder.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#CCCCCCFF"));
- _this._defaultStateBorder.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#DEDEDEFF"));
- _this._defaultStateBorder.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#ADADADFF"));
- _this._defaultStateBorder.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#6C8EC5FF"));
- return _this;
- }
- Object.defineProperty(Button, "pushedState", {
- get: function () {
- return Button_1._pushedState;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Button.prototype, "isPushed", {
- get: function () {
- return this._isPushed;
- },
- set: function (value) {
- this._isPushed = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Button.prototype, "isDefault", {
- get: function () {
- return this._isDefault;
- },
- set: function (value) {
- this._isDefault = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Button.prototype, "isOutline", {
- get: function () {
- return this._isOutline;
- },
- set: function (value) {
- this._isOutline = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Button.prototype, "clickObservable", {
- get: function () {
- if (!this._clickObservable) {
- this._clickObservable = new BABYLON.Observable();
- }
- return this._clickObservable;
- },
- enumerable: true,
- configurable: true
- });
- Button.prototype._raiseClick = function () {
- if (this._clickObservable && this._clickObservable.hasObservers()) {
- this._clickObservable.notifyObservers(this);
- }
- };
- Button.prototype.createVisualTree = function () {
- var _this = this;
- _super.prototype.createVisualTree.call(this);
- var p = this._visualPlaceholder;
- p.pointerEventObservable.add(function (e, s) {
- // check if input must be discarded
- if (!_this.isVisible || !_this.isEnabled) {
- return;
- }
- // We reject an event coming from the placeholder because it means it's on an empty spot, so it's not valid.
- if (e.relatedTarget === _this._visualPlaceholder) {
- return;
- }
- if (s.mask === BABYLON.PrimitivePointerInfo.PointerUp) {
- _this._raiseClick();
- _this.isPushed = false;
- }
- else if (s.mask === BABYLON.PrimitivePointerInfo.PointerDown) {
- _this.isPushed = true;
- _this.isFocused = true;
- }
- }, BABYLON.PrimitivePointerInfo.PointerUp | BABYLON.PrimitivePointerInfo.PointerDown);
- };
- Object.defineProperty(Button.prototype, "normalStateBackground", {
- get: function () {
- return this._normalStateBackground;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Button.prototype, "defaultStateBackground", {
- get: function () {
- return this._defaultStateBackground;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Button.prototype, "normalStateBorder", {
- get: function () {
- return this._normalStateBorder;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Button.prototype, "defaultStateBorder", {
- get: function () {
- return this._defaultStateBorder;
- },
- enumerable: true,
- configurable: true
- });
- return Button;
- }(BABYLON.ContentControl));
- Button.BUTTON_PROPCOUNT = BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 3;
- Button._pushedState = "Pushed";
- __decorate([
- BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 0, function (pi) { return Button_1.isPushedProperty = pi; })
- ], Button.prototype, "isPushed", null);
- __decorate([
- BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 1, function (pi) { return Button_1.isDefaultProperty = pi; })
- ], Button.prototype, "isDefault", null);
- __decorate([
- BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 2, function (pi) { return Button_1.isOutlineProperty = pi; })
- ], Button.prototype, "isOutline", null);
- Button = Button_1 = __decorate([
- BABYLON.className("Button", "BABYLON")
- ], Button);
- BABYLON.Button = Button;
- var DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate_1 = (function (_super) {
- __extends(DefaultButtonRenderingTemplate, _super);
- function DefaultButtonRenderingTemplate() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- DefaultButtonRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
- this._rect = new BABYLON.Rectangle2D({ parent: visualPlaceholder, fill: "#FF8080FF", border: "#FF8080FF", roundRadius: 10, borderThickness: 2 });
- this.stateChange();
- return { root: this._rect, contentPlaceholder: this._rect };
- };
- DefaultButtonRenderingTemplate.prototype.attach = function (owner) {
- var _this = this;
- _super.prototype.attach.call(this, owner);
- this.owner.propertyChanged.add(function (e, s) { return _this.stateChange(); }, BABYLON.UIElement.isEnabledProperty.flagId |
- BABYLON.UIElement.isFocusedProperty.flagId |
- BABYLON.UIElement.isMouseOverProperty.flagId |
- Button.isDefaultProperty.flagId |
- Button.isOutlineProperty.flagId |
- Button.isPushedProperty.flagId);
- // Register for brush change and update the Visual
- var button = owner;
- button.normalStateBackground.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
- button.normalStateBorder.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
- button.defaultStateBackground.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
- button.defaultStateBorder.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
- };
- DefaultButtonRenderingTemplate.prototype.stateChange = function () {
- //console.log("state changed");
- var b = this.owner;
- var state = BABYLON.UIElement.enabledState;
- var bg = b.isDefault ? b.defaultStateBackground.get(state) : b.normalStateBackground.get(state);
- var bd = b.isDefault ? b.defaultStateBorder.get(state) : b.normalStateBorder.get(state);
- if (b.isPushed) {
- state = Button.pushedState;
- if (b.isDefault) {
- bg = b.defaultStateBackground.get(state);
- bd = b.defaultStateBorder.get(state);
- }
- else {
- bg = b.normalStateBackground.get(state);
- bd = b.normalStateBorder.get(state);
- }
- }
- else if (b.isMouseOver) {
- state = BABYLON.UIElement.mouseOverState;
- if (b.isDefault) {
- bg = b.defaultStateBackground.get(state);
- bd = b.defaultStateBorder.get(state);
- }
- else {
- bg = b.normalStateBackground.get(state);
- bd = b.normalStateBorder.get(state);
- }
- }
- else if (!b.isEnabled) {
- state = BABYLON.UIElement.disabledState;
- if (b.isDefault) {
- bg = b.defaultStateBackground.get(state);
- bd = b.defaultStateBorder.get(state);
- }
- else {
- bg = b.normalStateBackground.get(state);
- bd = b.normalStateBorder.get(state);
- }
- }
- this._rect.fill = bg;
- this._rect.border = bd;
- };
- return DefaultButtonRenderingTemplate;
- }(BABYLON.UIElementRenderingTemplateBase));
- DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate_1 = __decorate([
- BABYLON.registerWindowRenderingTemplate("BABYLON.Button", "Default", function () { return new DefaultButtonRenderingTemplate_1(); })
- ], DefaultButtonRenderingTemplate);
- BABYLON.DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate;
- var Button_1, DefaultButtonRenderingTemplate_1;
- })(BABYLON || (BABYLON = {}));
|