babylon.engine.ts 314 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197
  1. module BABYLON {
  2. /**
  3. * Keeps track of all the buffer info used in engine.
  4. */
  5. class BufferPointer {
  6. public active: boolean;
  7. public index: number;
  8. public size: number;
  9. public type: number;
  10. public normalized: boolean;
  11. public stride: number;
  12. public offset: number;
  13. public buffer: WebGLBuffer;
  14. }
  15. /**
  16. * Interface for attribute information associated with buffer instanciation
  17. */
  18. export class InstancingAttributeInfo {
  19. /**
  20. * Index/offset of the attribute in the vertex shader
  21. */
  22. index: number;
  23. /**
  24. * size of the attribute, 1, 2, 3 or 4
  25. */
  26. attributeSize: number;
  27. /**
  28. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  29. * default is FLOAT
  30. */
  31. attribyteType: number;
  32. /**
  33. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  34. */
  35. normalized: boolean;
  36. /**
  37. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  38. */
  39. offset: number;
  40. /**
  41. * Name of the GLSL attribute, for debugging purpose only
  42. */
  43. attributeName: string;
  44. }
  45. /**
  46. * Define options used to create a render target texture
  47. */
  48. export class RenderTargetCreationOptions {
  49. /**
  50. * Specifies is mipmaps must be generated
  51. */
  52. generateMipMaps?: boolean;
  53. /** Specifies whether or not a depth should be allocated in the texture (true by default) */
  54. generateDepthBuffer?: boolean;
  55. /** Specifies whether or not a stencil should be allocated in the texture (false by default)*/
  56. generateStencilBuffer?: boolean;
  57. /** Defines texture type (int by default) */
  58. type?: number;
  59. /** Defines sampling mode (trilinear by default) */
  60. samplingMode?: number;
  61. /** Defines format (RGBA by default) */
  62. format?: number;
  63. }
  64. /**
  65. * Define options used to create a depth texture
  66. */
  67. export class DepthTextureCreationOptions {
  68. /** Specifies whether or not a stencil should be allocated in the texture */
  69. generateStencil?: boolean;
  70. /** Specifies whether or not bilinear filtering is enable on the texture */
  71. bilinearFiltering?: boolean;
  72. /** Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode */
  73. comparisonFunction?: number;
  74. /** Specifies if the created texture is a cube texture */
  75. isCube?: boolean;
  76. }
  77. /**
  78. * Class used to describe the capabilities of the engine relatively to the current browser
  79. */
  80. export class EngineCapabilities {
  81. /** Maximum textures units per fragment shader */
  82. public maxTexturesImageUnits: number;
  83. /** Maximum texture units per vertex shader */
  84. public maxVertexTextureImageUnits: number;
  85. /** Maximum textures units in the entire pipeline */
  86. public maxCombinedTexturesImageUnits: number;
  87. /** Maximum texture size */
  88. public maxTextureSize: number;
  89. /** Maximum cube texture size */
  90. public maxCubemapTextureSize: number;
  91. /** Maximum render texture size */
  92. public maxRenderTextureSize: number;
  93. /** Maximum number of vertex attributes */
  94. public maxVertexAttribs: number;
  95. /** Maximum number of varyings */
  96. public maxVaryingVectors: number;
  97. /** Maximum number of uniforms per vertex shader */
  98. public maxVertexUniformVectors: number;
  99. /** Maximum number of uniforms per fragment shader */
  100. public maxFragmentUniformVectors: number;
  101. /** Defines if standard derivates (dx/dy) are supported */
  102. public standardDerivatives: boolean;
  103. /** Defines if s3tc texture compression is supported */
  104. public s3tc: Nullable<WEBGL_compressed_texture_s3tc>;
  105. /** Defines if pvrtc texture compression is supported */
  106. public pvrtc: any; //WEBGL_compressed_texture_pvrtc;
  107. /** Defines if etc1 texture compression is supported */
  108. public etc1: any; //WEBGL_compressed_texture_etc1;
  109. /** Defines if etc2 texture compression is supported */
  110. public etc2: any; //WEBGL_compressed_texture_etc;
  111. /** Defines if astc texture compression is supported */
  112. public astc: any; //WEBGL_compressed_texture_astc;
  113. /** Defines if float textures are supported */
  114. public textureFloat: boolean;
  115. /** Defines if vertex array objects are supported */
  116. public vertexArrayObject: boolean;
  117. /** Gets the webgl extension for anisotropic filtering (null if not supported) */
  118. public textureAnisotropicFilterExtension: Nullable<EXT_texture_filter_anisotropic>;
  119. /** Gets the maximum level of anisotropy supported */
  120. public maxAnisotropy: number;
  121. /** Defines if instancing is supported */
  122. public instancedArrays: boolean;
  123. /** Defines if 32 bits indices are supported */
  124. public uintIndices: boolean;
  125. /** Defines if high precision shaders are supported */
  126. public highPrecisionShaderSupported: boolean;
  127. /** Defines if depth reading in the fragment shader is supported */
  128. public fragmentDepthSupported: boolean;
  129. /** Defines if float texture linear filtering is supported*/
  130. public textureFloatLinearFiltering: boolean;
  131. /** Defines if rendering to float textures is supported */
  132. public textureFloatRender: boolean;
  133. /** Defines if half float textures are supported*/
  134. public textureHalfFloat: boolean;
  135. /** Defines if half float texture linear filtering is supported*/
  136. public textureHalfFloatLinearFiltering: boolean;
  137. /** Defines if rendering to half float textures is supported */
  138. public textureHalfFloatRender: boolean;
  139. /** Defines if textureLOD shader command is supported */
  140. public textureLOD: boolean;
  141. /** Defines if draw buffers extension is supported */
  142. public drawBuffersExtension: boolean;
  143. /** Defines if depth textures are supported */
  144. public depthTextureExtension: boolean;
  145. /** Defines if float color buffer are supported */
  146. public colorBufferFloat: boolean;
  147. /** Gets disjoint timer query extension (null if not supported) */
  148. public timerQuery: EXT_disjoint_timer_query;
  149. /** Defines if timestamp can be used with timer query */
  150. public canUseTimestampForTimerQuery: boolean;
  151. }
  152. /** Interface defining initialization parameters for Engine class */
  153. export interface EngineOptions extends WebGLContextAttributes {
  154. /**
  155. * Defines if the engine should no exceed a specified device ratio
  156. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
  157. */
  158. limitDeviceRatio?: number;
  159. /**
  160. * Defines if webvr should be enabled automatically
  161. * @see http://doc.babylonjs.com/how_to/webvr_camera
  162. */
  163. autoEnableWebVR?: boolean;
  164. /**
  165. * Defines if webgl2 should be turned off even if supported
  166. * @see http://doc.babylonjs.com/features/webgl2
  167. */
  168. disableWebGL2Support?: boolean;
  169. /**
  170. * Defines if webaudio should be initialized as well
  171. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  172. */
  173. audioEngine?: boolean;
  174. /**
  175. * Defines if animations should run using a deterministic lock step
  176. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  177. */
  178. deterministicLockstep?: boolean;
  179. /** Defines the maximum steps to use with deterministic lock step mode */
  180. lockstepMaxSteps?: number;
  181. /**
  182. * Defines that engine should ignore context lost events
  183. * If this event happens when this parameter is true, you will have to reload the page to restore rendering
  184. */
  185. doNotHandleContextLost?: boolean;
  186. }
  187. /**
  188. * Defines the interface used by display changed events
  189. */
  190. export interface IDisplayChangedEventArgs {
  191. /** Gets the vrDisplay object (if any) */
  192. vrDisplay: Nullable<any>;
  193. /** Gets a boolean indicating if webVR is supported */
  194. vrSupported: boolean;
  195. }
  196. /**
  197. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  198. */
  199. export class Engine {
  200. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  201. public static ExceptionList = [
  202. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  203. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  204. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  205. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  206. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  207. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  208. ];
  209. /** Gets the list of created engines */
  210. public static Instances = new Array<Engine>();
  211. /**
  212. * Gets the latest created engine
  213. */
  214. public static get LastCreatedEngine(): Nullable<Engine> {
  215. if (Engine.Instances.length === 0) {
  216. return null;
  217. }
  218. return Engine.Instances[Engine.Instances.length - 1];
  219. }
  220. /**
  221. * Gets the latest created scene
  222. */
  223. public static get LastCreatedScene(): Nullable<Scene> {
  224. var lastCreatedEngine = Engine.LastCreatedEngine;
  225. if (!lastCreatedEngine) {
  226. return null;
  227. }
  228. if (lastCreatedEngine.scenes.length === 0) {
  229. return null;
  230. }
  231. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  232. }
  233. /**
  234. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  235. * @param flag defines which part of the materials must be marked as dirty
  236. * @param predicate defines a predicate used to filter which materials should be affected
  237. */
  238. public static MarkAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  239. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  240. var engine = Engine.Instances[engineIndex];
  241. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  242. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  243. }
  244. }
  245. }
  246. /**
  247. * Hidden
  248. */
  249. public static _TextureLoaders: IInternalTextureLoader[] = [];
  250. // Const statics
  251. /** Defines that alpha blending is disabled */
  252. public static readonly ALPHA_DISABLE = 0;
  253. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  254. public static readonly ALPHA_ADD = 1;
  255. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  256. public static readonly ALPHA_COMBINE = 2;
  257. /** Defines that alpha blending to DEST - SRC * DEST */
  258. public static readonly ALPHA_SUBTRACT = 3;
  259. /** Defines that alpha blending to SRC * DEST */
  260. public static readonly ALPHA_MULTIPLY = 4;
  261. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  262. public static readonly ALPHA_MAXIMIZED = 5;
  263. /** Defines that alpha blending to SRC + DEST */
  264. public static readonly ALPHA_ONEONE = 6;
  265. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  266. public static readonly ALPHA_PREMULTIPLIED = 7;
  267. /**
  268. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  269. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  270. */
  271. public static readonly ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  272. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  273. public static readonly ALPHA_INTERPOLATE = 9;
  274. /**
  275. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  276. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  277. */
  278. public static readonly ALPHA_SCREENMODE = 10;
  279. /** Defines that the ressource is not delayed*/
  280. public static readonly DELAYLOADSTATE_NONE = 0;
  281. /** Defines that the ressource was successfully delay loaded */
  282. public static readonly DELAYLOADSTATE_LOADED = 1;
  283. /** Defines that the ressource is currently delay loading */
  284. public static readonly DELAYLOADSTATE_LOADING = 2;
  285. /** Defines that the ressource is delayed and has not started loading */
  286. public static readonly DELAYLOADSTATE_NOTLOADED = 4;
  287. // Depht or Stencil test Constants.
  288. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  289. public static readonly NEVER = 0x0200;
  290. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */
  291. public static readonly ALWAYS = 0x0207;
  292. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  293. public static readonly LESS = 0x0201;
  294. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  295. public static readonly EQUAL = 0x0202;
  296. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */
  297. public static readonly LEQUAL = 0x0203;
  298. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  299. public static readonly GREATER = 0x0204;
  300. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */
  301. public static readonly GEQUAL = 0x0206;
  302. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */
  303. public static readonly NOTEQUAL = 0x0205;
  304. // Stencil Actions Constants.
  305. /** Passed to stencilOperation to specify that stencil value must be kept */
  306. public static readonly KEEP = 0x1E00;
  307. /** Passed to stencilOperation to specify that stencil value must be replaced */
  308. public static readonly REPLACE = 0x1E01;
  309. /** Passed to stencilOperation to specify that stencil value must be incremented */
  310. public static readonly INCR = 0x1E02;
  311. /** Passed to stencilOperation to specify that stencil value must be decremented */
  312. public static readonly DECR = 0x1E03;
  313. /** Passed to stencilOperation to specify that stencil value must be inverted */
  314. public static readonly INVERT = 0x150A;
  315. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  316. public static readonly INCR_WRAP = 0x8507;
  317. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  318. public static readonly DECR_WRAP = 0x8508;
  319. /** Texture is not repeating outside of 0..1 UVs */
  320. public static readonly TEXTURE_CLAMP_ADDRESSMODE = 0;
  321. /** Texture is repeating outside of 0..1 UVs */
  322. public static readonly TEXTURE_WRAP_ADDRESSMODE = 1;
  323. /** Texture is repeating and mirrored */
  324. public static readonly TEXTURE_MIRROR_ADDRESSMODE = 2;
  325. /** ALPHA */
  326. public static readonly TEXTUREFORMAT_ALPHA = 0;
  327. /** LUMINANCE */
  328. public static readonly TEXTUREFORMAT_LUMINANCE = 1;
  329. /** LUMINANCE_ALPHA */
  330. public static readonly TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  331. /** RGB */
  332. public static readonly TEXTUREFORMAT_RGB = 4;
  333. /** RGBA */
  334. public static readonly TEXTUREFORMAT_RGBA = 5;
  335. /** R */
  336. public static readonly TEXTUREFORMAT_R = 6;
  337. /** RG */
  338. public static readonly TEXTUREFORMAT_RG = 7;
  339. /** UNSIGNED_INT */
  340. public static readonly TEXTURETYPE_UNSIGNED_INT = 0;
  341. /** FLOAT */
  342. public static readonly TEXTURETYPE_FLOAT = 1;
  343. /** HALF_FLOAT */
  344. public static readonly TEXTURETYPE_HALF_FLOAT = 2;
  345. /** nearest is mag = nearest and min = nearest and mip = linear */
  346. public static readonly TEXTURE_NEAREST_SAMPLINGMODE = 1;
  347. /** Bilinear is mag = linear and min = linear and mip = nearest */
  348. public static readonly TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  349. /** Trilinear is mag = linear and min = linear and mip = linear */
  350. public static readonly TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  351. /** nearest is mag = nearest and min = nearest and mip = linear */
  352. public static readonly TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  353. /** Bilinear is mag = linear and min = linear and mip = nearest */
  354. public static readonly TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  355. /** Trilinear is mag = linear and min = linear and mip = linear */
  356. public static readonly TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  357. /** mag = nearest and min = nearest and mip = nearest */
  358. public static readonly TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  359. /** mag = nearest and min = linear and mip = nearest */
  360. public static readonly TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  361. /** mag = nearest and min = linear and mip = linear */
  362. public static readonly TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  363. /** mag = nearest and min = linear and mip = none */
  364. public static readonly TEXTURE_NEAREST_LINEAR = 7;
  365. /** mag = nearest and min = nearest and mip = none */
  366. public static readonly TEXTURE_NEAREST_NEAREST = 8;
  367. /** mag = linear and min = nearest and mip = nearest */
  368. public static readonly TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  369. /** mag = linear and min = nearest and mip = linear */
  370. public static readonly TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  371. /** mag = linear and min = linear and mip = none */
  372. public static readonly TEXTURE_LINEAR_LINEAR = 11;
  373. /** mag = linear and min = nearest and mip = none */
  374. public static readonly TEXTURE_LINEAR_NEAREST = 12;
  375. /** Explicit coordinates mode */
  376. public static readonly TEXTURE_EXPLICIT_MODE = 0;
  377. /** Spherical coordinates mode */
  378. public static readonly TEXTURE_SPHERICAL_MODE = 1;
  379. /** Planar coordinates mode */
  380. public static readonly TEXTURE_PLANAR_MODE = 2;
  381. /** Cubic coordinates mode */
  382. public static readonly TEXTURE_CUBIC_MODE = 3;
  383. /** Projection coordinates mode */
  384. public static readonly TEXTURE_PROJECTION_MODE = 4;
  385. /** Skybox coordinates mode */
  386. public static readonly TEXTURE_SKYBOX_MODE = 5;
  387. /** Inverse Cubic coordinates mode */
  388. public static readonly TEXTURE_INVCUBIC_MODE = 6;
  389. /** Equirectangular coordinates mode */
  390. public static readonly TEXTURE_EQUIRECTANGULAR_MODE = 7;
  391. /** Equirectangular Fixed coordinates mode */
  392. public static readonly TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  393. /** Equirectangular Fixed Mirrored coordinates mode */
  394. public static readonly TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  395. // Texture rescaling mode
  396. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  397. public static readonly SCALEMODE_FLOOR = 1;
  398. /** Defines that texture rescaling will look for the nearest power of 2 size */
  399. public static readonly SCALEMODE_NEAREST = 2;
  400. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  401. public static readonly SCALEMODE_CEILING = 3;
  402. /**
  403. * Returns the current version of the framework
  404. */
  405. public static get Version(): string {
  406. return "3.3.0-alpha.13";
  407. }
  408. // Updatable statics so stick with vars here
  409. /**
  410. * Gets or sets the epsilon value used by collision engine
  411. */
  412. public static CollisionsEpsilon = 0.001;
  413. /**
  414. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  415. */
  416. public static CodeRepository = "src/";
  417. /**
  418. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  419. */
  420. public static ShadersRepository = "src/Shaders/";
  421. // Public members
  422. /**
  423. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  424. */
  425. public forcePOTTextures = false;
  426. /**
  427. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  428. */
  429. public isFullscreen = false;
  430. /**
  431. * Gets a boolean indicating if the pointer is currently locked
  432. */
  433. public isPointerLock = false;
  434. /**
  435. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  436. */
  437. public cullBackFaces = true;
  438. /**
  439. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  440. */
  441. public renderEvenInBackground = true;
  442. /**
  443. * Gets or sets a boolean indicating that cache can be kept between frames
  444. */
  445. public preventCacheWipeBetweenFrames = false;
  446. /**
  447. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  448. **/
  449. public enableOfflineSupport = false;
  450. /**
  451. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  452. **/
  453. public disableManifestCheck = false;
  454. /**
  455. * Gets the list of created scenes
  456. */
  457. public scenes = new Array<Scene>();
  458. /**
  459. * Gets the list of created postprocesses
  460. */
  461. public postProcesses = new Array<PostProcess>();
  462. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  463. public validateShaderPrograms = false;
  464. // Observables
  465. /**
  466. * Observable event triggered each time the rendering canvas is resized
  467. */
  468. public onResizeObservable = new Observable<Engine>();
  469. /**
  470. * Observable event triggered each time the canvas loses focus
  471. */
  472. public onCanvasBlurObservable = new Observable<Engine>();
  473. /**
  474. * Observable event triggered each time the canvas gains focus
  475. */
  476. public onCanvasFocusObservable = new Observable<Engine>();
  477. /**
  478. * Observable event triggered each time the canvas receives pointerout event
  479. */
  480. public onCanvasPointerOutObservable = new Observable<PointerEvent>();
  481. /**
  482. * Observable event triggered before each texture is initialized
  483. */
  484. public onBeforeTextureInitObservable = new Observable<Texture>();
  485. //WebVR
  486. private _vrDisplay: any = undefined;
  487. private _vrSupported: boolean = false;
  488. private _oldSize: Size;
  489. private _oldHardwareScaleFactor: number;
  490. private _vrExclusivePointerMode = false;
  491. private _webVRInitPromise: Promise<IDisplayChangedEventArgs>;
  492. /**
  493. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  494. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  495. */
  496. public get isInVRExclusivePointerMode(): boolean {
  497. return this._vrExclusivePointerMode;
  498. }
  499. // Uniform buffers list
  500. /**
  501. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  502. */
  503. public disableUniformBuffers = false;
  504. /** @hidden */
  505. public _uniformBuffers = new Array<UniformBuffer>();
  506. /**
  507. * Gets a boolean indicating that the engine supports uniform buffers
  508. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  509. */
  510. public get supportsUniformBuffers(): boolean {
  511. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  512. }
  513. // Observables
  514. /**
  515. * Observable raised when the engine begins a new frame
  516. */
  517. public onBeginFrameObservable = new Observable<Engine>();
  518. /**
  519. * Observable raised when the engine ends the current frame
  520. */
  521. public onEndFrameObservable = new Observable<Engine>();
  522. /**
  523. * Observable raised when the engine is about to compile a shader
  524. */
  525. public onBeforeShaderCompilationObservable = new Observable<Engine>();
  526. /**
  527. * Observable raised when the engine has jsut compiled a shader
  528. */
  529. public onAfterShaderCompilationObservable = new Observable<Engine>();
  530. // Private Members
  531. /** @hidden */
  532. public _gl: WebGLRenderingContext;
  533. private _renderingCanvas: Nullable<HTMLCanvasElement>;
  534. private _windowIsBackground = false;
  535. private _webGLVersion = 1.0;
  536. /**
  537. * Gets a boolean indicating that only power of 2 textures are supported
  538. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  539. */
  540. public get needPOTTextures(): boolean {
  541. return this._webGLVersion < 2 || this.forcePOTTextures;
  542. }
  543. /** @hidden */
  544. public _badOS = false;
  545. /** @hidden */
  546. public _badDesktopOS = false;
  547. /**
  548. * Gets or sets a value indicating if we want to disable texture binding optmization.
  549. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  550. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  551. */
  552. public disableTextureBindingOptimization = false;
  553. /**
  554. * Gets the audio engine
  555. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  556. * @ignorenaming
  557. */
  558. public static audioEngine: AudioEngine;
  559. // Focus
  560. private _onFocus: () => void;
  561. private _onBlur: () => void;
  562. private _onCanvasPointerOut: (event: PointerEvent) => void;
  563. private _onCanvasBlur: () => void;
  564. private _onCanvasFocus: () => void;
  565. private _onFullscreenChange: () => void;
  566. private _onPointerLockChange: () => void;
  567. private _onVRDisplayPointerRestricted: () => void;
  568. private _onVRDisplayPointerUnrestricted: () => void;
  569. // VRDisplay connection
  570. private _onVrDisplayConnect: Nullable<(display: any) => void>;
  571. private _onVrDisplayDisconnect: Nullable<() => void>;
  572. private _onVrDisplayPresentChange: Nullable<() => void>;
  573. /**
  574. * Observable signaled when VR display mode changes
  575. */
  576. public onVRDisplayChangedObservable = new Observable<IDisplayChangedEventArgs>();
  577. /**
  578. * Observable signaled when VR request present is complete
  579. */
  580. public onVRRequestPresentComplete = new Observable<boolean>();
  581. /**
  582. * Observable signaled when VR request present starts
  583. */
  584. public onVRRequestPresentStart = new Observable<Engine>();
  585. private _hardwareScalingLevel: number;
  586. /** @hidden */
  587. protected _caps: EngineCapabilities;
  588. private _pointerLockRequested: boolean;
  589. private _isStencilEnable: boolean;
  590. private _colorWrite = true;
  591. private _loadingScreen: ILoadingScreen;
  592. /** @hidden */
  593. public _drawCalls = new PerfCounter();
  594. /** @hidden */
  595. public _textureCollisions = new PerfCounter();
  596. private _glVersion: string;
  597. private _glRenderer: string;
  598. private _glVendor: string;
  599. private _videoTextureSupported: boolean;
  600. private _renderingQueueLaunched = false;
  601. private _activeRenderLoops = new Array<() => void>();
  602. // Deterministic lockstepMaxSteps
  603. private _deterministicLockstep: boolean = false;
  604. private _lockstepMaxSteps: number = 4;
  605. // Lost context
  606. /**
  607. * Observable signaled when a context lost event is raised
  608. */
  609. public onContextLostObservable = new Observable<Engine>();
  610. /**
  611. * Observable signaled when a context restored event is raised
  612. */
  613. public onContextRestoredObservable = new Observable<Engine>();
  614. private _onContextLost: (evt: Event) => void;
  615. private _onContextRestored: (evt: Event) => void;
  616. private _contextWasLost = false;
  617. private _doNotHandleContextLost = false;
  618. /**
  619. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  620. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  621. */
  622. public get doNotHandleContextLost(): boolean {
  623. return this._doNotHandleContextLost;
  624. }
  625. public set doNotHandleContextLost(value: boolean) {
  626. this._doNotHandleContextLost = value;
  627. }
  628. // FPS
  629. private _performanceMonitor = new PerformanceMonitor();
  630. private _fps = 60;
  631. private _deltaTime = 0;
  632. /**
  633. * Turn this value on if you want to pause FPS computation when in background
  634. */
  635. public disablePerformanceMonitorInBackground = false;
  636. /**
  637. * Gets the performance monitor attached to this engine
  638. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  639. */
  640. public get performanceMonitor(): PerformanceMonitor {
  641. return this._performanceMonitor;
  642. }
  643. // States
  644. /** @hidden */
  645. protected _depthCullingState = new _DepthCullingState();
  646. /** @hidden */
  647. protected _stencilState = new _StencilState();
  648. /** @hidden */
  649. protected _alphaState = new _AlphaState();
  650. /** @hidden */
  651. protected _alphaMode = Engine.ALPHA_DISABLE;
  652. // Cache
  653. protected _internalTexturesCache = new Array<InternalTexture>();
  654. /** @hidden */
  655. protected _activeChannel = 0;
  656. private _currentTextureChannel = -1;
  657. /** @hidden */
  658. protected _boundTexturesCache: { [key: string]: Nullable<InternalTexture> } = {};
  659. /** @hidden */
  660. protected _currentEffect: Nullable<Effect>;
  661. /** @hidden */
  662. protected _currentProgram: Nullable<WebGLProgram>;
  663. private _compiledEffects: { [key: string]: Effect } = {}
  664. private _vertexAttribArraysEnabled: boolean[] = [];
  665. /** @hidden */
  666. protected _cachedViewport: Nullable<Viewport>;
  667. private _cachedVertexArrayObject: Nullable<WebGLVertexArrayObject>;
  668. /** @hidden */
  669. protected _cachedVertexBuffers: any;
  670. /** @hidden */
  671. protected _cachedIndexBuffer: Nullable<WebGLBuffer>;
  672. /** @hidden */
  673. protected _cachedEffectForVertexBuffers: Nullable<Effect>;
  674. /** @hidden */
  675. protected _currentRenderTarget: Nullable<InternalTexture>;
  676. private _uintIndicesCurrentlySet = false;
  677. private _currentBoundBuffer = new Array<Nullable<WebGLBuffer>>();
  678. /** @hidden */
  679. protected _currentFramebuffer: Nullable<WebGLFramebuffer> = null;
  680. private _currentBufferPointers = new Array<BufferPointer>();
  681. private _currentInstanceLocations = new Array<number>();
  682. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  683. private _textureUnits: Int32Array;
  684. private _firstBoundInternalTextureTracker = new DummyInternalTextureTracker();
  685. private _lastBoundInternalTextureTracker = new DummyInternalTextureTracker();
  686. private _workingCanvas: Nullable<HTMLCanvasElement>;
  687. private _workingContext: Nullable<CanvasRenderingContext2D>;
  688. private _rescalePostProcess: PassPostProcess;
  689. private _dummyFramebuffer: WebGLFramebuffer;
  690. private _externalData: StringDictionary<Object>;
  691. private _bindedRenderFunction: any;
  692. private _vaoRecordInProgress = false;
  693. private _mustWipeVertexAttributes = false;
  694. private _emptyTexture: Nullable<InternalTexture>;
  695. private _emptyCubeTexture: Nullable<InternalTexture>;
  696. private _emptyTexture3D: Nullable<InternalTexture>;
  697. private _frameHandler: number;
  698. private _nextFreeTextureSlots = new Array<number>();
  699. private _maxSimultaneousTextures = 0;
  700. private _activeRequests = new Array<IFileRequest>();
  701. // Hardware supported Compressed Textures
  702. private _texturesSupported = new Array<string>();
  703. private _textureFormatInUse: Nullable<string>;
  704. /**
  705. * Gets the list of texture formats supported
  706. */
  707. public get texturesSupported(): Array<string> {
  708. return this._texturesSupported;
  709. }
  710. /**
  711. * Gets the list of texture formats in use
  712. */
  713. public get textureFormatInUse(): Nullable<string> {
  714. return this._textureFormatInUse;
  715. }
  716. /**
  717. * Gets the current viewport
  718. */
  719. public get currentViewport(): Nullable<Viewport> {
  720. return this._cachedViewport;
  721. }
  722. /**
  723. * Gets the default empty texture
  724. */
  725. public get emptyTexture(): InternalTexture {
  726. if (!this._emptyTexture) {
  727. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  728. }
  729. return this._emptyTexture;
  730. }
  731. /**
  732. * Gets the default empty 3D texture
  733. */
  734. public get emptyTexture3D(): InternalTexture {
  735. if (!this._emptyTexture3D) {
  736. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  737. }
  738. return this._emptyTexture3D;
  739. }
  740. /**
  741. * Gets the default empty cube texture
  742. */
  743. public get emptyCubeTexture(): InternalTexture {
  744. if (!this._emptyCubeTexture) {
  745. var faceData = new Uint8Array(4);
  746. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  747. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  748. }
  749. return this._emptyCubeTexture;
  750. }
  751. /**
  752. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  753. */
  754. public readonly premultipliedAlpha: boolean = true;
  755. /**
  756. * Creates a new engine
  757. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  758. * @param antialias defines enable antialiasing (default: false)
  759. * @param options defines further options to be sent to the getContext() function
  760. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  761. */
  762. constructor(canvasOrContext: Nullable<HTMLCanvasElement | WebGLRenderingContext>, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio: boolean = false) {
  763. // Register promises
  764. PromisePolyfill.Apply();
  765. let canvas: Nullable<HTMLCanvasElement> = null;
  766. Engine.Instances.push(this);
  767. if (!canvasOrContext) {
  768. return;
  769. }
  770. options = options || {};
  771. if ((<HTMLCanvasElement>canvasOrContext).getContext) {
  772. canvas = <HTMLCanvasElement>canvasOrContext;
  773. this._renderingCanvas = canvas;
  774. if (antialias != null) {
  775. options.antialias = antialias;
  776. }
  777. if (options.deterministicLockstep === undefined) {
  778. options.deterministicLockstep = false;
  779. }
  780. if (options.lockstepMaxSteps === undefined) {
  781. options.lockstepMaxSteps = 4;
  782. }
  783. if (options.preserveDrawingBuffer === undefined) {
  784. options.preserveDrawingBuffer = false;
  785. }
  786. if (options.audioEngine === undefined) {
  787. options.audioEngine = true;
  788. }
  789. if (options.stencil === undefined) {
  790. options.stencil = true;
  791. }
  792. if (options.premultipliedAlpha === false) {
  793. this.premultipliedAlpha = false;
  794. }
  795. this._deterministicLockstep = options.deterministicLockstep;
  796. this._lockstepMaxSteps = options.lockstepMaxSteps;
  797. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  798. // Exceptions
  799. if (navigator && navigator.userAgent) {
  800. let ua = navigator.userAgent;
  801. for (var exception of Engine.ExceptionList) {
  802. let key = exception.key;
  803. let targets = exception.targets;
  804. if (ua.indexOf(key) > -1) {
  805. if (exception.capture && exception.captureConstraint) {
  806. let capture = exception.capture;
  807. let constraint = exception.captureConstraint;
  808. let regex = new RegExp(capture);
  809. let matches = regex.exec(ua);
  810. if (matches && matches.length > 0) {
  811. let capturedValue = parseInt(matches[matches.length - 1]);
  812. if (capturedValue >= constraint) {
  813. continue;
  814. }
  815. }
  816. }
  817. for (var target of targets) {
  818. switch (target) {
  819. case "uniformBuffer":
  820. this.disableUniformBuffers = true;
  821. break;
  822. case "textureBindingOptimization":
  823. this.disableTextureBindingOptimization = true;
  824. break;
  825. }
  826. }
  827. }
  828. }
  829. }
  830. // GL
  831. if (!options.disableWebGL2Support) {
  832. try {
  833. this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  834. if (this._gl) {
  835. this._webGLVersion = 2.0;
  836. }
  837. } catch (e) {
  838. // Do nothing
  839. }
  840. }
  841. if (!this._gl) {
  842. if (!canvas) {
  843. throw new Error("The provided canvas is null or undefined.");
  844. }
  845. try {
  846. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  847. } catch (e) {
  848. throw new Error("WebGL not supported");
  849. }
  850. }
  851. if (!this._gl) {
  852. throw new Error("WebGL not supported");
  853. }
  854. this._onCanvasFocus = () => {
  855. this.onCanvasFocusObservable.notifyObservers(this);
  856. }
  857. this._onCanvasBlur = () => {
  858. this.onCanvasBlurObservable.notifyObservers(this);
  859. }
  860. canvas.addEventListener("focus", this._onCanvasFocus);
  861. canvas.addEventListener("blur", this._onCanvasBlur);
  862. this._onBlur = () => {
  863. if (this.disablePerformanceMonitorInBackground) {
  864. this._performanceMonitor.disable();
  865. }
  866. this._windowIsBackground = true;
  867. };
  868. this._onFocus = () => {
  869. if (this.disablePerformanceMonitorInBackground) {
  870. this._performanceMonitor.enable();
  871. }
  872. this._windowIsBackground = false;
  873. };
  874. this._onCanvasPointerOut = (ev) => {
  875. this.onCanvasPointerOutObservable.notifyObservers(ev);
  876. };
  877. window.addEventListener("blur", this._onBlur);
  878. window.addEventListener("focus", this._onFocus);
  879. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  880. // Context lost
  881. if (!this._doNotHandleContextLost) {
  882. this._onContextLost = (evt: Event) => {
  883. evt.preventDefault();
  884. this._contextWasLost = true;
  885. Tools.Warn("WebGL context lost.");
  886. this.onContextLostObservable.notifyObservers(this);
  887. };
  888. this._onContextRestored = (evt: Event) => {
  889. // Adding a timeout to avoid race condition at browser level
  890. setTimeout(() => {
  891. // Rebuild gl context
  892. this._initGLContext();
  893. // Rebuild effects
  894. this._rebuildEffects();
  895. // Rebuild textures
  896. this._rebuildInternalTextures();
  897. // Rebuild buffers
  898. this._rebuildBuffers();
  899. // Cache
  900. this.wipeCaches(true);
  901. Tools.Warn("WebGL context successfully restored.");
  902. this.onContextRestoredObservable.notifyObservers(this);
  903. this._contextWasLost = false;
  904. }, 0);
  905. };
  906. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  907. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  908. }
  909. } else {
  910. this._gl = <WebGLRenderingContext>canvasOrContext;
  911. this._renderingCanvas = this._gl.canvas
  912. if (this._gl.renderbufferStorageMultisample) {
  913. this._webGLVersion = 2.0;
  914. }
  915. options.stencil = this._gl.getContextAttributes().stencil;
  916. }
  917. // Viewport
  918. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  919. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  920. this.resize();
  921. this._isStencilEnable = options.stencil ? true : false;
  922. this._initGLContext();
  923. if (canvas) {
  924. // Fullscreen
  925. this._onFullscreenChange = () => {
  926. if (document.fullscreen !== undefined) {
  927. this.isFullscreen = document.fullscreen;
  928. } else if (document.mozFullScreen !== undefined) {
  929. this.isFullscreen = document.mozFullScreen;
  930. } else if (document.webkitIsFullScreen !== undefined) {
  931. this.isFullscreen = document.webkitIsFullScreen;
  932. } else if (document.msIsFullScreen !== undefined) {
  933. this.isFullscreen = document.msIsFullScreen;
  934. }
  935. // Pointer lock
  936. if (this.isFullscreen && this._pointerLockRequested && canvas) {
  937. canvas.requestPointerLock = canvas.requestPointerLock ||
  938. canvas.msRequestPointerLock ||
  939. canvas.mozRequestPointerLock ||
  940. canvas.webkitRequestPointerLock;
  941. if (canvas.requestPointerLock) {
  942. canvas.requestPointerLock();
  943. }
  944. }
  945. };
  946. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  947. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  948. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  949. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  950. // Pointer lock
  951. this._onPointerLockChange = () => {
  952. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  953. document.webkitPointerLockElement === canvas ||
  954. document.msPointerLockElement === canvas ||
  955. document.pointerLockElement === canvas
  956. );
  957. };
  958. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  959. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  960. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  961. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  962. this._onVRDisplayPointerRestricted = () => {
  963. if (canvas) {
  964. canvas.requestPointerLock();
  965. }
  966. }
  967. this._onVRDisplayPointerUnrestricted = () => {
  968. document.exitPointerLock();
  969. }
  970. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  971. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  972. }
  973. if (options.audioEngine && AudioEngine && !Engine.audioEngine) {
  974. Engine.audioEngine = new AudioEngine();
  975. }
  976. // Prepare buffer pointers
  977. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  978. this._currentBufferPointers[i] = new BufferPointer();
  979. }
  980. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  981. // Load WebVR Devices
  982. if (options.autoEnableWebVR) {
  983. this.initWebVR();
  984. }
  985. // Detect if we are running on a faulty buggy OS.
  986. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  987. // Detect if we are running on a faulty buggy desktop OS.
  988. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  989. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  990. this.enableOfflineSupport = (Database !== undefined);
  991. }
  992. private _rebuildInternalTextures(): void {
  993. let currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  994. for (var internalTexture of currentState) {
  995. internalTexture._rebuild();
  996. }
  997. }
  998. private _rebuildEffects(): void {
  999. for (var key in this._compiledEffects) {
  1000. let effect = <Effect>this._compiledEffects[key];
  1001. effect._prepareEffect();
  1002. }
  1003. Effect.ResetCache();
  1004. }
  1005. private _rebuildBuffers(): void {
  1006. // Index / Vertex
  1007. for (var scene of this.scenes) {
  1008. scene.resetCachedMaterial();
  1009. scene._rebuildGeometries();
  1010. scene._rebuildTextures();
  1011. }
  1012. // Uniforms
  1013. for (var uniformBuffer of this._uniformBuffers) {
  1014. uniformBuffer._rebuild();
  1015. }
  1016. }
  1017. private _initGLContext(): void {
  1018. // Caps
  1019. this._caps = new EngineCapabilities();
  1020. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  1021. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  1022. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  1023. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  1024. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  1025. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  1026. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  1027. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  1028. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  1029. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  1030. // Infos
  1031. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  1032. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  1033. if (rendererInfo != null) {
  1034. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  1035. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  1036. }
  1037. if (!this._glVendor) {
  1038. this._glVendor = "Unknown vendor";
  1039. }
  1040. if (!this._glRenderer) {
  1041. this._glRenderer = "Unknown renderer";
  1042. }
  1043. // Constants
  1044. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  1045. if (this._gl.RGBA16F !== 0x881A) {
  1046. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  1047. }
  1048. if (this._gl.RGBA32F !== 0x8814) {
  1049. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  1050. }
  1051. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  1052. this._gl.DEPTH24_STENCIL8 = 35056;
  1053. }
  1054. // Extensions
  1055. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  1056. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  1057. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  1058. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  1059. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  1060. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  1061. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  1062. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  1063. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  1064. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  1065. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  1066. this._caps.highPrecisionShaderSupported = true;
  1067. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  1068. if (this._caps.timerQuery) {
  1069. if (this._webGLVersion === 1) {
  1070. this._gl.getQuery = (<any>this._caps.timerQuery).getQueryEXT.bind(this._caps.timerQuery);
  1071. }
  1072. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  1073. }
  1074. // Checks if some of the format renders first to allow the use of webgl inspector.
  1075. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  1076. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  1077. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  1078. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true: false;
  1079. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true: false;
  1080. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  1081. if (this._webGLVersion > 1) {
  1082. this._gl.HALF_FLOAT_OES = 0x140B;
  1083. }
  1084. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  1085. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true: false;
  1086. // Draw buffers
  1087. if (this._webGLVersion > 1) {
  1088. this._caps.drawBuffersExtension = true;
  1089. } else {
  1090. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  1091. if (drawBuffersExtension !== null) {
  1092. this._caps.drawBuffersExtension = true;
  1093. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  1094. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  1095. for (var i = 0; i < 16; i++) {
  1096. (<any>this._gl)["COLOR_ATTACHMENT" + i + "_WEBGL"] = (<any>drawBuffersExtension)["COLOR_ATTACHMENT" + i + "_WEBGL"];
  1097. }
  1098. } else {
  1099. this._caps.drawBuffersExtension = false;
  1100. }
  1101. }
  1102. // Depth Texture
  1103. if (this._webGLVersion > 1) {
  1104. this._caps.depthTextureExtension = true;
  1105. } else {
  1106. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  1107. if (depthTextureExtension != null) {
  1108. this._caps.depthTextureExtension = true;
  1109. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  1110. }
  1111. }
  1112. // Vertex array object
  1113. if (this._webGLVersion > 1) {
  1114. this._caps.vertexArrayObject = true;
  1115. } else {
  1116. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  1117. if (vertexArrayObjectExtension != null) {
  1118. this._caps.vertexArrayObject = true;
  1119. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  1120. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  1121. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  1122. } else {
  1123. this._caps.vertexArrayObject = false;
  1124. }
  1125. }
  1126. // Instances count
  1127. if (this._webGLVersion > 1) {
  1128. this._caps.instancedArrays = true;
  1129. } else {
  1130. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  1131. if (instanceExtension != null) {
  1132. this._caps.instancedArrays = true;
  1133. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  1134. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  1135. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  1136. } else {
  1137. this._caps.instancedArrays = false;
  1138. }
  1139. }
  1140. // Intelligently add supported compressed formats in order to check for.
  1141. // Check for ASTC support first as it is most powerful and to be very cross platform.
  1142. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  1143. // Likely no hardware which supports both PVR & DXT, so order matters little.
  1144. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  1145. if (this._caps.astc) this.texturesSupported.push('-astc.ktx');
  1146. if (this._caps.s3tc) this.texturesSupported.push('-dxt.ktx');
  1147. if (this._caps.pvrtc) this.texturesSupported.push('-pvrtc.ktx');
  1148. if (this._caps.etc2) this.texturesSupported.push('-etc2.ktx');
  1149. if (this._caps.etc1) this.texturesSupported.push('-etc1.ktx');
  1150. if (this._gl.getShaderPrecisionFormat) {
  1151. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  1152. if (highp) {
  1153. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  1154. }
  1155. }
  1156. // Depth buffer
  1157. this.setDepthBuffer(true);
  1158. this.setDepthFunctionToLessOrEqual();
  1159. this.setDepthWrite(true);
  1160. // Texture maps
  1161. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  1162. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1163. this._nextFreeTextureSlots.push(slot);
  1164. }
  1165. }
  1166. /**
  1167. * Gets version of the current webGL context
  1168. */
  1169. public get webGLVersion(): number {
  1170. return this._webGLVersion;
  1171. }
  1172. /**
  1173. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  1174. */
  1175. public get isStencilEnable(): boolean {
  1176. return this._isStencilEnable;
  1177. }
  1178. private _prepareWorkingCanvas(): void {
  1179. if (this._workingCanvas) {
  1180. return;
  1181. }
  1182. this._workingCanvas = document.createElement("canvas");
  1183. let context = this._workingCanvas.getContext("2d");
  1184. if (context) {
  1185. this._workingContext = context;
  1186. }
  1187. }
  1188. /**
  1189. * Reset the texture cache to empty state
  1190. */
  1191. public resetTextureCache() {
  1192. for (var key in this._boundTexturesCache) {
  1193. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  1194. continue;
  1195. }
  1196. let boundTexture = this._boundTexturesCache[key];
  1197. if (boundTexture) {
  1198. this._removeDesignatedSlot(boundTexture);
  1199. }
  1200. this._boundTexturesCache[key] = null;
  1201. }
  1202. if (!this.disableTextureBindingOptimization) {
  1203. this._nextFreeTextureSlots = [];
  1204. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1205. this._nextFreeTextureSlots.push(slot);
  1206. }
  1207. }
  1208. this._currentTextureChannel = -1;
  1209. }
  1210. /**
  1211. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  1212. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  1213. * @returns true if engine is in deterministic lock step mode
  1214. */
  1215. public isDeterministicLockStep(): boolean {
  1216. return this._deterministicLockstep;
  1217. }
  1218. /**
  1219. * Gets the max steps when engine is running in deterministic lock step
  1220. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  1221. * @returns the max steps
  1222. */
  1223. public getLockstepMaxSteps(): number {
  1224. return this._lockstepMaxSteps;
  1225. }
  1226. /**
  1227. * Gets an object containing information about the current webGL context
  1228. * @returns an object containing the vender, the renderer and the version of the current webGL context
  1229. */
  1230. public getGlInfo() {
  1231. return {
  1232. vendor: this._glVendor,
  1233. renderer: this._glRenderer,
  1234. version: this._glVersion
  1235. }
  1236. }
  1237. /**
  1238. * Gets current aspect ratio
  1239. * @param camera defines the camera to use to get the aspect ratio
  1240. * @param useScreen defines if screen size must be used (or the current render target if any)
  1241. * @returns a number defining the aspect ratio
  1242. */
  1243. public getAspectRatio(camera: Camera, useScreen = false): number {
  1244. var viewport = camera.viewport;
  1245. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  1246. }
  1247. /**
  1248. * Gets current screen aspect ratio
  1249. * @returns a number defining the aspect ratio
  1250. */
  1251. public getScreenAspectRatio(): number {
  1252. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  1253. }
  1254. /**
  1255. * Gets the current render width
  1256. * @param useScreen defines if screen size must be used (or the current render target if any)
  1257. * @returns a number defining the current render width
  1258. */
  1259. public getRenderWidth(useScreen = false): number {
  1260. if (!useScreen && this._currentRenderTarget) {
  1261. return this._currentRenderTarget.width;
  1262. }
  1263. return this._gl.drawingBufferWidth;
  1264. }
  1265. /**
  1266. * Gets the current render height
  1267. * @param useScreen defines if screen size must be used (or the current render target if any)
  1268. * @returns a number defining the current render height
  1269. */
  1270. public getRenderHeight(useScreen = false): number {
  1271. if (!useScreen && this._currentRenderTarget) {
  1272. return this._currentRenderTarget.height;
  1273. }
  1274. return this._gl.drawingBufferHeight;
  1275. }
  1276. /**
  1277. * Gets the HTML canvas attached with the current webGL context
  1278. * @returns a HTML canvas
  1279. */
  1280. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  1281. return this._renderingCanvas;
  1282. }
  1283. /**
  1284. * Gets the client rect of the HTML canvas attached with the current webGL context
  1285. * @returns a client rectanglee
  1286. */
  1287. public getRenderingCanvasClientRect(): Nullable<ClientRect> {
  1288. if (!this._renderingCanvas) {
  1289. return null;
  1290. }
  1291. return this._renderingCanvas.getBoundingClientRect();
  1292. }
  1293. /**
  1294. * Defines the hardware scaling level.
  1295. * By default the hardware scaling level is computed from the window device ratio.
  1296. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  1297. * @param level defines the level to use
  1298. */
  1299. public setHardwareScalingLevel(level: number): void {
  1300. this._hardwareScalingLevel = level;
  1301. this.resize();
  1302. }
  1303. /**
  1304. * Gets the current hardware scaling level.
  1305. * By default the hardware scaling level is computed from the window device ratio.
  1306. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  1307. * @returns a number indicating the current hardware scaling level
  1308. */
  1309. public getHardwareScalingLevel(): number {
  1310. return this._hardwareScalingLevel;
  1311. }
  1312. /**
  1313. * Gets the list of loaded textures
  1314. * @returns an array containing all loaded textures
  1315. */
  1316. public getLoadedTexturesCache(): InternalTexture[] {
  1317. return this._internalTexturesCache;
  1318. }
  1319. /**
  1320. * Gets the object containing all engine capabilities
  1321. * @returns the EngineCapabilities object
  1322. */
  1323. public getCaps(): EngineCapabilities {
  1324. return this._caps;
  1325. }
  1326. /** @hidden */
  1327. public get drawCalls(): number {
  1328. Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  1329. return 0;
  1330. }
  1331. /** @hidden */
  1332. public get drawCallsPerfCounter(): Nullable<PerfCounter> {
  1333. Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  1334. return null;
  1335. }
  1336. /**
  1337. * Gets the current depth function
  1338. * @returns a number defining the depth function
  1339. */
  1340. public getDepthFunction(): Nullable<number> {
  1341. return this._depthCullingState.depthFunc;
  1342. }
  1343. /**
  1344. * Sets the current depth function
  1345. * @param depthFunc defines the function to use
  1346. */
  1347. public setDepthFunction(depthFunc: number) {
  1348. this._depthCullingState.depthFunc = depthFunc;
  1349. }
  1350. /**
  1351. * Sets the current depth function to GREATER
  1352. */
  1353. public setDepthFunctionToGreater(): void {
  1354. this._depthCullingState.depthFunc = this._gl.GREATER;
  1355. }
  1356. /**
  1357. * Sets the current depth function to GEQUAL
  1358. */
  1359. public setDepthFunctionToGreaterOrEqual(): void {
  1360. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  1361. }
  1362. /**
  1363. * Sets the current depth function to LESS
  1364. */
  1365. public setDepthFunctionToLess(): void {
  1366. this._depthCullingState.depthFunc = this._gl.LESS;
  1367. }
  1368. /**
  1369. * Sets the current depth function to LEQUAL
  1370. */
  1371. public setDepthFunctionToLessOrEqual(): void {
  1372. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  1373. }
  1374. /**
  1375. * Gets a boolean indicating if stencil buffer is enabled
  1376. * @returns the current stencil buffer state
  1377. */
  1378. public getStencilBuffer(): boolean {
  1379. return this._stencilState.stencilTest;
  1380. }
  1381. /**
  1382. * Enable or disable the stencil buffer
  1383. * @param enable defines if the stencil buffer must be enabled or disabled
  1384. */
  1385. public setStencilBuffer(enable: boolean): void {
  1386. this._stencilState.stencilTest = enable;
  1387. }
  1388. /**
  1389. * Gets the current stencil mask
  1390. * @returns a number defining the new stencil mask to use
  1391. */
  1392. public getStencilMask(): number {
  1393. return this._stencilState.stencilMask;
  1394. }
  1395. /**
  1396. * Sets the current stencil mask
  1397. * @param mask defines the new stencil mask to use
  1398. */
  1399. public setStencilMask(mask: number): void {
  1400. this._stencilState.stencilMask = mask;
  1401. }
  1402. /**
  1403. * Gets the current stencil function
  1404. * @returns a number defining the stencil function to use
  1405. */
  1406. public getStencilFunction(): number {
  1407. return this._stencilState.stencilFunc;
  1408. }
  1409. /**
  1410. * Gets the current stencil reference value
  1411. * @returns a number defining the stencil reference value to use
  1412. */
  1413. public getStencilFunctionReference(): number {
  1414. return this._stencilState.stencilFuncRef;
  1415. }
  1416. /**
  1417. * Gets the current stencil mask
  1418. * @returns a number defining the stencil mask to use
  1419. */
  1420. public getStencilFunctionMask(): number {
  1421. return this._stencilState.stencilFuncMask;
  1422. }
  1423. /**
  1424. * Sets the current stencil function
  1425. * @param stencilFunc defines the new stencil function to use
  1426. */
  1427. public setStencilFunction(stencilFunc: number) {
  1428. this._stencilState.stencilFunc = stencilFunc;
  1429. }
  1430. /**
  1431. * Sets the current stencil reference
  1432. * @param reference defines the new stencil reference to use
  1433. */
  1434. public setStencilFunctionReference(reference: number) {
  1435. this._stencilState.stencilFuncRef = reference;
  1436. }
  1437. /**
  1438. * Sets the current stencil mask
  1439. * @param mask defines the new stencil mask to use
  1440. */
  1441. public setStencilFunctionMask(mask: number) {
  1442. this._stencilState.stencilFuncMask = mask;
  1443. }
  1444. /**
  1445. * Gets the current stencil operation when stencil fails
  1446. * @returns a number defining stencil operation to use when stencil fails
  1447. */
  1448. public getStencilOperationFail(): number {
  1449. return this._stencilState.stencilOpStencilFail;
  1450. }
  1451. /**
  1452. * Gets the current stencil operation when depth fails
  1453. * @returns a number defining stencil operation to use when depth fails
  1454. */
  1455. public getStencilOperationDepthFail(): number {
  1456. return this._stencilState.stencilOpDepthFail;
  1457. }
  1458. /**
  1459. * Gets the current stencil operation when stencil passes
  1460. * @returns a number defining stencil operation to use when stencil passes
  1461. */
  1462. public getStencilOperationPass(): number {
  1463. return this._stencilState.stencilOpStencilDepthPass;
  1464. }
  1465. /**
  1466. * Sets the stencil operation to use when stencil fails
  1467. * @param operation defines the stencil operation to use when stencil fails
  1468. */
  1469. public setStencilOperationFail(operation: number): void {
  1470. this._stencilState.stencilOpStencilFail = operation;
  1471. }
  1472. /**
  1473. * Sets the stencil operation to use when depth fails
  1474. * @param operation defines the stencil operation to use when depth fails
  1475. */
  1476. public setStencilOperationDepthFail(operation: number): void {
  1477. this._stencilState.stencilOpDepthFail = operation;
  1478. }
  1479. /**
  1480. * Sets the stencil operation to use when stencil passes
  1481. * @param operation defines the stencil operation to use when stencil passes
  1482. */
  1483. public setStencilOperationPass(operation: number): void {
  1484. this._stencilState.stencilOpStencilDepthPass = operation;
  1485. }
  1486. /**
  1487. * Sets a boolean indicating if the dithering state is enabled or disabled
  1488. * @param value defines the dithering state
  1489. */
  1490. public setDitheringState(value: boolean): void {
  1491. if (value) {
  1492. this._gl.enable(this._gl.DITHER);
  1493. } else {
  1494. this._gl.disable(this._gl.DITHER);
  1495. }
  1496. }
  1497. /**
  1498. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  1499. * @param value defines the rasterizer state
  1500. */
  1501. public setRasterizerState(value: boolean): void {
  1502. if (value) {
  1503. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  1504. } else {
  1505. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  1506. }
  1507. }
  1508. /**
  1509. * stop executing a render loop function and remove it from the execution array
  1510. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  1511. */
  1512. public stopRenderLoop(renderFunction?: () => void): void {
  1513. if (!renderFunction) {
  1514. this._activeRenderLoops = [];
  1515. return;
  1516. }
  1517. var index = this._activeRenderLoops.indexOf(renderFunction);
  1518. if (index >= 0) {
  1519. this._activeRenderLoops.splice(index, 1);
  1520. }
  1521. }
  1522. /** @hidden */
  1523. public _renderLoop(): void {
  1524. if (!this._contextWasLost) {
  1525. var shouldRender = true;
  1526. if (!this.renderEvenInBackground && this._windowIsBackground) {
  1527. shouldRender = false;
  1528. }
  1529. if (shouldRender) {
  1530. // Start new frame
  1531. this.beginFrame();
  1532. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  1533. var renderFunction = this._activeRenderLoops[index];
  1534. renderFunction();
  1535. }
  1536. // Present
  1537. this.endFrame();
  1538. }
  1539. }
  1540. if (this._activeRenderLoops.length > 0) {
  1541. // Register new frame
  1542. var requester = null;
  1543. if (this._vrDisplay && this._vrDisplay.isPresenting)
  1544. requester = this._vrDisplay;
  1545. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  1546. } else {
  1547. this._renderingQueueLaunched = false;
  1548. }
  1549. }
  1550. /**
  1551. * Register and execute a render loop. The engine can have more than one render function
  1552. * @param renderFunction defines the function to continuously execute
  1553. */
  1554. public runRenderLoop(renderFunction: () => void): void {
  1555. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  1556. return;
  1557. }
  1558. this._activeRenderLoops.push(renderFunction);
  1559. if (!this._renderingQueueLaunched) {
  1560. this._renderingQueueLaunched = true;
  1561. this._bindedRenderFunction = this._renderLoop.bind(this);
  1562. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1563. }
  1564. }
  1565. /**
  1566. * Toggle full screen mode
  1567. * @param requestPointerLock defines if a pointer lock should be requested from the user
  1568. * @param options defines an option object to be sent to the requestFullscreen function
  1569. */
  1570. public switchFullscreen(requestPointerLock: boolean): void {
  1571. if (this.isFullscreen) {
  1572. Tools.ExitFullscreen();
  1573. } else {
  1574. this._pointerLockRequested = requestPointerLock;
  1575. if (this._renderingCanvas) {
  1576. Tools.RequestFullscreen(this._renderingCanvas);
  1577. }
  1578. }
  1579. }
  1580. /**
  1581. * Clear the current render buffer or the current render target (if any is set up)
  1582. * @param color defines the color to use
  1583. * @param backBuffer defines if the back buffer must be cleared
  1584. * @param depth defines if the depth buffer must be cleared
  1585. * @param stencil defines if the stencil buffer must be cleared
  1586. */
  1587. public clear(color: Nullable<Color4>, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  1588. this.applyStates();
  1589. var mode = 0;
  1590. if (backBuffer && color) {
  1591. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  1592. mode |= this._gl.COLOR_BUFFER_BIT;
  1593. }
  1594. if (depth) {
  1595. this._gl.clearDepth(1.0);
  1596. mode |= this._gl.DEPTH_BUFFER_BIT;
  1597. }
  1598. if (stencil) {
  1599. this._gl.clearStencil(0);
  1600. mode |= this._gl.STENCIL_BUFFER_BIT;
  1601. }
  1602. this._gl.clear(mode);
  1603. }
  1604. /**
  1605. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  1606. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  1607. * @param y defines the y-coordinate of the corner of the clear rectangle
  1608. * @param width defines the width of the clear rectangle
  1609. * @param height defines the height of the clear rectangle
  1610. * @param clearColor defines the clear color
  1611. */
  1612. public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
  1613. let gl = this._gl;
  1614. // Save state
  1615. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  1616. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  1617. // Change state
  1618. gl.enable(gl.SCISSOR_TEST);
  1619. gl.scissor(x, y, width, height);
  1620. // Clear
  1621. this.clear(clearColor, true, true, true);
  1622. // Restore state
  1623. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  1624. if (curScissor === true) {
  1625. gl.enable(gl.SCISSOR_TEST);
  1626. } else {
  1627. gl.disable(gl.SCISSOR_TEST);
  1628. }
  1629. }
  1630. private _viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  1631. /** @hidden */
  1632. public _viewport(x: number, y: number, width: number, height: number): void {
  1633. if (x !== this._viewportCached.x ||
  1634. y !== this._viewportCached.y ||
  1635. width !== this._viewportCached.z ||
  1636. height !== this._viewportCached.w)
  1637. {
  1638. this._viewportCached.x = x;
  1639. this._viewportCached.y = y;
  1640. this._viewportCached.z = width;
  1641. this._viewportCached.w = height;
  1642. this._gl.viewport(x, y, width, height);
  1643. }
  1644. }
  1645. /**
  1646. * Set the WebGL's viewport
  1647. * @param viewport defines the viewport element to be used
  1648. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  1649. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  1650. */
  1651. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  1652. var width = requiredWidth || this.getRenderWidth();
  1653. var height = requiredHeight || this.getRenderHeight();
  1654. var x = viewport.x || 0;
  1655. var y = viewport.y || 0;
  1656. this._cachedViewport = viewport;
  1657. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  1658. }
  1659. /**
  1660. * Directly set the WebGL Viewport
  1661. * @param x defines the x coordinate of the viewport (in screen space)
  1662. * @param y defines the y coordinate of the viewport (in screen space)
  1663. * @param width defines the width of the viewport (in screen space)
  1664. * @param height defines the height of the viewport (in screen space)
  1665. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state
  1666. */
  1667. public setDirectViewport(x: number, y: number, width: number, height: number): Nullable<Viewport> {
  1668. let currentViewport = this._cachedViewport;
  1669. this._cachedViewport = null;
  1670. this._viewport(x, y, width, height);
  1671. return currentViewport;
  1672. }
  1673. /**
  1674. * Begin a new frame
  1675. */
  1676. public beginFrame(): void {
  1677. this.onBeginFrameObservable.notifyObservers(this);
  1678. this._measureFps();
  1679. }
  1680. /**
  1681. * Enf the current frame
  1682. */
  1683. public endFrame(): void {
  1684. // Force a flush in case we are using a bad OS.
  1685. if (this._badOS) {
  1686. this.flushFramebuffer();
  1687. }
  1688. // Submit frame to the vr device, if enabled
  1689. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1690. // TODO: We should only submit the frame if we read frameData successfully.
  1691. this._vrDisplay.submitFrame();
  1692. }
  1693. this.onEndFrameObservable.notifyObservers(this);
  1694. }
  1695. /**
  1696. * Resize the view according to the canvas' size
  1697. */
  1698. public resize(): void {
  1699. // We're not resizing the size of the canvas while in VR mode & presenting
  1700. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  1701. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  1702. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  1703. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  1704. }
  1705. }
  1706. /**
  1707. * Force a specific size of the canvas
  1708. * @param width defines the new canvas' width
  1709. * @param height defines the new canvas' height
  1710. */
  1711. public setSize(width: number, height: number): void {
  1712. if (!this._renderingCanvas) {
  1713. return;
  1714. }
  1715. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  1716. return;
  1717. }
  1718. this._renderingCanvas.width = width;
  1719. this._renderingCanvas.height = height;
  1720. for (var index = 0; index < this.scenes.length; index++) {
  1721. var scene = this.scenes[index];
  1722. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  1723. var cam = scene.cameras[camIndex];
  1724. cam._currentRenderId = 0;
  1725. }
  1726. }
  1727. if (this.onResizeObservable.hasObservers) {
  1728. this.onResizeObservable.notifyObservers(this);
  1729. }
  1730. }
  1731. // WebVR functions
  1732. /**
  1733. * Gets a boolean indicating if a webVR device was detected
  1734. * @returns true if a webVR device was detected
  1735. */
  1736. public isVRDevicePresent(): boolean {
  1737. return !!this._vrDisplay;
  1738. }
  1739. /**
  1740. * Gets the current webVR device
  1741. * @returns the current webVR device (or null)
  1742. */
  1743. public getVRDevice(): any {
  1744. return this._vrDisplay;
  1745. }
  1746. /**
  1747. * Initializes a webVR display and starts listening to display change events
  1748. * The onVRDisplayChangedObservable will be notified upon these changes
  1749. * @returns The onVRDisplayChangedObservable
  1750. */
  1751. public initWebVR(): Observable<IDisplayChangedEventArgs> {
  1752. this.initWebVRAsync();
  1753. return this.onVRDisplayChangedObservable;
  1754. }
  1755. /**
  1756. * Initializes a webVR display and starts listening to display change events
  1757. * The onVRDisplayChangedObservable will be notified upon these changes
  1758. * @returns A promise containing a VRDisplay and if vr is supported
  1759. */
  1760. public initWebVRAsync(): Promise<IDisplayChangedEventArgs> {
  1761. var notifyObservers = () => {
  1762. var eventArgs = {
  1763. vrDisplay: this._vrDisplay,
  1764. vrSupported: this._vrSupported
  1765. };
  1766. this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  1767. this._webVRInitPromise = new Promise((res)=>{res(eventArgs)});
  1768. }
  1769. if (!this._onVrDisplayConnect) {
  1770. this._onVrDisplayConnect = (event) => {
  1771. this._vrDisplay = event.display;
  1772. notifyObservers();
  1773. };
  1774. this._onVrDisplayDisconnect = () => {
  1775. this._vrDisplay.cancelAnimationFrame(this._frameHandler);
  1776. this._vrDisplay = undefined;
  1777. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1778. notifyObservers();
  1779. };
  1780. this._onVrDisplayPresentChange = () => {
  1781. this._vrExclusivePointerMode = this._vrDisplay && this._vrDisplay.isPresenting;
  1782. }
  1783. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  1784. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  1785. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  1786. }
  1787. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  1788. this._webVRInitPromise.then(notifyObservers);
  1789. return this._webVRInitPromise;
  1790. }
  1791. /**
  1792. * Call this function to switch to webVR mode
  1793. * Will do nothing if webVR is not supported or if there is no webVR device
  1794. * @see http://doc.babylonjs.com/how_to/webvr_camera
  1795. */
  1796. public enableVR() {
  1797. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  1798. var onResolved = () => {
  1799. this.onVRRequestPresentComplete.notifyObservers(true);
  1800. this._onVRFullScreenTriggered();
  1801. };
  1802. var onRejected = () => {
  1803. this.onVRRequestPresentComplete.notifyObservers(false);
  1804. };
  1805. this.onVRRequestPresentStart.notifyObservers(this);
  1806. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  1807. }
  1808. }
  1809. /**
  1810. * Call this function to leave webVR mode
  1811. * Will do nothing if webVR is not supported or if there is no webVR device
  1812. * @see http://doc.babylonjs.com/how_to/webvr_camera
  1813. */
  1814. public disableVR() {
  1815. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1816. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  1817. }
  1818. }
  1819. private _onVRFullScreenTriggered = () => {
  1820. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1821. //get the old size before we change
  1822. this._oldSize = new Size(this.getRenderWidth(), this.getRenderHeight());
  1823. this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
  1824. //get the width and height, change the render size
  1825. var leftEye = this._vrDisplay.getEyeParameters('left');
  1826. this.setHardwareScalingLevel(1);
  1827. this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  1828. } else {
  1829. this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
  1830. this.setSize(this._oldSize.width, this._oldSize.height);
  1831. }
  1832. }
  1833. private _getVRDisplaysAsync():Promise<IDisplayChangedEventArgs> {
  1834. return new Promise((res, rej)=>{
  1835. if (navigator.getVRDisplays) {
  1836. navigator.getVRDisplays().then((devices: Array<any>)=>{
  1837. this._vrSupported = true;
  1838. // note that devices may actually be an empty array. This is fine;
  1839. // we expect this._vrDisplay to be undefined in this case.
  1840. this._vrDisplay = devices[0];
  1841. res({
  1842. vrDisplay: this._vrDisplay,
  1843. vrSupported: this._vrSupported
  1844. });
  1845. });
  1846. } else {
  1847. this._vrDisplay = undefined;
  1848. this._vrSupported = false;
  1849. res({
  1850. vrDisplay: this._vrDisplay,
  1851. vrSupported: this._vrSupported
  1852. });
  1853. }
  1854. });
  1855. }
  1856. /**
  1857. * Binds the frame buffer to the specified texture.
  1858. * @param texture The texture to render to or null for the default canvas
  1859. * @param faceIndex The face of the texture to render to in case of cube texture
  1860. * @param requiredWidth The width of the target to render to
  1861. * @param requiredHeight The height of the target to render to
  1862. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  1863. * @param depthStencilTexture The depth stencil texture to use to render
  1864. * @param lodLevel defines le lod level to bind to the frame buffer
  1865. */
  1866. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean, depthStencilTexture?: InternalTexture, lodLevel = 0): void {
  1867. if (this._currentRenderTarget) {
  1868. this.unBindFramebuffer(this._currentRenderTarget);
  1869. }
  1870. this._currentRenderTarget = texture;
  1871. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  1872. var gl = this._gl;
  1873. if (texture.isCube) {
  1874. if (faceIndex === undefined) {
  1875. faceIndex = 0;
  1876. }
  1877. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  1878. if (depthStencilTexture) {
  1879. if (depthStencilTexture._generateStencilBuffer) {
  1880. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  1881. }
  1882. else {
  1883. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  1884. }
  1885. }
  1886. }
  1887. if (this._cachedViewport && !forceFullscreenViewport) {
  1888. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  1889. } else {
  1890. if (!requiredWidth) {
  1891. requiredWidth = texture.width;
  1892. if (lodLevel) {
  1893. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  1894. }
  1895. }
  1896. if (!requiredHeight) {
  1897. requiredHeight = texture.height;
  1898. if (lodLevel) {
  1899. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  1900. }
  1901. }
  1902. this._viewport(0, 0, requiredWidth, requiredHeight);
  1903. }
  1904. this.wipeCaches();
  1905. }
  1906. private bindUnboundFramebuffer(framebuffer: Nullable<WebGLFramebuffer>) {
  1907. if (this._currentFramebuffer !== framebuffer) {
  1908. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  1909. this._currentFramebuffer = framebuffer;
  1910. }
  1911. }
  1912. /**
  1913. * Unbind the current render target texture from the webGL context
  1914. * @param texture defines the render target texture to unbind
  1915. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  1916. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  1917. */
  1918. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1919. this._currentRenderTarget = null;
  1920. // If MSAA, we need to bitblt back to main texture
  1921. var gl = this._gl;
  1922. if (texture._MSAAFramebuffer) {
  1923. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  1924. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  1925. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  1926. 0, 0, texture.width, texture.height,
  1927. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1928. }
  1929. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1930. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  1931. gl.generateMipmap(gl.TEXTURE_2D);
  1932. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1933. }
  1934. if (onBeforeUnbind) {
  1935. if (texture._MSAAFramebuffer) {
  1936. // Bind the correct framebuffer
  1937. this.bindUnboundFramebuffer(texture._framebuffer);
  1938. }
  1939. onBeforeUnbind();
  1940. }
  1941. this.bindUnboundFramebuffer(null);
  1942. }
  1943. /**
  1944. * Unbind a list of render target textures from the webGL context
  1945. * This is used only when drawBuffer extension or webGL2 are active
  1946. * @param textures defines the render target textures to unbind
  1947. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  1948. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  1949. */
  1950. public unBindMultiColorAttachmentFramebuffer(textures: InternalTexture[], disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1951. this._currentRenderTarget = null;
  1952. // If MSAA, we need to bitblt back to main texture
  1953. var gl = this._gl;
  1954. if (textures[0]._MSAAFramebuffer) {
  1955. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  1956. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  1957. var attachments = textures[0]._attachments;
  1958. if (!attachments) {
  1959. attachments = new Array(textures.length);
  1960. textures[0]._attachments = attachments;
  1961. }
  1962. for (var i = 0; i < textures.length; i++) {
  1963. var texture = textures[i];
  1964. for (var j = 0; j < attachments.length; j++) {
  1965. attachments[j] = gl.NONE;
  1966. }
  1967. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  1968. gl.readBuffer(attachments[i]);
  1969. gl.drawBuffers(attachments);
  1970. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  1971. 0, 0, texture.width, texture.height,
  1972. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1973. }
  1974. for (var i = 0; i < attachments.length; i++) {
  1975. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  1976. }
  1977. gl.drawBuffers(attachments);
  1978. }
  1979. for (var i = 0; i < textures.length; i++) {
  1980. var texture = textures[i];
  1981. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1982. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  1983. gl.generateMipmap(gl.TEXTURE_2D);
  1984. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1985. }
  1986. }
  1987. if (onBeforeUnbind) {
  1988. if (textures[0]._MSAAFramebuffer) {
  1989. // Bind the correct framebuffer
  1990. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  1991. }
  1992. onBeforeUnbind();
  1993. }
  1994. this.bindUnboundFramebuffer(null);
  1995. }
  1996. /**
  1997. * Force the mipmap generation for the given render target texture
  1998. * @param texture defines the render target texture to use
  1999. */
  2000. public generateMipMapsForCubemap(texture: InternalTexture) {
  2001. if (texture.generateMipMaps) {
  2002. var gl = this._gl;
  2003. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  2004. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2005. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2006. }
  2007. }
  2008. /**
  2009. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  2010. */
  2011. public flushFramebuffer(): void {
  2012. this._gl.flush();
  2013. }
  2014. /**
  2015. * Unbind the current render target and bind the default framebuffer
  2016. */
  2017. public restoreDefaultFramebuffer(): void {
  2018. if (this._currentRenderTarget) {
  2019. this.unBindFramebuffer(this._currentRenderTarget);
  2020. } else {
  2021. this.bindUnboundFramebuffer(null);
  2022. }
  2023. if (this._cachedViewport) {
  2024. this.setViewport(this._cachedViewport);
  2025. }
  2026. this.wipeCaches();
  2027. }
  2028. // UBOs
  2029. /**
  2030. * Create an uniform buffer
  2031. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  2032. * @param elements defines the content of the uniform buffer
  2033. * @returns the webGL uniform buffer
  2034. */
  2035. public createUniformBuffer(elements: FloatArray): WebGLBuffer {
  2036. var ubo = this._gl.createBuffer();
  2037. if (!ubo) {
  2038. throw new Error("Unable to create uniform buffer");
  2039. }
  2040. this.bindUniformBuffer(ubo);
  2041. if (elements instanceof Float32Array) {
  2042. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.STATIC_DRAW);
  2043. } else {
  2044. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.STATIC_DRAW);
  2045. }
  2046. this.bindUniformBuffer(null);
  2047. ubo.references = 1;
  2048. return ubo;
  2049. }
  2050. /**
  2051. * Create a dynamic uniform buffer
  2052. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  2053. * @param elements defines the content of the uniform buffer
  2054. * @returns the webGL uniform buffer
  2055. */
  2056. public createDynamicUniformBuffer(elements: FloatArray): WebGLBuffer {
  2057. var ubo = this._gl.createBuffer();
  2058. if (!ubo) {
  2059. throw new Error("Unable to create dynamic uniform buffer");
  2060. }
  2061. this.bindUniformBuffer(ubo);
  2062. if (elements instanceof Float32Array) {
  2063. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.DYNAMIC_DRAW);
  2064. } else {
  2065. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.DYNAMIC_DRAW);
  2066. }
  2067. this.bindUniformBuffer(null);
  2068. ubo.references = 1;
  2069. return ubo;
  2070. }
  2071. /**
  2072. * Update an existing uniform buffer
  2073. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  2074. * @param uniformBuffer defines the target uniform buffer
  2075. * @param elements defines the content to update
  2076. * @param offset defines the offset in the uniform buffer where update should start
  2077. * @param count defines the size of the data to update
  2078. */
  2079. public updateUniformBuffer(uniformBuffer: WebGLBuffer, elements: FloatArray, offset?: number, count?: number): void {
  2080. this.bindUniformBuffer(uniformBuffer);
  2081. if (offset === undefined) {
  2082. offset = 0;
  2083. }
  2084. if (count === undefined) {
  2085. if (elements instanceof Float32Array) {
  2086. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, <Float32Array>elements);
  2087. } else {
  2088. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(<number[]>elements));
  2089. }
  2090. } else {
  2091. if (elements instanceof Float32Array) {
  2092. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, <Float32Array>elements.subarray(offset, offset + count));
  2093. } else {
  2094. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(<number[]>elements).subarray(offset, offset + count));
  2095. }
  2096. }
  2097. this.bindUniformBuffer(null);
  2098. }
  2099. // VBOs
  2100. private _resetVertexBufferBinding(): void {
  2101. this.bindArrayBuffer(null);
  2102. this._cachedVertexBuffers = null;
  2103. }
  2104. /**
  2105. * Creates a vertex buffer
  2106. * @param data the data for the vertex buffer
  2107. * @returns the new WebGL static buffer
  2108. */
  2109. public createVertexBuffer(data: DataArray): WebGLBuffer {
  2110. var vbo = this._gl.createBuffer();
  2111. if (!vbo) {
  2112. throw new Error("Unable to create vertex buffer");
  2113. }
  2114. this.bindArrayBuffer(vbo);
  2115. if (data instanceof Array) {
  2116. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  2117. } else {
  2118. this._gl.bufferData(this._gl.ARRAY_BUFFER, <ArrayBuffer>data, this._gl.STATIC_DRAW);
  2119. }
  2120. this._resetVertexBufferBinding();
  2121. vbo.references = 1;
  2122. return vbo;
  2123. }
  2124. /**
  2125. * Creates a dynamic vertex buffer
  2126. * @param data the data for the dynamic vertex buffer
  2127. * @returns the new WebGL dynamic buffer
  2128. */
  2129. public createDynamicVertexBuffer(data: DataArray): WebGLBuffer {
  2130. var vbo = this._gl.createBuffer();
  2131. if (!vbo) {
  2132. throw new Error("Unable to create dynamic vertex buffer");
  2133. }
  2134. this.bindArrayBuffer(vbo);
  2135. if (data instanceof Array) {
  2136. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  2137. } else {
  2138. this._gl.bufferData(this._gl.ARRAY_BUFFER, <ArrayBuffer>data, this._gl.DYNAMIC_DRAW);
  2139. }
  2140. this._resetVertexBufferBinding();
  2141. vbo.references = 1;
  2142. return vbo;
  2143. }
  2144. /**
  2145. * Update a dynamic index buffer
  2146. * @param indexBuffer defines the target index buffer
  2147. * @param indices defines the data to update
  2148. * @param offset defines the offset in the target index buffer where update should start
  2149. */
  2150. public updateDynamicIndexBuffer(indexBuffer: WebGLBuffer, indices: IndicesArray, offset: number = 0): void {
  2151. // Force cache update
  2152. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  2153. this.bindIndexBuffer(indexBuffer);
  2154. var arrayBuffer;
  2155. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  2156. arrayBuffer = indices;
  2157. } else {
  2158. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  2159. }
  2160. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  2161. this._resetIndexBufferBinding();
  2162. }
  2163. /**
  2164. * Updates a dynamic vertex buffer.
  2165. * @param vertexBuffer the vertex buffer to update
  2166. * @param data the data used to update the vertex buffer
  2167. * @param byteOffset the byte offset of the data
  2168. * @param byteLength the byte length of the data
  2169. */
  2170. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void {
  2171. this.bindArrayBuffer(vertexBuffer);
  2172. if (byteOffset === undefined) {
  2173. byteOffset = 0;
  2174. }
  2175. if (byteLength === undefined) {
  2176. if (data instanceof Array) {
  2177. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  2178. } else {
  2179. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, <ArrayBuffer>data);
  2180. }
  2181. } else {
  2182. if (data instanceof Array) {
  2183. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  2184. } else {
  2185. if (data instanceof ArrayBuffer) {
  2186. data = new Uint8Array(data, byteOffset, byteLength);
  2187. } else {
  2188. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  2189. }
  2190. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <ArrayBuffer>data);
  2191. }
  2192. }
  2193. this._resetVertexBufferBinding();
  2194. }
  2195. private _resetIndexBufferBinding(): void {
  2196. this.bindIndexBuffer(null);
  2197. this._cachedIndexBuffer = null;
  2198. }
  2199. /**
  2200. * Creates a new index buffer
  2201. * @param indices defines the content of the index buffer
  2202. * @param updatable defines if the index buffer must be updatable
  2203. * @returns a new webGL buffer
  2204. */
  2205. public createIndexBuffer(indices: IndicesArray, updatable?: boolean): WebGLBuffer {
  2206. var vbo = this._gl.createBuffer();
  2207. if (!vbo) {
  2208. throw new Error("Unable to create index buffer");
  2209. }
  2210. this.bindIndexBuffer(vbo);
  2211. // Check for 32 bits indices
  2212. var arrayBuffer;
  2213. var need32Bits = false;
  2214. if (indices instanceof Uint16Array) {
  2215. arrayBuffer = indices;
  2216. } else {
  2217. //check 32 bit support
  2218. if (this._caps.uintIndices) {
  2219. if (indices instanceof Uint32Array) {
  2220. arrayBuffer = indices;
  2221. need32Bits = true;
  2222. } else {
  2223. //number[] or Int32Array, check if 32 bit is necessary
  2224. for (var index = 0; index < indices.length; index++) {
  2225. if (indices[index] > 65535) {
  2226. need32Bits = true;
  2227. break;
  2228. }
  2229. }
  2230. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  2231. }
  2232. } else {
  2233. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  2234. arrayBuffer = new Uint16Array(indices);
  2235. }
  2236. }
  2237. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  2238. this._resetIndexBufferBinding();
  2239. vbo.references = 1;
  2240. vbo.is32Bits = need32Bits;
  2241. return vbo;
  2242. }
  2243. /**
  2244. * Bind a webGL buffer to the webGL context
  2245. * @param buffer defines the buffer to bind
  2246. */
  2247. public bindArrayBuffer(buffer: Nullable<WebGLBuffer>): void {
  2248. if (!this._vaoRecordInProgress) {
  2249. this._unbindVertexArrayObject();
  2250. }
  2251. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  2252. }
  2253. /**
  2254. * Bind an uniform buffer to the current webGL context
  2255. * @param buffer defines the buffer to bind
  2256. */
  2257. public bindUniformBuffer(buffer: Nullable<WebGLBuffer>): void {
  2258. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  2259. }
  2260. /**
  2261. * Bind a buffer to the current webGL context at a given location
  2262. * @param buffer defines the buffer to bind
  2263. * @param location defines the index where to bind the buffer
  2264. */
  2265. public bindUniformBufferBase(buffer: WebGLBuffer, location: number): void {
  2266. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  2267. }
  2268. /**
  2269. * Bind a specific block at a given index in a specific shader program
  2270. * @param shaderProgram defines the shader program
  2271. * @param blockName defines the block name
  2272. * @param index defines the index where to bind the block
  2273. */
  2274. public bindUniformBlock(shaderProgram: WebGLProgram, blockName: string, index: number): void {
  2275. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  2276. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  2277. };
  2278. private bindIndexBuffer(buffer: Nullable<WebGLBuffer>): void {
  2279. if (!this._vaoRecordInProgress) {
  2280. this._unbindVertexArrayObject();
  2281. }
  2282. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  2283. }
  2284. private bindBuffer(buffer: Nullable<WebGLBuffer>, target: number): void {
  2285. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  2286. this._gl.bindBuffer(target, buffer);
  2287. this._currentBoundBuffer[target] = buffer;
  2288. }
  2289. }
  2290. /**
  2291. * update the bound buffer with the given data
  2292. * @param data defines the data to update
  2293. */
  2294. public updateArrayBuffer(data: Float32Array): void {
  2295. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2296. }
  2297. private _vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  2298. var pointer = this._currentBufferPointers[indx];
  2299. var changed = false;
  2300. if (!pointer.active) {
  2301. changed = true;
  2302. pointer.active = true;
  2303. pointer.index = indx;
  2304. pointer.size = size;
  2305. pointer.type = type;
  2306. pointer.normalized = normalized;
  2307. pointer.stride = stride;
  2308. pointer.offset = offset;
  2309. pointer.buffer = buffer;
  2310. } else {
  2311. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  2312. if (pointer.size !== size) { pointer.size = size; changed = true; }
  2313. if (pointer.type !== type) { pointer.type = type; changed = true; }
  2314. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  2315. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  2316. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  2317. }
  2318. if (changed || this._vaoRecordInProgress) {
  2319. this.bindArrayBuffer(buffer);
  2320. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  2321. }
  2322. }
  2323. private _bindIndexBufferWithCache(indexBuffer: Nullable<WebGLBuffer>): void {
  2324. if (indexBuffer == null) {
  2325. return;
  2326. }
  2327. if (this._cachedIndexBuffer !== indexBuffer) {
  2328. this._cachedIndexBuffer = indexBuffer;
  2329. this.bindIndexBuffer(indexBuffer);
  2330. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  2331. }
  2332. }
  2333. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, effect: Effect): void {
  2334. var attributes = effect.getAttributesNames();
  2335. if (!this._vaoRecordInProgress) {
  2336. this._unbindVertexArrayObject();
  2337. }
  2338. this.unbindAllAttributes();
  2339. for (var index = 0; index < attributes.length; index++) {
  2340. var order = effect.getAttributeLocation(index);
  2341. if (order >= 0) {
  2342. var vertexBuffer = vertexBuffers[attributes[index]];
  2343. if (!vertexBuffer) {
  2344. continue;
  2345. }
  2346. this._gl.enableVertexAttribArray(order);
  2347. if (!this._vaoRecordInProgress) {
  2348. this._vertexAttribArraysEnabled[order] = true;
  2349. }
  2350. var buffer = vertexBuffer.getBuffer();
  2351. if (buffer) {
  2352. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  2353. if (vertexBuffer.getIsInstanced()) {
  2354. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  2355. if (!this._vaoRecordInProgress) {
  2356. this._currentInstanceLocations.push(order);
  2357. this._currentInstanceBuffers.push(buffer);
  2358. }
  2359. }
  2360. }
  2361. }
  2362. }
  2363. }
  2364. /**
  2365. * Records a vertex array object
  2366. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  2367. * @param vertexBuffers defines the list of vertex buffers to store
  2368. * @param indexBuffer defines the index buffer to store
  2369. * @param effect defines the effect to store
  2370. * @returns the new vertex array object
  2371. */
  2372. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): WebGLVertexArrayObject {
  2373. var vao = this._gl.createVertexArray();
  2374. this._vaoRecordInProgress = true;
  2375. this._gl.bindVertexArray(vao);
  2376. this._mustWipeVertexAttributes = true;
  2377. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  2378. this.bindIndexBuffer(indexBuffer);
  2379. this._vaoRecordInProgress = false;
  2380. this._gl.bindVertexArray(null);
  2381. return vao;
  2382. }
  2383. /**
  2384. * Bind a specific vertex array object
  2385. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  2386. * @param vertexArrayObject defines the vertex array object to bind
  2387. * @param indexBuffer defines the index buffer to bind
  2388. */
  2389. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: Nullable<WebGLBuffer>): void {
  2390. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  2391. this._cachedVertexArrayObject = vertexArrayObject;
  2392. this._gl.bindVertexArray(vertexArrayObject);
  2393. this._cachedVertexBuffers = null;
  2394. this._cachedIndexBuffer = null;
  2395. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  2396. this._mustWipeVertexAttributes = true;
  2397. }
  2398. }
  2399. /**
  2400. * Bind webGl buffers directly to the webGL context
  2401. * @param vertexBuffer defines the vertex buffer to bind
  2402. * @param indexBuffer defines the index buffer to bind
  2403. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  2404. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  2405. * @param effect defines the effect associated with the vertex buffer
  2406. */
  2407. public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  2408. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2409. this._cachedVertexBuffers = vertexBuffer;
  2410. this._cachedEffectForVertexBuffers = effect;
  2411. let attributesCount = effect.getAttributesCount();
  2412. this._unbindVertexArrayObject();
  2413. this.unbindAllAttributes();
  2414. var offset = 0;
  2415. for (var index = 0; index < attributesCount; index++) {
  2416. if (index < vertexDeclaration.length) {
  2417. var order = effect.getAttributeLocation(index);
  2418. if (order >= 0) {
  2419. this._gl.enableVertexAttribArray(order);
  2420. this._vertexAttribArraysEnabled[order] = true;
  2421. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2422. }
  2423. offset += vertexDeclaration[index] * 4;
  2424. }
  2425. }
  2426. }
  2427. this._bindIndexBufferWithCache(indexBuffer);
  2428. }
  2429. private _unbindVertexArrayObject(): void {
  2430. if (!this._cachedVertexArrayObject) {
  2431. return;
  2432. }
  2433. this._cachedVertexArrayObject = null;
  2434. this._gl.bindVertexArray(null);
  2435. }
  2436. /**
  2437. * Bind a list of vertex buffers to the webGL context
  2438. * @param vertexBuffers defines the list of vertex buffers to bind
  2439. * @param indexBuffer defines the index buffer to bind
  2440. * @param effect defines the effect associated with the vertex buffers
  2441. */
  2442. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): void {
  2443. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2444. this._cachedVertexBuffers = vertexBuffers;
  2445. this._cachedEffectForVertexBuffers = effect;
  2446. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  2447. }
  2448. this._bindIndexBufferWithCache(indexBuffer);
  2449. }
  2450. /**
  2451. * Unbind all instance attributes
  2452. */
  2453. public unbindInstanceAttributes() {
  2454. var boundBuffer;
  2455. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  2456. var instancesBuffer = this._currentInstanceBuffers[i];
  2457. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  2458. boundBuffer = instancesBuffer;
  2459. this.bindArrayBuffer(instancesBuffer);
  2460. }
  2461. var offsetLocation = this._currentInstanceLocations[i];
  2462. this._gl.vertexAttribDivisor(offsetLocation, 0);
  2463. }
  2464. this._currentInstanceBuffers.length = 0;
  2465. this._currentInstanceLocations.length = 0;
  2466. }
  2467. /**
  2468. * Release and free the memory of a vertex array object
  2469. * @param vao defines the vertex array object to delete
  2470. */
  2471. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  2472. this._gl.deleteVertexArray(vao);
  2473. }
  2474. /** @hidden */
  2475. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  2476. buffer.references--;
  2477. if (buffer.references === 0) {
  2478. this._gl.deleteBuffer(buffer);
  2479. return true;
  2480. }
  2481. return false;
  2482. }
  2483. /**
  2484. * Creates a webGL buffer to use with instanciation
  2485. * @param capacity defines the size of the buffer
  2486. * @returns the webGL buffer
  2487. */
  2488. public createInstancesBuffer(capacity: number): WebGLBuffer {
  2489. var buffer = this._gl.createBuffer();
  2490. if (!buffer) {
  2491. throw new Error("Unable to create instance buffer");
  2492. }
  2493. buffer.capacity = capacity;
  2494. this.bindArrayBuffer(buffer);
  2495. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2496. return buffer;
  2497. }
  2498. /**
  2499. * Delete a webGL buffer used with instanciation
  2500. * @param buffer defines the webGL buffer to delete
  2501. */
  2502. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  2503. this._gl.deleteBuffer(buffer);
  2504. }
  2505. /**
  2506. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  2507. * @param instancesBuffer defines the webGL buffer to update and bind
  2508. * @param data defines the data to store in the buffer
  2509. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  2510. */
  2511. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  2512. this.bindArrayBuffer(instancesBuffer);
  2513. if (data) {
  2514. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2515. }
  2516. if ((<any>offsetLocations[0]).index !== undefined) {
  2517. let stride = 0;
  2518. for (let i = 0; i < offsetLocations.length; i++) {
  2519. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2520. stride += ai.attributeSize * 4;
  2521. }
  2522. for (let i = 0; i < offsetLocations.length; i++) {
  2523. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2524. if (!this._vertexAttribArraysEnabled[ai.index]) {
  2525. this._gl.enableVertexAttribArray(ai.index);
  2526. this._vertexAttribArraysEnabled[ai.index] = true;
  2527. }
  2528. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  2529. this._gl.vertexAttribDivisor(ai.index, 1);
  2530. this._currentInstanceLocations.push(ai.index);
  2531. this._currentInstanceBuffers.push(instancesBuffer);
  2532. }
  2533. } else {
  2534. for (let index = 0; index < 4; index++) {
  2535. let offsetLocation = <number>offsetLocations[index];
  2536. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  2537. this._gl.enableVertexAttribArray(offsetLocation);
  2538. this._vertexAttribArraysEnabled[offsetLocation] = true;
  2539. }
  2540. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2541. this._gl.vertexAttribDivisor(offsetLocation, 1);
  2542. this._currentInstanceLocations.push(offsetLocation);
  2543. this._currentInstanceBuffers.push(instancesBuffer);
  2544. }
  2545. }
  2546. }
  2547. /**
  2548. * Apply all cached states (depth, culling, stencil and alpha)
  2549. */
  2550. public applyStates() {
  2551. this._depthCullingState.apply(this._gl);
  2552. this._stencilState.apply(this._gl);
  2553. this._alphaState.apply(this._gl);
  2554. }
  2555. /**
  2556. * Send a draw order
  2557. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  2558. * @param indexStart defines the starting index
  2559. * @param indexCount defines the number of index to draw
  2560. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2561. */
  2562. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  2563. this.drawElementsType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  2564. }
  2565. /**
  2566. * Draw a list of points
  2567. * @param verticesStart defines the index of first vertex to draw
  2568. * @param verticesCount defines the count of vertices to draw
  2569. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2570. */
  2571. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2572. this.drawArraysType(Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  2573. }
  2574. /**
  2575. * Draw a list of unindexed primitives
  2576. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  2577. * @param verticesStart defines the index of first vertex to draw
  2578. * @param verticesCount defines the count of vertices to draw
  2579. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2580. */
  2581. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2582. this.drawArraysType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  2583. }
  2584. /**
  2585. * Draw a list of indexed primitives
  2586. * @param fillMode defines the primitive to use
  2587. * @param indexStart defines the starting index
  2588. * @param indexCount defines the number of index to draw
  2589. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2590. */
  2591. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount?: number): void {
  2592. // Apply states
  2593. this.applyStates();
  2594. this._drawCalls.addCount(1, false);
  2595. // Render
  2596. const drawMode = this._drawMode(fillMode);
  2597. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  2598. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  2599. if (instancesCount) {
  2600. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  2601. } else {
  2602. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  2603. }
  2604. }
  2605. /**
  2606. * Draw a list of unindexed primitives
  2607. * @param fillMode defines the primitive to use
  2608. * @param verticesStart defines the index of first vertex to draw
  2609. * @param verticesCount defines the count of vertices to draw
  2610. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2611. */
  2612. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2613. // Apply states
  2614. this.applyStates();
  2615. this._drawCalls.addCount(1, false);
  2616. const drawMode = this._drawMode(fillMode);
  2617. if (instancesCount) {
  2618. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  2619. } else {
  2620. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  2621. }
  2622. }
  2623. private _drawMode(fillMode: number): number {
  2624. switch (fillMode) {
  2625. // Triangle views
  2626. case Material.TriangleFillMode:
  2627. return this._gl.TRIANGLES;
  2628. case Material.PointFillMode:
  2629. return this._gl.POINTS;
  2630. case Material.WireFrameFillMode:
  2631. return this._gl.LINES;
  2632. // Draw modes
  2633. case Material.PointListDrawMode:
  2634. return this._gl.POINTS
  2635. case Material.LineListDrawMode:
  2636. return this._gl.LINES;
  2637. case Material.LineLoopDrawMode:
  2638. return this._gl.LINE_LOOP
  2639. case Material.LineStripDrawMode:
  2640. return this._gl.LINE_STRIP
  2641. case Material.TriangleStripDrawMode:
  2642. return this._gl.TRIANGLE_STRIP
  2643. case Material.TriangleFanDrawMode:
  2644. return this._gl.TRIANGLE_FAN;
  2645. default:
  2646. return this._gl.TRIANGLES;
  2647. }
  2648. }
  2649. // Shaders
  2650. /** @hidden */
  2651. public _releaseEffect(effect: Effect): void {
  2652. if (this._compiledEffects[effect._key]) {
  2653. delete this._compiledEffects[effect._key];
  2654. this._deleteProgram(effect.getProgram());
  2655. }
  2656. }
  2657. /** @hidden */
  2658. public _deleteProgram(program: WebGLProgram): void {
  2659. if (program) {
  2660. program.__SPECTOR_rebuildProgram = null;
  2661. if (program.transformFeedback) {
  2662. this.deleteTransformFeedback(program.transformFeedback);
  2663. program.transformFeedback = null;
  2664. }
  2665. this._gl.deleteProgram(program);
  2666. }
  2667. }
  2668. /**
  2669. * Create a new effect (used to store vertex/fragment shaders)
  2670. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  2671. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  2672. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  2673. * @param samplers defines an array of string used to represent textures
  2674. * @param defines defines the string containing the defines to use to compile the shaders
  2675. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  2676. * @param onCompiled defines a function to call when the effect creation is successful
  2677. * @param onError defines a function to call when the effect creation has failed
  2678. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  2679. * @returns the new Effect
  2680. */
  2681. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  2682. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  2683. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2684. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2685. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  2686. if (this._compiledEffects[name]) {
  2687. var compiledEffect = <Effect>this._compiledEffects[name];
  2688. if (onCompiled && compiledEffect.isReady()) {
  2689. onCompiled(compiledEffect);
  2690. }
  2691. return compiledEffect;
  2692. }
  2693. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  2694. effect._key = name;
  2695. this._compiledEffects[name] = effect;
  2696. return effect;
  2697. }
  2698. private _compileShader(source: string, type: string, defines: Nullable<string>, shaderVersion: string): WebGLShader {
  2699. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  2700. };
  2701. private _compileRawShader(source: string, type: string): WebGLShader {
  2702. var gl = this._gl;
  2703. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2704. gl.shaderSource(shader, source);
  2705. gl.compileShader(shader);
  2706. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2707. let log = gl.getShaderInfoLog(shader);
  2708. if (log) {
  2709. throw new Error(log);
  2710. }
  2711. }
  2712. if (!shader) {
  2713. throw new Error("Something went wrong while compile the shader.");
  2714. }
  2715. return shader;
  2716. };
  2717. /**
  2718. * Directly creates a webGL program
  2719. * @param vertexCode defines the vertex shader code to use
  2720. * @param fragmentCode defines the fragment shader code to use
  2721. * @param context defines the webGL context to use (if not set, the current one will be used)
  2722. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  2723. * @returns the new webGL program
  2724. */
  2725. public createRawShaderProgram(vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2726. context = context || this._gl;
  2727. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  2728. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  2729. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2730. }
  2731. /**
  2732. * Creates a webGL program
  2733. * @param vertexCode defines the vertex shader code to use
  2734. * @param fragmentCode defines the fragment shader code to use
  2735. * @param defines defines the string containing the defines to use to compile the shaders
  2736. * @param context defines the webGL context to use (if not set, the current one will be used)
  2737. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  2738. * @returns the new webGL program
  2739. */
  2740. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2741. context = context || this._gl;
  2742. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  2743. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  2744. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  2745. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  2746. let program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2747. this.onAfterShaderCompilationObservable.notifyObservers(this);
  2748. return program;
  2749. }
  2750. private _createShaderProgram(vertexShader: WebGLShader, fragmentShader: WebGLShader, context: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2751. var shaderProgram = context.createProgram();
  2752. if (!shaderProgram) {
  2753. throw new Error("Unable to create program");
  2754. }
  2755. context.attachShader(shaderProgram, vertexShader);
  2756. context.attachShader(shaderProgram, fragmentShader);
  2757. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2758. let transformFeedback = this.createTransformFeedback();
  2759. this.bindTransformFeedback(transformFeedback);
  2760. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  2761. shaderProgram.transformFeedback = transformFeedback;
  2762. }
  2763. context.linkProgram(shaderProgram);
  2764. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2765. this.bindTransformFeedback(null);
  2766. }
  2767. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  2768. if (!linked) {
  2769. var error = context.getProgramInfoLog(shaderProgram);
  2770. if (error) {
  2771. throw new Error(error);
  2772. }
  2773. }
  2774. if (this.validateShaderPrograms) {
  2775. context.validateProgram(shaderProgram);
  2776. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  2777. if(!validated) {
  2778. var error = context.getProgramInfoLog(shaderProgram);
  2779. if (error) {
  2780. throw new Error(error);
  2781. }
  2782. }
  2783. }
  2784. context.deleteShader(vertexShader);
  2785. context.deleteShader(fragmentShader);
  2786. return shaderProgram;
  2787. }
  2788. /**
  2789. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  2790. * @param shaderProgram defines the webGL program to use
  2791. * @param uniformsNames defines the list of uniform names
  2792. * @returns an array of webGL uniform locations
  2793. */
  2794. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  2795. var results = new Array<Nullable<WebGLUniformLocation>>();
  2796. for (var index = 0; index < uniformsNames.length; index++) {
  2797. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  2798. }
  2799. return results;
  2800. }
  2801. /**
  2802. * Gets the lsit of active attributes for a given webGL program
  2803. * @param shaderProgram defines the webGL program to use
  2804. * @param attributesNames defines the list of attribute names to get
  2805. * @returns an array of indices indicating the offset of each attribute
  2806. */
  2807. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  2808. var results = [];
  2809. for (var index = 0; index < attributesNames.length; index++) {
  2810. try {
  2811. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  2812. } catch (e) {
  2813. results.push(-1);
  2814. }
  2815. }
  2816. return results;
  2817. }
  2818. /**
  2819. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  2820. * @param effect defines the effect to activate
  2821. */
  2822. public enableEffect(effect: Nullable<Effect>): void {
  2823. if (!effect) {
  2824. return;
  2825. }
  2826. // Use program
  2827. this.bindSamplers(effect);
  2828. this._currentEffect = effect;
  2829. if (effect.onBind) {
  2830. effect.onBind(effect);
  2831. }
  2832. effect.onBindObservable.notifyObservers(effect);
  2833. }
  2834. /**
  2835. * Set the value of an uniform to an array of int32
  2836. * @param uniform defines the webGL uniform location where to store the value
  2837. * @param array defines the array of int32 to store
  2838. */
  2839. public setIntArray(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2840. if (!uniform)
  2841. return;
  2842. this._gl.uniform1iv(uniform, array);
  2843. }
  2844. /**
  2845. * Set the value of an uniform to an array of int32 (stored as vec2)
  2846. * @param uniform defines the webGL uniform location where to store the value
  2847. * @param array defines the array of int32 to store
  2848. */
  2849. public setIntArray2(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2850. if (!uniform || array.length % 2 !== 0)
  2851. return;
  2852. this._gl.uniform2iv(uniform, array);
  2853. }
  2854. /**
  2855. * Set the value of an uniform to an array of int32 (stored as vec3)
  2856. * @param uniform defines the webGL uniform location where to store the value
  2857. * @param array defines the array of int32 to store
  2858. */
  2859. public setIntArray3(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2860. if (!uniform || array.length % 3 !== 0)
  2861. return;
  2862. this._gl.uniform3iv(uniform, array);
  2863. }
  2864. /**
  2865. * Set the value of an uniform to an array of int32 (stored as vec4)
  2866. * @param uniform defines the webGL uniform location where to store the value
  2867. * @param array defines the array of int32 to store
  2868. */
  2869. public setIntArray4(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2870. if (!uniform || array.length % 4 !== 0)
  2871. return;
  2872. this._gl.uniform4iv(uniform, array);
  2873. }
  2874. /**
  2875. * Set the value of an uniform to an array of float32
  2876. * @param uniform defines the webGL uniform location where to store the value
  2877. * @param array defines the array of float32 to store
  2878. */
  2879. public setFloatArray(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2880. if (!uniform)
  2881. return;
  2882. this._gl.uniform1fv(uniform, array);
  2883. }
  2884. /**
  2885. * Set the value of an uniform to an array of float32 (stored as vec2)
  2886. * @param uniform defines the webGL uniform location where to store the value
  2887. * @param array defines the array of float32 to store
  2888. */
  2889. public setFloatArray2(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2890. if (!uniform || array.length % 2 !== 0)
  2891. return;
  2892. this._gl.uniform2fv(uniform, array);
  2893. }
  2894. /**
  2895. * Set the value of an uniform to an array of float32 (stored as vec3)
  2896. * @param uniform defines the webGL uniform location where to store the value
  2897. * @param array defines the array of float32 to store
  2898. */
  2899. public setFloatArray3(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2900. if (!uniform || array.length % 3 !== 0)
  2901. return;
  2902. this._gl.uniform3fv(uniform, array);
  2903. }
  2904. /**
  2905. * Set the value of an uniform to an array of float32 (stored as vec4)
  2906. * @param uniform defines the webGL uniform location where to store the value
  2907. * @param array defines the array of float32 to store
  2908. */
  2909. public setFloatArray4(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2910. if (!uniform || array.length % 4 !== 0)
  2911. return;
  2912. this._gl.uniform4fv(uniform, array);
  2913. }
  2914. /**
  2915. * Set the value of an uniform to an array of number
  2916. * @param uniform defines the webGL uniform location where to store the value
  2917. * @param array defines the array of number to store
  2918. */
  2919. public setArray(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2920. if (!uniform)
  2921. return;
  2922. this._gl.uniform1fv(uniform, <any>array);
  2923. }
  2924. /**
  2925. * Set the value of an uniform to an array of number (stored as vec2)
  2926. * @param uniform defines the webGL uniform location where to store the value
  2927. * @param array defines the array of number to store
  2928. */
  2929. public setArray2(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2930. if (!uniform || array.length % 2 !== 0)
  2931. return;
  2932. this._gl.uniform2fv(uniform, <any>array);
  2933. }
  2934. /**
  2935. * Set the value of an uniform to an array of number (stored as vec3)
  2936. * @param uniform defines the webGL uniform location where to store the value
  2937. * @param array defines the array of number to store
  2938. */
  2939. public setArray3(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2940. if (!uniform || array.length % 3 !== 0)
  2941. return;
  2942. this._gl.uniform3fv(uniform, <any>array);
  2943. }
  2944. /**
  2945. * Set the value of an uniform to an array of number (stored as vec4)
  2946. * @param uniform defines the webGL uniform location where to store the value
  2947. * @param array defines the array of number to store
  2948. */
  2949. public setArray4(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2950. if (!uniform || array.length % 4 !== 0)
  2951. return;
  2952. this._gl.uniform4fv(uniform, <any>array);
  2953. }
  2954. /**
  2955. * Set the value of an uniform to an array of float32 (stored as matrices)
  2956. * @param uniform defines the webGL uniform location where to store the value
  2957. * @param matrices defines the array of float32 to store
  2958. */
  2959. public setMatrices(uniform: Nullable<WebGLUniformLocation>, matrices: Float32Array): void {
  2960. if (!uniform)
  2961. return;
  2962. this._gl.uniformMatrix4fv(uniform, false, matrices);
  2963. }
  2964. /**
  2965. * Set the value of an uniform to a matrix
  2966. * @param uniform defines the webGL uniform location where to store the value
  2967. * @param matrix defines the matrix to store
  2968. */
  2969. public setMatrix(uniform: Nullable<WebGLUniformLocation>, matrix: Matrix): void {
  2970. if (!uniform)
  2971. return;
  2972. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  2973. }
  2974. /**
  2975. * Set the value of an uniform to a matrix (3x3)
  2976. * @param uniform defines the webGL uniform location where to store the value
  2977. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  2978. */
  2979. public setMatrix3x3(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  2980. if (!uniform)
  2981. return;
  2982. this._gl.uniformMatrix3fv(uniform, false, matrix);
  2983. }
  2984. /**
  2985. * Set the value of an uniform to a matrix (2x2)
  2986. * @param uniform defines the webGL uniform location where to store the value
  2987. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  2988. */
  2989. public setMatrix2x2(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  2990. if (!uniform)
  2991. return;
  2992. this._gl.uniformMatrix2fv(uniform, false, matrix);
  2993. }
  2994. /**
  2995. * Set the value of an uniform to a number (int)
  2996. * @param uniform defines the webGL uniform location where to store the value
  2997. * @param value defines the int number to store
  2998. */
  2999. public setInt(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  3000. if (!uniform)
  3001. return;
  3002. this._gl.uniform1i(uniform, value);
  3003. }
  3004. /**
  3005. * Set the value of an uniform to a number (float)
  3006. * @param uniform defines the webGL uniform location where to store the value
  3007. * @param value defines the float number to store
  3008. */
  3009. public setFloat(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  3010. if (!uniform)
  3011. return;
  3012. this._gl.uniform1f(uniform, value);
  3013. }
  3014. /**
  3015. * Set the value of an uniform to a vec2
  3016. * @param uniform defines the webGL uniform location where to store the value
  3017. * @param x defines the 1st component of the value
  3018. * @param y defines the 2nd component of the value
  3019. */
  3020. public setFloat2(uniform: Nullable<WebGLUniformLocation>, x: number, y: number): void {
  3021. if (!uniform)
  3022. return;
  3023. this._gl.uniform2f(uniform, x, y);
  3024. }
  3025. /**
  3026. * Set the value of an uniform to a vec3
  3027. * @param uniform defines the webGL uniform location where to store the value
  3028. * @param x defines the 1st component of the value
  3029. * @param y defines the 2nd component of the value
  3030. * @param z defines the 3rd component of the value
  3031. */
  3032. public setFloat3(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number): void {
  3033. if (!uniform)
  3034. return;
  3035. this._gl.uniform3f(uniform, x, y, z);
  3036. }
  3037. /**
  3038. * Set the value of an uniform to a boolean
  3039. * @param uniform defines the webGL uniform location where to store the value
  3040. * @param bool defines the boolean to store
  3041. */
  3042. public setBool(uniform: Nullable<WebGLUniformLocation>, bool: number): void {
  3043. if (!uniform)
  3044. return;
  3045. this._gl.uniform1i(uniform, bool);
  3046. }
  3047. /**
  3048. * Set the value of an uniform to a vec4
  3049. * @param uniform defines the webGL uniform location where to store the value
  3050. * @param x defines the 1st component of the value
  3051. * @param y defines the 2nd component of the value
  3052. * @param z defines the 3rd component of the value
  3053. * @param w defines the 4th component of the value
  3054. */
  3055. public setFloat4(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number, w: number): void {
  3056. if (!uniform)
  3057. return;
  3058. this._gl.uniform4f(uniform, x, y, z, w);
  3059. }
  3060. /**
  3061. * Set the value of an uniform to a Color3
  3062. * @param uniform defines the webGL uniform location where to store the value
  3063. * @param color3 defines the color to store
  3064. */
  3065. public setColor3(uniform: Nullable<WebGLUniformLocation>, color3: Color3): void {
  3066. if (!uniform)
  3067. return;
  3068. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3069. }
  3070. /**
  3071. * Set the value of an uniform to a Color3 and an alpha value
  3072. * @param uniform defines the webGL uniform location where to store the value
  3073. * @param color3 defines the color to store
  3074. * @param alpha defines the alpha component to store
  3075. */
  3076. public setColor4(uniform: Nullable<WebGLUniformLocation>, color3: Color3, alpha: number): void {
  3077. if (!uniform)
  3078. return;
  3079. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3080. }
  3081. /**
  3082. * Sets a Color4 on a uniform variable
  3083. * @param uniform defines the uniform location
  3084. * @param color4 defines the value to be set
  3085. */
  3086. public setDirectColor4(uniform: Nullable<WebGLUniformLocation>, color4: Color4): void {
  3087. if (!uniform)
  3088. return;
  3089. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  3090. }
  3091. // States
  3092. /**
  3093. * Set various states to the webGL context
  3094. * @param culling defines backface culling state
  3095. * @param zOffset defines the value to apply to zOffset (0 by default)
  3096. * @param force defines if states must be applied even if cache is up to date
  3097. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  3098. */
  3099. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  3100. // Culling
  3101. if (this._depthCullingState.cull !== culling || force) {
  3102. this._depthCullingState.cull = culling;
  3103. }
  3104. // Cull face
  3105. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3106. if (this._depthCullingState.cullFace !== cullFace || force) {
  3107. this._depthCullingState.cullFace = cullFace;
  3108. }
  3109. // Z offset
  3110. this.setZOffset(zOffset);
  3111. // Front face
  3112. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  3113. if (this._depthCullingState.frontFace !== frontFace || force) {
  3114. this._depthCullingState.frontFace = frontFace;
  3115. }
  3116. }
  3117. /**
  3118. * Set the z offset to apply to current rendering
  3119. * @param value defines the offset to apply
  3120. */
  3121. public setZOffset(value: number): void {
  3122. this._depthCullingState.zOffset = value;
  3123. }
  3124. /**
  3125. * Gets the current value of the zOffset
  3126. * @returns the current zOffset state
  3127. */
  3128. public getZOffset(): number {
  3129. return this._depthCullingState.zOffset;
  3130. }
  3131. /**
  3132. * Enable or disable depth buffering
  3133. * @param enable defines the state to set
  3134. */
  3135. public setDepthBuffer(enable: boolean): void {
  3136. this._depthCullingState.depthTest = enable;
  3137. }
  3138. /**
  3139. * Gets a boolean indicating if depth writing is enabled
  3140. * @returns the current depth writing state
  3141. */
  3142. public getDepthWrite(): boolean {
  3143. return this._depthCullingState.depthMask;
  3144. }
  3145. /**
  3146. * Enable or disable depth writing
  3147. * @param enable defines the state to set
  3148. */
  3149. public setDepthWrite(enable: boolean): void {
  3150. this._depthCullingState.depthMask = enable;
  3151. }
  3152. /**
  3153. * Enable or disable color writing
  3154. * @param enable defines the state to set
  3155. */
  3156. public setColorWrite(enable: boolean): void {
  3157. this._gl.colorMask(enable, enable, enable, enable);
  3158. this._colorWrite = enable;
  3159. }
  3160. /**
  3161. * Gets a boolean indicating if color writing is enabled
  3162. * @returns the current color writing state
  3163. */
  3164. public getColorWrite(): boolean {
  3165. return this._colorWrite;
  3166. }
  3167. /**
  3168. * Sets alpha constants used by some alpha blending modes
  3169. * @param r defines the red component
  3170. * @param g defines the green component
  3171. * @param b defines the blue component
  3172. * @param a defines the alpha component
  3173. */
  3174. public setAlphaConstants(r: number, g: number, b: number, a: number) {
  3175. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  3176. }
  3177. /**
  3178. * Sets the current alpha mode
  3179. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  3180. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  3181. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  3182. */
  3183. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  3184. if (this._alphaMode === mode) {
  3185. return;
  3186. }
  3187. switch (mode) {
  3188. case Engine.ALPHA_DISABLE:
  3189. this._alphaState.alphaBlend = false;
  3190. break;
  3191. case Engine.ALPHA_PREMULTIPLIED:
  3192. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3193. this._alphaState.alphaBlend = true;
  3194. break;
  3195. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  3196. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  3197. this._alphaState.alphaBlend = true;
  3198. break;
  3199. case Engine.ALPHA_COMBINE:
  3200. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3201. this._alphaState.alphaBlend = true;
  3202. break;
  3203. case Engine.ALPHA_ONEONE:
  3204. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3205. this._alphaState.alphaBlend = true;
  3206. break;
  3207. case Engine.ALPHA_ADD:
  3208. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3209. this._alphaState.alphaBlend = true;
  3210. break;
  3211. case Engine.ALPHA_SUBTRACT:
  3212. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  3213. this._alphaState.alphaBlend = true;
  3214. break;
  3215. case Engine.ALPHA_MULTIPLY:
  3216. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  3217. this._alphaState.alphaBlend = true;
  3218. break;
  3219. case Engine.ALPHA_MAXIMIZED:
  3220. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  3221. this._alphaState.alphaBlend = true;
  3222. break;
  3223. case Engine.ALPHA_INTERPOLATE:
  3224. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  3225. this._alphaState.alphaBlend = true;
  3226. break;
  3227. case Engine.ALPHA_SCREENMODE:
  3228. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  3229. this._alphaState.alphaBlend = true;
  3230. break;
  3231. }
  3232. if (!noDepthWriteChange) {
  3233. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  3234. }
  3235. this._alphaMode = mode;
  3236. }
  3237. /**
  3238. * Gets the current alpha mode
  3239. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  3240. * @returns the current alpha mode
  3241. */
  3242. public getAlphaMode(): number {
  3243. return this._alphaMode;
  3244. }
  3245. // Textures
  3246. /**
  3247. * Clears the list of texture accessible through engine.
  3248. * This can help preventing texture load conflict due to name collision.
  3249. */
  3250. public clearInternalTexturesCache() {
  3251. this._internalTexturesCache = [];
  3252. }
  3253. /**
  3254. * Force the entire cache to be cleared
  3255. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  3256. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  3257. */
  3258. public wipeCaches(bruteForce?: boolean): void {
  3259. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  3260. return;
  3261. }
  3262. this._currentEffect = null;
  3263. this._unpackFlipYCached = null;
  3264. this._viewportCached.x = 0;
  3265. this._viewportCached.y = 0;
  3266. this._viewportCached.z = 0;
  3267. this._viewportCached.w = 0;
  3268. if (bruteForce) {
  3269. this.resetTextureCache();
  3270. this._currentProgram = null;
  3271. this._stencilState.reset();
  3272. this._depthCullingState.reset();
  3273. this.setDepthFunctionToLessOrEqual();
  3274. this._alphaState.reset();
  3275. }
  3276. this._resetVertexBufferBinding();
  3277. this._cachedIndexBuffer = null;
  3278. this._cachedEffectForVertexBuffers = null;
  3279. this._unbindVertexArrayObject();
  3280. this.bindIndexBuffer(null);
  3281. }
  3282. /**
  3283. * Set the compressed texture format to use, based on the formats you have, and the formats
  3284. * supported by the hardware / browser.
  3285. *
  3286. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  3287. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  3288. * to API arguments needed to compressed textures. This puts the burden on the container
  3289. * generator to house the arcane code for determining these for current & future formats.
  3290. *
  3291. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  3292. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  3293. *
  3294. * Note: The result of this call is not taken into account when a texture is base64.
  3295. *
  3296. * @param formatsAvailable defines the list of those format families you have created
  3297. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  3298. *
  3299. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  3300. * @returns The extension selected.
  3301. */
  3302. public setTextureFormatToUse(formatsAvailable: Array<string>): Nullable<string> {
  3303. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  3304. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  3305. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  3306. return this._textureFormatInUse = this._texturesSupported[i];
  3307. }
  3308. }
  3309. }
  3310. // actively set format to nothing, to allow this to be called more than once
  3311. // and possibly fail the 2nd time
  3312. this._textureFormatInUse = null;
  3313. return null;
  3314. }
  3315. private _getSamplingParameters(samplingMode: number, generateMipMaps: boolean): { min: number; mag: number } {
  3316. var gl = this._gl;
  3317. var magFilter = gl.NEAREST;
  3318. var minFilter = gl.NEAREST;
  3319. switch (samplingMode) {
  3320. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  3321. magFilter = gl.LINEAR;
  3322. if (generateMipMaps) {
  3323. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3324. } else {
  3325. minFilter = gl.LINEAR;
  3326. }
  3327. break;
  3328. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  3329. magFilter = gl.LINEAR;
  3330. if (generateMipMaps) {
  3331. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3332. } else {
  3333. minFilter = gl.LINEAR;
  3334. }
  3335. break;
  3336. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  3337. magFilter = gl.NEAREST;
  3338. if (generateMipMaps) {
  3339. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3340. } else {
  3341. minFilter = gl.NEAREST;
  3342. }
  3343. break;
  3344. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  3345. magFilter = gl.NEAREST;
  3346. if (generateMipMaps) {
  3347. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  3348. } else {
  3349. minFilter = gl.NEAREST;
  3350. }
  3351. break;
  3352. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  3353. magFilter = gl.NEAREST;
  3354. if (generateMipMaps) {
  3355. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3356. } else {
  3357. minFilter = gl.LINEAR;
  3358. }
  3359. break;
  3360. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  3361. magFilter = gl.NEAREST;
  3362. if (generateMipMaps) {
  3363. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3364. } else {
  3365. minFilter = gl.LINEAR;
  3366. }
  3367. break;
  3368. case Engine.TEXTURE_NEAREST_LINEAR:
  3369. magFilter = gl.NEAREST;
  3370. minFilter = gl.LINEAR;
  3371. break;
  3372. case Engine.TEXTURE_NEAREST_NEAREST:
  3373. magFilter = gl.NEAREST;
  3374. minFilter = gl.NEAREST;
  3375. break;
  3376. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  3377. magFilter = gl.LINEAR;
  3378. if (generateMipMaps) {
  3379. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  3380. } else {
  3381. minFilter = gl.NEAREST;
  3382. }
  3383. break;
  3384. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  3385. magFilter = gl.LINEAR;
  3386. if (generateMipMaps) {
  3387. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3388. } else {
  3389. minFilter = gl.NEAREST;
  3390. }
  3391. break;
  3392. case Engine.TEXTURE_LINEAR_LINEAR:
  3393. magFilter = gl.LINEAR;
  3394. minFilter = gl.LINEAR;
  3395. break;
  3396. case Engine.TEXTURE_LINEAR_NEAREST:
  3397. magFilter = gl.LINEAR;
  3398. minFilter = gl.NEAREST;
  3399. break;
  3400. }
  3401. return {
  3402. min: minFilter,
  3403. mag: magFilter
  3404. }
  3405. }
  3406. private _partialLoadImg(url: string, index: number, loadedImages: HTMLImageElement[], scene: Nullable<Scene>,
  3407. onfinish: (images: HTMLImageElement[]) => void, onErrorCallBack: Nullable<(message?: string, exception?: any) => void> = null) {
  3408. var img: HTMLImageElement;
  3409. var onload = () => {
  3410. loadedImages[index] = img;
  3411. (<any>loadedImages)._internalCount++;
  3412. if (scene) {
  3413. scene._removePendingData(img);
  3414. }
  3415. if ((<any>loadedImages)._internalCount === 6) {
  3416. onfinish(loadedImages);
  3417. }
  3418. };
  3419. var onerror = (message?: string, exception?: any) => {
  3420. if (scene) {
  3421. scene._removePendingData(img);
  3422. }
  3423. if (onErrorCallBack) {
  3424. onErrorCallBack(message, exception);
  3425. }
  3426. };
  3427. img = Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  3428. if (scene) {
  3429. scene._addPendingData(img);
  3430. }
  3431. }
  3432. private _cascadeLoadImgs(rootUrl: string, scene: Nullable<Scene>,
  3433. onfinish: (images: HTMLImageElement[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null) {
  3434. var loadedImages: HTMLImageElement[] = [];
  3435. (<any>loadedImages)._internalCount = 0;
  3436. for (let index = 0; index < 6; index++) {
  3437. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  3438. }
  3439. };
  3440. /** @hidden */
  3441. public _createTexture(): WebGLTexture {
  3442. let texture = this._gl.createTexture();
  3443. if (!texture) {
  3444. throw new Error("Unable to create texture");
  3445. }
  3446. return texture;
  3447. }
  3448. /**
  3449. * Usually called from BABYLON.Texture.ts.
  3450. * Passed information to create a WebGLTexture
  3451. * @param urlArg defines a value which contains one of the following:
  3452. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  3453. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  3454. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  3455. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  3456. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  3457. * @param scene needed for loading to the correct scene
  3458. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  3459. * @param onLoad optional callback to be called upon successful completion
  3460. * @param onError optional callback to be called upon failure
  3461. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  3462. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  3463. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  3464. * @param forcedExtension defines the extension to use to pick the right loader
  3465. * @returns a InternalTexture for assignment back into BABYLON.Texture
  3466. */
  3467. public createTexture(urlArg: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<Scene>, samplingMode: number = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE,
  3468. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  3469. buffer: Nullable<string | ArrayBuffer | HTMLImageElement | Blob> = null, fallback: Nullable<InternalTexture> = null, format: Nullable<number> = null,
  3470. forcedExtension: Nullable<string> = null): InternalTexture {
  3471. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  3472. var fromData = url.substr(0, 5) === "data:";
  3473. var fromBlob = url.substr(0, 5) === "blob:";
  3474. var isBase64 = fromData && url.indexOf("base64") !== -1;
  3475. let texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_URL);
  3476. // establish the file extension, if possible
  3477. var lastDot = url.lastIndexOf('.');
  3478. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  3479. let loader: Nullable<IInternalTextureLoader> = null;
  3480. for (let availableLoader of Engine._TextureLoaders) {
  3481. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  3482. loader = availableLoader;
  3483. break;
  3484. }
  3485. }
  3486. if (loader) {
  3487. url = loader.transformUrl(url, this._textureFormatInUse);
  3488. }
  3489. if (scene) {
  3490. scene._addPendingData(texture);
  3491. }
  3492. texture.url = url;
  3493. texture.generateMipMaps = !noMipmap;
  3494. texture.samplingMode = samplingMode;
  3495. texture.invertY = invertY;
  3496. if (!this._doNotHandleContextLost) {
  3497. // Keep a link to the buffer only if we plan to handle context lost
  3498. texture._buffer = buffer;
  3499. }
  3500. let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
  3501. if (onLoad && !fallback) {
  3502. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  3503. }
  3504. if (!fallback) this._internalTexturesCache.push(texture);
  3505. let onInternalError = (message?: string, exception?: any) => {
  3506. if (scene) {
  3507. scene._removePendingData(texture);
  3508. }
  3509. let customFallback = false;
  3510. if (loader) {
  3511. const fallbackUrl = loader.getFallbackTextureUrl(url, this._textureFormatInUse);
  3512. if (fallbackUrl) {
  3513. // Add Back
  3514. customFallback = true;
  3515. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  3516. }
  3517. }
  3518. if (!customFallback) {
  3519. if (onLoadObserver) {
  3520. texture.onLoadedObservable.remove(onLoadObserver);
  3521. }
  3522. if (Tools.UseFallbackTexture) {
  3523. this.createTexture(Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  3524. }
  3525. }
  3526. if (onError) {
  3527. onError(message || "Unknown error", exception);
  3528. }
  3529. }
  3530. // processing for non-image formats
  3531. if (loader) {
  3532. var callback = (data: string | ArrayBuffer) => {
  3533. loader!.loadData(data as ArrayBuffer, texture, (width: number, height: number, loadMipmap: boolean, isCompressed: boolean, done: () => void) => {
  3534. this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, () => {
  3535. done();
  3536. return false;
  3537. },
  3538. samplingMode);
  3539. });
  3540. }
  3541. if (!buffer) {
  3542. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, (request?: XMLHttpRequest, exception?: any) => {
  3543. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  3544. });
  3545. } else {
  3546. callback(buffer as ArrayBuffer);
  3547. }
  3548. } else {
  3549. var onload = (img: HTMLImageElement) => {
  3550. if (fromBlob && !this._doNotHandleContextLost) {
  3551. // We need to store the image if we need to rebuild the texture
  3552. // in case of a webgl context lost
  3553. texture._buffer = img;
  3554. }
  3555. this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight, continuationCallback) => {
  3556. let gl = this._gl;
  3557. var isPot = (img.width === potWidth && img.height === potHeight);
  3558. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  3559. if (isPot) {
  3560. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  3561. return false;
  3562. }
  3563. let maxTextureSize = this._caps.maxTextureSize;
  3564. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  3565. this._prepareWorkingCanvas();
  3566. if (!this._workingCanvas || !this._workingContext) {
  3567. return false;
  3568. }
  3569. this._workingCanvas.width = potWidth;
  3570. this._workingCanvas.height = potHeight;
  3571. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3572. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  3573. texture.width = potWidth;
  3574. texture.height = potHeight;
  3575. return false;
  3576. } else {
  3577. // Using shaders when possible to rescale because canvas.drawImage is lossy
  3578. let source = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  3579. this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  3580. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  3581. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3582. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  3583. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3584. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3585. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  3586. this._releaseTexture(source);
  3587. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  3588. continuationCallback();
  3589. });
  3590. }
  3591. return true;
  3592. }, samplingMode);
  3593. };
  3594. if (!fromData || isBase64) {
  3595. if (buffer instanceof HTMLImageElement) {
  3596. onload(buffer);
  3597. } else {
  3598. Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  3599. }
  3600. }
  3601. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  3602. Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  3603. }
  3604. else {
  3605. onload(<HTMLImageElement>buffer);
  3606. }
  3607. }
  3608. return texture;
  3609. }
  3610. private _rescaleTexture(source: InternalTexture, destination: InternalTexture, scene: Nullable<Scene>, internalFormat: number, onComplete: () => void): void {
  3611. let rtt = this.createRenderTargetTexture({
  3612. width: destination.width,
  3613. height: destination.height,
  3614. }, {
  3615. generateMipMaps: false,
  3616. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  3617. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  3618. generateDepthBuffer: false,
  3619. generateStencilBuffer: false
  3620. }
  3621. );
  3622. if (!this._rescalePostProcess) {
  3623. this._rescalePostProcess = new PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  3624. }
  3625. this._rescalePostProcess.getEffect().executeWhenCompiled(() => {
  3626. this._rescalePostProcess.onApply = function (effect) {
  3627. effect._bindTexture("textureSampler", source);
  3628. }
  3629. let hostingScene = scene;
  3630. if (!hostingScene) {
  3631. hostingScene = this.scenes[this.scenes.length - 1];
  3632. }
  3633. hostingScene.postProcessManager.directRender([this._rescalePostProcess], rtt, true);
  3634. this._bindTextureDirectly(this._gl.TEXTURE_2D, destination, true);
  3635. this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  3636. this.unBindFramebuffer(rtt);
  3637. this._releaseTexture(rtt);
  3638. if (onComplete) {
  3639. onComplete();
  3640. }
  3641. });
  3642. }
  3643. /**
  3644. * Update a raw texture
  3645. * @param texture defines the texture to update
  3646. * @param data defines the data to store in the texture
  3647. * @param format defines the format of the data
  3648. * @param invertY defines if data must be stored with Y axis inverted
  3649. * @param compression defines the compression used (null by default)
  3650. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  3651. */
  3652. public updateRawTexture(texture: Nullable<InternalTexture>, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, type = Engine.TEXTURETYPE_UNSIGNED_INT): void { if (!texture) {
  3653. return;
  3654. }
  3655. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  3656. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  3657. // babylon's internalFormat but gl's texImage2D format
  3658. var internalFormat = this._getInternalFormat(format);
  3659. var textureType = this._getWebGLTextureType(type);
  3660. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3661. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  3662. if (!this._doNotHandleContextLost) {
  3663. texture._bufferView = data;
  3664. texture.format = format;
  3665. texture.type = type;
  3666. texture.invertY = invertY;
  3667. texture._compression = compression;
  3668. }
  3669. if (texture.width % 4 !== 0) {
  3670. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  3671. }
  3672. if (compression && data) {
  3673. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, 0, <DataView>data);
  3674. } else {
  3675. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  3676. }
  3677. if (texture.generateMipMaps) {
  3678. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3679. }
  3680. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3681. // this.resetTextureCache();
  3682. texture.isReady = true;
  3683. }
  3684. /**
  3685. * Creates a raw texture
  3686. * @param data defines the data to store in the texture
  3687. * @param width defines the width of the texture
  3688. * @param height defines the height of the texture
  3689. * @param format defines the format of the data
  3690. * @param generateMipMaps defines if the engine should generate the mip levels
  3691. * @param invertY defines if data must be stored with Y axis inverted
  3692. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  3693. * @param compression defines the compression used (null by default)
  3694. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  3695. * @returns the raw texture inside an InternalTexture
  3696. */
  3697. public createRawTexture(data: Nullable<ArrayBufferView>, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null, type: number = Engine.TEXTURETYPE_UNSIGNED_INT): InternalTexture {
  3698. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW);
  3699. texture.baseWidth = width;
  3700. texture.baseHeight = height;
  3701. texture.width = width;
  3702. texture.height = height;
  3703. texture.format = format;
  3704. texture.generateMipMaps = generateMipMaps;
  3705. texture.samplingMode = samplingMode;
  3706. texture.invertY = invertY;
  3707. texture._compression = compression;
  3708. texture.type = type;
  3709. if (!this._doNotHandleContextLost) {
  3710. texture._bufferView = data;
  3711. }
  3712. this.updateRawTexture(texture, data, format, invertY, compression, type);
  3713. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3714. // Filters
  3715. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  3716. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3717. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3718. if (generateMipMaps) {
  3719. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3720. }
  3721. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3722. this._internalTexturesCache.push(texture);
  3723. return texture;
  3724. }
  3725. private _unpackFlipYCached: Nullable<boolean> = null;
  3726. /** @hidden */
  3727. public _unpackFlipY(value: boolean) {
  3728. if (this._unpackFlipYCached !== value) {
  3729. this._unpackFlipYCached = value;
  3730. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  3731. }
  3732. }
  3733. /** @hidden */
  3734. public _getUnpackAlignement(): number {
  3735. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  3736. }
  3737. /**
  3738. * Creates a dynamic texture
  3739. * @param width defines the width of the texture
  3740. * @param height defines the height of the texture
  3741. * @param generateMipMaps defines if the engine should generate the mip levels
  3742. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  3743. * @returns the dynamic texture inside an InternalTexture
  3744. */
  3745. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): InternalTexture {
  3746. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_DYNAMIC)
  3747. texture.baseWidth = width;
  3748. texture.baseHeight = height;
  3749. if (generateMipMaps) {
  3750. width = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  3751. height = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  3752. }
  3753. // this.resetTextureCache();
  3754. texture.width = width;
  3755. texture.height = height;
  3756. texture.isReady = false;
  3757. texture.generateMipMaps = generateMipMaps;
  3758. texture.samplingMode = samplingMode;
  3759. this.updateTextureSamplingMode(samplingMode, texture);
  3760. this._internalTexturesCache.push(texture);
  3761. return texture;
  3762. }
  3763. /**
  3764. * Update the sampling mode of a given texture
  3765. * @param samplingMode defines the required sampling mode
  3766. * @param texture defines the texture to update
  3767. */
  3768. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  3769. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  3770. if (texture.isCube) {
  3771. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3772. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3773. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3774. } else if (texture.is3D) {
  3775. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3776. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3777. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3778. } else {
  3779. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3780. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3781. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3782. }
  3783. texture.samplingMode = samplingMode;
  3784. }
  3785. /**
  3786. * Update the content of a dynamic texture
  3787. * @param texture defines the texture to update
  3788. * @param canvas defines the canvas containing the source
  3789. * @param invertY defines if data must be stored with Y axis inverted
  3790. * @param premulAlpha defines if alpha is stored as premultiplied
  3791. * @param format defines the format of the data
  3792. */
  3793. public updateDynamicTexture(texture: Nullable<InternalTexture>, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  3794. if (!texture) {
  3795. return;
  3796. }
  3797. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3798. this._unpackFlipY(invertY);
  3799. if (premulAlpha) {
  3800. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  3801. }
  3802. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  3803. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  3804. if (texture.generateMipMaps) {
  3805. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3806. }
  3807. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3808. if (premulAlpha) {
  3809. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  3810. }
  3811. texture.isReady = true;
  3812. }
  3813. /**
  3814. * Update a video texture
  3815. * @param texture defines the texture to update
  3816. * @param video defines the video element to use
  3817. * @param invertY defines if data must be stored with Y axis inverted
  3818. */
  3819. public updateVideoTexture(texture: Nullable<InternalTexture>, video: HTMLVideoElement, invertY: boolean): void {
  3820. if (!texture || texture._isDisabled) {
  3821. return;
  3822. }
  3823. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3824. this._unpackFlipY(!invertY); // Video are upside down by default
  3825. try {
  3826. // Testing video texture support
  3827. if (this._videoTextureSupported === undefined) {
  3828. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3829. if (this._gl.getError() !== 0) {
  3830. this._videoTextureSupported = false;
  3831. } else {
  3832. this._videoTextureSupported = true;
  3833. }
  3834. }
  3835. // Copy video through the current working canvas if video texture is not supported
  3836. if (!this._videoTextureSupported) {
  3837. if (!texture._workingCanvas) {
  3838. texture._workingCanvas = document.createElement("canvas");
  3839. let context = texture._workingCanvas.getContext("2d");
  3840. if (!context) {
  3841. throw new Error("Unable to get 2d context");
  3842. }
  3843. texture._workingContext = context;
  3844. texture._workingCanvas.width = texture.width;
  3845. texture._workingCanvas.height = texture.height;
  3846. }
  3847. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  3848. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3849. } else {
  3850. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3851. }
  3852. if (texture.generateMipMaps) {
  3853. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3854. }
  3855. if (!wasPreviouslyBound) {
  3856. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3857. }
  3858. // this.resetTextureCache();
  3859. texture.isReady = true;
  3860. } catch (ex) {
  3861. // Something unexpected
  3862. // Let's disable the texture
  3863. texture._isDisabled = true;
  3864. }
  3865. }
  3866. /**
  3867. * Updates a depth texture Comparison Mode and Function.
  3868. * If the comparison Function is equal to 0, the mode will be set to none.
  3869. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  3870. * @param texture The texture to set the comparison function for
  3871. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  3872. */
  3873. public updateTextureComparisonFunction(texture: InternalTexture, comparisonFunction: number): void {
  3874. if (this.webGLVersion === 1) {
  3875. Tools.Error("WebGL 1 does not support texture comparison.");
  3876. return;
  3877. }
  3878. var gl = this._gl;
  3879. if (texture.isCube) {
  3880. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  3881. if (comparisonFunction === 0) {
  3882. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  3883. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  3884. }
  3885. else {
  3886. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  3887. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  3888. }
  3889. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3890. } else {
  3891. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3892. if (comparisonFunction === 0) {
  3893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  3894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  3895. }
  3896. else {
  3897. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  3898. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  3899. }
  3900. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3901. }
  3902. texture._comparisonFunction = comparisonFunction;
  3903. }
  3904. private _setupDepthStencilTexture(internalTexture: InternalTexture, size: number | { width: number, height: number }, generateStencil: boolean, bilinearFiltering: boolean, comparisonFunction: number) : void {
  3905. var width = (<{ width: number, height: number }>size).width || <number>size;
  3906. var height = (<{ width: number, height: number }>size).height || <number>size;
  3907. internalTexture.baseWidth = width;
  3908. internalTexture.baseHeight = height;
  3909. internalTexture.width = width;
  3910. internalTexture.height = height;
  3911. internalTexture.isReady = true;
  3912. internalTexture.samples = 1;
  3913. internalTexture.generateMipMaps = false;
  3914. internalTexture._generateDepthBuffer = true;
  3915. internalTexture._generateStencilBuffer = generateStencil;
  3916. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  3917. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  3918. internalTexture._comparisonFunction = comparisonFunction;
  3919. var gl = this._gl;
  3920. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  3921. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  3922. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  3923. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  3924. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3925. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3926. if (comparisonFunction === 0) {
  3927. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  3928. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  3929. }
  3930. else {
  3931. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  3932. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  3933. }
  3934. }
  3935. /**
  3936. * Creates a depth stencil texture.
  3937. * This is only available in WebGL 2 or with the depth texture extension available.
  3938. * @param size The size of face edge in the texture.
  3939. * @param options The options defining the texture.
  3940. * @returns The texture
  3941. */
  3942. public createDepthStencilTexture(size: number | { width: number, height: number }, options: DepthTextureCreationOptions) : InternalTexture {
  3943. if (options.isCube) {
  3944. let width = (<{ width: number, height: number }>size).width || <number>size;
  3945. return this._createDepthStencilCubeTexture(width, options);
  3946. }
  3947. else {
  3948. return this._createDepthStencilTexture(size, options);
  3949. }
  3950. }
  3951. /**
  3952. * Creates a depth stencil texture.
  3953. * This is only available in WebGL 2 or with the depth texture extension available.
  3954. * @param size The size of face edge in the texture.
  3955. * @param options The options defining the texture.
  3956. * @returns The texture
  3957. */
  3958. private _createDepthStencilTexture(size: number | { width: number, height: number }, options: DepthTextureCreationOptions) : InternalTexture {
  3959. var internalTexture = new InternalTexture(this, InternalTexture.DATASOURCE_DEPTHTEXTURE);
  3960. if (!this._caps.depthTextureExtension) {
  3961. Tools.Error("Depth texture is not supported by your browser or hardware.");
  3962. return internalTexture;
  3963. }
  3964. var internalOptions = {
  3965. bilinearFiltering: false,
  3966. comparisonFunction: 0,
  3967. generateStencil: false,
  3968. ...options
  3969. }
  3970. var gl = this._gl;
  3971. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  3972. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  3973. if (this.webGLVersion > 1) {
  3974. if (internalOptions.generateStencil) {
  3975. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  3976. }
  3977. else {
  3978. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  3979. }
  3980. }
  3981. else {
  3982. if (internalOptions.generateStencil) {
  3983. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  3984. }
  3985. else {
  3986. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  3987. }
  3988. }
  3989. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  3990. return internalTexture;
  3991. }
  3992. /**
  3993. * Creates a depth stencil cube texture.
  3994. * This is only available in WebGL 2.
  3995. * @param size The size of face edge in the cube texture.
  3996. * @param options The options defining the cube texture.
  3997. * @returns The cube texture
  3998. */
  3999. private _createDepthStencilCubeTexture(size: number, options: DepthTextureCreationOptions) : InternalTexture {
  4000. var internalTexture = new InternalTexture(this, InternalTexture.DATASOURCE_UNKNOWN);
  4001. internalTexture.isCube = true;
  4002. if (this.webGLVersion === 1) {
  4003. Tools.Error("Depth cube texture is not supported by WebGL 1.");
  4004. return internalTexture;
  4005. }
  4006. var internalOptions = {
  4007. bilinearFiltering: false,
  4008. comparisonFunction: 0,
  4009. generateStencil: false,
  4010. ...options
  4011. }
  4012. var gl = this._gl;
  4013. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  4014. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  4015. // Create the depth/stencil buffer
  4016. for (var face = 0; face < 6; face++) {
  4017. if (internalOptions.generateStencil) {
  4018. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  4019. }
  4020. else {
  4021. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  4022. }
  4023. }
  4024. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4025. return internalTexture;
  4026. }
  4027. /**
  4028. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  4029. * @param renderTarget The render target to set the frame buffer for
  4030. */
  4031. public setFrameBufferDepthStencilTexture(renderTarget: RenderTargetTexture): void {
  4032. // Create the framebuffer
  4033. var internalTexture = renderTarget.getInternalTexture();
  4034. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  4035. return;
  4036. }
  4037. var gl = this._gl;
  4038. var depthStencilTexture = renderTarget.depthStencilTexture;
  4039. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  4040. if (depthStencilTexture.isCube) {
  4041. if (depthStencilTexture._generateStencilBuffer) {
  4042. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  4043. }
  4044. else {
  4045. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  4046. }
  4047. }
  4048. else {
  4049. if (depthStencilTexture._generateStencilBuffer) {
  4050. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  4051. }
  4052. else {
  4053. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  4054. }
  4055. }
  4056. this.bindUnboundFramebuffer(null);
  4057. }
  4058. /**
  4059. * Creates a new render target texture
  4060. * @param size defines the size of the texture
  4061. * @param options defines the options used to create the texture
  4062. * @returns a new render target texture stored in an InternalTexture
  4063. */
  4064. public createRenderTargetTexture(size: number | { width: number, height: number }, options: boolean | RenderTargetCreationOptions): InternalTexture {
  4065. let fullOptions = new RenderTargetCreationOptions();
  4066. if (options !== undefined && typeof options === "object") {
  4067. fullOptions.generateMipMaps = options.generateMipMaps;
  4068. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4069. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  4070. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  4071. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  4072. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  4073. } else {
  4074. fullOptions.generateMipMaps = <boolean>options;
  4075. fullOptions.generateDepthBuffer = true;
  4076. fullOptions.generateStencilBuffer = false;
  4077. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4078. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  4079. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  4080. }
  4081. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4082. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4083. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4084. }
  4085. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4086. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4087. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4088. }
  4089. var gl = this._gl;
  4090. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  4091. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  4092. var width = (<{ width: number, height: number }>size).width || <number>size;
  4093. var height = (<{ width: number, height: number }>size).height || <number>size;
  4094. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  4095. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4096. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4097. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4098. }
  4099. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4100. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4101. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4102. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4103. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  4104. // Create the framebuffer
  4105. var currentFrameBuffer = this._currentFramebuffer;
  4106. var framebuffer = gl.createFramebuffer();
  4107. this.bindUnboundFramebuffer(framebuffer);
  4108. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  4109. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  4110. if (fullOptions.generateMipMaps) {
  4111. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4112. }
  4113. // Unbind
  4114. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4115. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4116. this.bindUnboundFramebuffer(currentFrameBuffer);
  4117. texture._framebuffer = framebuffer;
  4118. texture.baseWidth = width;
  4119. texture.baseHeight = height;
  4120. texture.width = width;
  4121. texture.height = height;
  4122. texture.isReady = true;
  4123. texture.samples = 1;
  4124. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  4125. texture.samplingMode = fullOptions.samplingMode;
  4126. texture.type = fullOptions.type;
  4127. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  4128. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  4129. // this.resetTextureCache();
  4130. this._internalTexturesCache.push(texture);
  4131. return texture;
  4132. }
  4133. /**
  4134. * Create a multi render target texture
  4135. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  4136. * @param size defines the size of the texture
  4137. * @param options defines the creation options
  4138. * @returns the cube texture as an InternalTexture
  4139. */
  4140. public createMultipleRenderTarget(size: any, options: IMultiRenderTargetOptions): InternalTexture[] {
  4141. var generateMipMaps = false;
  4142. var generateDepthBuffer = true;
  4143. var generateStencilBuffer = false;
  4144. var generateDepthTexture = false;
  4145. var textureCount = 1;
  4146. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  4147. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  4148. var types = new Array<number>();
  4149. var samplingModes = new Array<number>();
  4150. if (options !== undefined) {
  4151. generateMipMaps = options.generateMipMaps === undefined ? false: options.generateMipMaps;
  4152. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4153. generateStencilBuffer = options.generateStencilBuffer === undefined ? false: options.generateStencilBuffer;
  4154. generateDepthTexture = options.generateDepthTexture === undefined ? false: options.generateDepthTexture;
  4155. textureCount = options.textureCount || 1;
  4156. if (options.types) {
  4157. types = options.types;
  4158. }
  4159. if (options.samplingModes) {
  4160. samplingModes = options.samplingModes;
  4161. }
  4162. }
  4163. var gl = this._gl;
  4164. // Create the framebuffer
  4165. var framebuffer = gl.createFramebuffer();
  4166. this.bindUnboundFramebuffer(framebuffer);
  4167. var width = size.width || size;
  4168. var height = size.height || size;
  4169. var textures = [];
  4170. var attachments = []
  4171. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  4172. for (var i = 0; i < textureCount; i++) {
  4173. var samplingMode = samplingModes[i] || defaultSamplingMode;
  4174. var type = types[i] || defaultType;
  4175. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4176. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4177. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4178. }
  4179. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4180. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4181. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4182. }
  4183. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  4184. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4185. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4186. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4187. }
  4188. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  4189. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  4190. textures.push(texture);
  4191. attachments.push(attachment);
  4192. gl.activeTexture((<any>gl)["TEXTURE" + i]);
  4193. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  4194. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4195. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4196. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4197. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4198. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  4199. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  4200. if (generateMipMaps) {
  4201. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4202. }
  4203. // Unbind
  4204. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4205. texture._framebuffer = framebuffer;
  4206. texture._depthStencilBuffer = depthStencilBuffer;
  4207. texture.baseWidth = width;
  4208. texture.baseHeight = height;
  4209. texture.width = width;
  4210. texture.height = height;
  4211. texture.isReady = true;
  4212. texture.samples = 1;
  4213. texture.generateMipMaps = generateMipMaps;
  4214. texture.samplingMode = samplingMode;
  4215. texture.type = type;
  4216. texture._generateDepthBuffer = generateDepthBuffer;
  4217. texture._generateStencilBuffer = generateStencilBuffer;
  4218. texture._attachments = attachments;
  4219. this._internalTexturesCache.push(texture);
  4220. }
  4221. if (generateDepthTexture && this._caps.depthTextureExtension) {
  4222. // Depth texture
  4223. var depthTexture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  4224. gl.activeTexture(gl.TEXTURE0);
  4225. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  4226. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4227. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4228. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4229. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4230. gl.texImage2D(
  4231. gl.TEXTURE_2D,
  4232. 0,
  4233. this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16,
  4234. width,
  4235. height,
  4236. 0,
  4237. gl.DEPTH_COMPONENT,
  4238. gl.UNSIGNED_SHORT,
  4239. null
  4240. );
  4241. gl.framebufferTexture2D(
  4242. gl.FRAMEBUFFER,
  4243. gl.DEPTH_ATTACHMENT,
  4244. gl.TEXTURE_2D,
  4245. depthTexture._webGLTexture,
  4246. 0
  4247. );
  4248. depthTexture._framebuffer = framebuffer;
  4249. depthTexture.baseWidth = width;
  4250. depthTexture.baseHeight = height;
  4251. depthTexture.width = width;
  4252. depthTexture.height = height;
  4253. depthTexture.isReady = true;
  4254. depthTexture.samples = 1;
  4255. depthTexture.generateMipMaps = generateMipMaps;
  4256. depthTexture.samplingMode = gl.NEAREST;
  4257. depthTexture._generateDepthBuffer = generateDepthBuffer;
  4258. depthTexture._generateStencilBuffer = generateStencilBuffer;
  4259. textures.push(depthTexture)
  4260. this._internalTexturesCache.push(depthTexture);
  4261. }
  4262. gl.drawBuffers(attachments);
  4263. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4264. this.bindUnboundFramebuffer(null);
  4265. this.resetTextureCache();
  4266. return textures;
  4267. }
  4268. private _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): Nullable<WebGLRenderbuffer> {
  4269. var depthStencilBuffer: Nullable<WebGLRenderbuffer> = null;
  4270. var gl = this._gl;
  4271. // Create the depth/stencil buffer
  4272. if (generateStencilBuffer) {
  4273. depthStencilBuffer = gl.createRenderbuffer();
  4274. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  4275. if (samples > 1) {
  4276. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  4277. } else {
  4278. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  4279. }
  4280. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  4281. }
  4282. else if (generateDepthBuffer) {
  4283. depthStencilBuffer = gl.createRenderbuffer();
  4284. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  4285. if (samples > 1) {
  4286. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  4287. } else {
  4288. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4289. }
  4290. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  4291. }
  4292. return depthStencilBuffer;
  4293. }
  4294. /**
  4295. * Updates the sample count of a render target texture
  4296. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  4297. * @param texture defines the texture to update
  4298. * @param samples defines the sample count to set
  4299. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  4300. */
  4301. public updateRenderTargetTextureSampleCount(texture: Nullable<InternalTexture>, samples: number): number {
  4302. if (this.webGLVersion < 2 || !texture) {
  4303. return 1;
  4304. }
  4305. if (texture.samples === samples) {
  4306. return samples;
  4307. }
  4308. var gl = this._gl;
  4309. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  4310. // Dispose previous render buffers
  4311. if (texture._depthStencilBuffer) {
  4312. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  4313. texture._depthStencilBuffer = null;
  4314. }
  4315. if (texture._MSAAFramebuffer) {
  4316. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  4317. texture._MSAAFramebuffer = null;
  4318. }
  4319. if (texture._MSAARenderBuffer) {
  4320. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  4321. texture._MSAARenderBuffer = null;
  4322. }
  4323. if (samples > 1) {
  4324. let framebuffer = gl.createFramebuffer();
  4325. if (!framebuffer) {
  4326. throw new Error("Unable to create multi sampled framebuffer");
  4327. }
  4328. texture._MSAAFramebuffer = framebuffer;
  4329. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  4330. var colorRenderbuffer = gl.createRenderbuffer();
  4331. if (!colorRenderbuffer) {
  4332. throw new Error("Unable to create multi sampled framebuffer");
  4333. }
  4334. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  4335. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  4336. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  4337. texture._MSAARenderBuffer = colorRenderbuffer;
  4338. } else {
  4339. this.bindUnboundFramebuffer(texture._framebuffer);
  4340. }
  4341. texture.samples = samples;
  4342. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  4343. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4344. this.bindUnboundFramebuffer(null);
  4345. return samples;
  4346. }
  4347. /**
  4348. * Update the sample count for a given multiple render target texture
  4349. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  4350. * @param textures defines the textures to update
  4351. * @param samples defines the sample count to set
  4352. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  4353. */
  4354. public updateMultipleRenderTargetTextureSampleCount(textures: Nullable<InternalTexture[]>, samples: number): number {
  4355. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  4356. return 1;
  4357. }
  4358. if (textures[0].samples === samples) {
  4359. return samples;
  4360. }
  4361. var gl = this._gl;
  4362. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  4363. // Dispose previous render buffers
  4364. if (textures[0]._depthStencilBuffer) {
  4365. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  4366. textures[0]._depthStencilBuffer = null;
  4367. }
  4368. if (textures[0]._MSAAFramebuffer) {
  4369. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  4370. textures[0]._MSAAFramebuffer = null;
  4371. }
  4372. for (var i = 0; i < textures.length; i++) {
  4373. if (textures[i]._MSAARenderBuffer) {
  4374. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  4375. textures[i]._MSAARenderBuffer = null;
  4376. }
  4377. }
  4378. if (samples > 1) {
  4379. let framebuffer = gl.createFramebuffer();
  4380. if (!framebuffer) {
  4381. throw new Error("Unable to create multi sampled framebuffer");
  4382. }
  4383. this.bindUnboundFramebuffer(framebuffer);
  4384. let depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  4385. var attachments = [];
  4386. for (var i = 0; i < textures.length; i++) {
  4387. var texture = textures[i];
  4388. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  4389. var colorRenderbuffer = gl.createRenderbuffer();
  4390. if (!colorRenderbuffer) {
  4391. throw new Error("Unable to create multi sampled framebuffer");
  4392. }
  4393. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  4394. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  4395. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  4396. texture._MSAAFramebuffer = framebuffer;
  4397. texture._MSAARenderBuffer = colorRenderbuffer;
  4398. texture.samples = samples;
  4399. texture._depthStencilBuffer = depthStencilBuffer;
  4400. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4401. attachments.push(attachment);
  4402. }
  4403. gl.drawBuffers(attachments);
  4404. } else {
  4405. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  4406. }
  4407. this.bindUnboundFramebuffer(null);
  4408. return samples;
  4409. }
  4410. /** @hidden */
  4411. public _uploadCompressedDataToTextureDirectly(texture: InternalTexture, internalFormat: number, width: number, height: number, data: ArrayBufferView, faceIndex: number = 0, lod: number = 0) {
  4412. var gl = this._gl;
  4413. var target = gl.TEXTURE_2D;
  4414. if (texture.isCube) {
  4415. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  4416. }
  4417. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, <DataView>data);
  4418. }
  4419. /** @hidden */
  4420. public _uploadDataToTextureDirectly(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  4421. var gl = this._gl;
  4422. var textureType = this._getWebGLTextureType(texture.type);
  4423. var format = this._getInternalFormat(texture.format);
  4424. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  4425. this._unpackFlipY(texture.invertY);
  4426. var target = gl.TEXTURE_2D;
  4427. if (texture.isCube) {
  4428. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  4429. }
  4430. const lodMaxWidth = Math.round(Scalar.Log2(texture.width));
  4431. const lodMaxHeight = Math.round(Scalar.Log2(texture.height));
  4432. const width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  4433. const height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  4434. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  4435. }
  4436. /** @hidden */
  4437. public _uploadArrayBufferViewToTexture(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  4438. var gl = this._gl;
  4439. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  4440. this._bindTextureDirectly(bindTarget, texture, true);
  4441. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  4442. this._bindTextureDirectly(bindTarget, null, true);
  4443. }
  4444. /** @hidden */
  4445. public _uploadImageToTexture(texture: InternalTexture, image: HTMLImageElement, faceIndex: number = 0, lod: number = 0) {
  4446. var gl = this._gl;
  4447. var textureType = this._getWebGLTextureType(texture.type);
  4448. var format = this._getInternalFormat(texture.format);
  4449. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  4450. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  4451. this._bindTextureDirectly(bindTarget, texture, true);
  4452. this._unpackFlipY(texture.invertY);
  4453. var target = gl.TEXTURE_2D;
  4454. if (texture.isCube) {
  4455. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  4456. }
  4457. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  4458. this._bindTextureDirectly(bindTarget, null, true);
  4459. }
  4460. /**
  4461. * Creates a new render target cube texture
  4462. * @param size defines the size of the texture
  4463. * @param options defines the options used to create the texture
  4464. * @returns a new render target cube texture stored in an InternalTexture
  4465. */
  4466. public createRenderTargetCubeTexture(size: number, options?: Partial<RenderTargetCreationOptions>): InternalTexture {
  4467. let fullOptions = {
  4468. generateMipMaps: true,
  4469. generateDepthBuffer: true,
  4470. generateStencilBuffer: false,
  4471. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  4472. samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE,
  4473. format: Engine.TEXTUREFORMAT_RGBA,
  4474. ...options
  4475. };
  4476. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  4477. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4478. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4479. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4480. }
  4481. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4482. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4483. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4484. }
  4485. var gl = this._gl
  4486. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  4487. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4488. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  4489. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4490. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4491. Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  4492. }
  4493. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  4494. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  4495. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4496. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4497. for (var face = 0; face < 6; face++) {
  4498. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  4499. }
  4500. // Create the framebuffer
  4501. var framebuffer = gl.createFramebuffer();
  4502. this.bindUnboundFramebuffer(framebuffer);
  4503. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  4504. // MipMaps
  4505. if (fullOptions.generateMipMaps) {
  4506. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4507. }
  4508. // Unbind
  4509. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4510. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4511. this.bindUnboundFramebuffer(null);
  4512. texture._framebuffer = framebuffer;
  4513. texture.width = size;
  4514. texture.height = size;
  4515. texture.isReady = true;
  4516. texture.isCube = true;
  4517. texture.samples = 1;
  4518. texture.generateMipMaps = fullOptions.generateMipMaps;
  4519. texture.samplingMode = fullOptions.samplingMode;
  4520. texture.type = fullOptions.type;
  4521. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  4522. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  4523. this._internalTexturesCache.push(texture);
  4524. return texture;
  4525. }
  4526. /**
  4527. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  4528. * @param rootUrl defines the url where the file to load is located
  4529. * @param scene defines the current scene
  4530. * @param lodScale defines scale to apply to the mip map selection
  4531. * @param lodOffset defines offset to apply to the mip map selection
  4532. * @param onLoad defines an optional callback raised when the texture is loaded
  4533. * @param onError defines an optional callback raised if there is an issue to load the texture
  4534. * @param format defines the format of the data
  4535. * @param forcedExtension defines the extension to use to pick the right loader
  4536. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  4537. * @returns the cube texture as an InternalTexture
  4538. */
  4539. public createPrefilteredCubeTexture(rootUrl: string, scene: Nullable<Scene>, lodScale: number, lodOffset: number,
  4540. onLoad: Nullable<(internalTexture: Nullable<InternalTexture>) => void> = null,
  4541. onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null,
  4542. createPolynomials: boolean = true): InternalTexture {
  4543. var callback = (loadData: any) => {
  4544. if (!loadData) {
  4545. if (onLoad) {
  4546. onLoad(null);
  4547. }
  4548. return;
  4549. }
  4550. let texture = loadData.texture as InternalTexture;
  4551. if (!createPolynomials) {
  4552. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  4553. }
  4554. else if(loadData.info.sphericalPolynomial){
  4555. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  4556. }
  4557. texture._dataSource = InternalTexture.DATASOURCE_CUBEPREFILTERED;
  4558. if (this._caps.textureLOD) {
  4559. // Do not add extra process if texture lod is supported.
  4560. if (onLoad) {
  4561. onLoad(texture);
  4562. }
  4563. return;
  4564. }
  4565. const mipSlices = 3;
  4566. var gl = this._gl;
  4567. const width = loadData.width;
  4568. if (!width) {
  4569. return;
  4570. }
  4571. const textures: BaseTexture[] = [];
  4572. for (let i = 0; i < mipSlices; i++) {
  4573. //compute LOD from even spacing in smoothness (matching shader calculation)
  4574. let smoothness = i / (mipSlices - 1);
  4575. let roughness = 1 - smoothness;
  4576. let minLODIndex = lodOffset; // roughness = 0
  4577. let maxLODIndex = Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  4578. let lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  4579. let mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  4580. var glTextureFromLod = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  4581. glTextureFromLod.type = texture.type;
  4582. glTextureFromLod.format = texture.format;
  4583. glTextureFromLod.width = Math.pow(2, Math.max( Scalar.Log2(width) - mipmapIndex, 0));
  4584. glTextureFromLod.height = glTextureFromLod.width;
  4585. glTextureFromLod.isCube = true;
  4586. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  4587. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  4589. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4590. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4591. if (loadData.isDDS) {
  4592. var info: DDSInfo = loadData.info;
  4593. var data: any = loadData.data;
  4594. this._unpackFlipY(info.isCompressed);
  4595. DDSTools.UploadDDSLevels(this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  4596. }
  4597. else {
  4598. Tools.Warn("DDS is the only prefiltered cube map supported so far.")
  4599. }
  4600. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4601. // Wrap in a base texture for easy binding.
  4602. const lodTexture = new BaseTexture(scene);
  4603. lodTexture.isCube = true;
  4604. lodTexture._texture = glTextureFromLod;
  4605. glTextureFromLod.isReady = true;
  4606. textures.push(lodTexture);
  4607. }
  4608. texture._lodTextureHigh = textures[2];
  4609. texture._lodTextureMid = textures[1];
  4610. texture._lodTextureLow = textures[0];
  4611. if (onLoad) {
  4612. onLoad(texture);
  4613. }
  4614. };
  4615. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  4616. }
  4617. /**
  4618. * Creates a cube texture
  4619. * @param rootUrl defines the url where the files to load is located
  4620. * @param scene defines the current scene
  4621. * @param files defines the list of files to load (1 per face)
  4622. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  4623. * @param onLoad defines an optional callback raised when the texture is loaded
  4624. * @param onError defines an optional callback raised if there is an issue to load the texture
  4625. * @param format defines the format of the data
  4626. * @param forcedExtension defines the extension to use to pick the right loader
  4627. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  4628. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  4629. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  4630. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  4631. * @returns the cube texture as an InternalTexture
  4632. */
  4633. public createCubeTexture(rootUrl: string, scene: Nullable<Scene>, files: Nullable<string[]>, noMipmap?: boolean, onLoad: Nullable<(data?: any) => void> = null, onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null, createPolynomials = false, lodScale: number = 0, lodOffset: number = 0, fallback: Nullable<InternalTexture> = null): InternalTexture {
  4634. var gl = this._gl;
  4635. var texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
  4636. texture.isCube = true;
  4637. texture.url = rootUrl;
  4638. texture.generateMipMaps = !noMipmap;
  4639. texture._lodGenerationScale = lodScale;
  4640. texture._lodGenerationOffset = lodOffset;
  4641. if (!this._doNotHandleContextLost) {
  4642. texture._extension = forcedExtension;
  4643. texture._files = files;
  4644. }
  4645. var lastDot = rootUrl.lastIndexOf('.');
  4646. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  4647. let loader: Nullable<IInternalTextureLoader> = null;
  4648. for (let availableLoader of Engine._TextureLoaders) {
  4649. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  4650. loader = availableLoader;
  4651. break;
  4652. }
  4653. }
  4654. let onInternalError = (request?: XMLHttpRequest, exception?: any) => {
  4655. if (loader) {
  4656. const fallbackUrl = loader.getFallbackTextureUrl(rootUrl, this._textureFormatInUse);
  4657. if (fallbackUrl) {
  4658. this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  4659. }
  4660. }
  4661. if (onError && request) {
  4662. onError(request.status + " " + request.statusText, exception);
  4663. }
  4664. }
  4665. if (loader) {
  4666. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  4667. const onloaddata = (data: any) => {
  4668. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4669. loader!.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  4670. };
  4671. if (files && files.length === 6) {
  4672. if (loader.supportCascades) {
  4673. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  4674. }
  4675. else if (onError) {
  4676. onError("Textures type does not support cascades.");
  4677. }
  4678. }
  4679. else {
  4680. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  4681. }
  4682. }
  4683. else {
  4684. if (!files) {
  4685. throw new Error("Cannot load cubemap because files were not defined");
  4686. }
  4687. this._cascadeLoadImgs(rootUrl, scene, imgs => {
  4688. var width = this.needPOTTextures ? Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width;
  4689. var height = width;
  4690. this._prepareWorkingCanvas();
  4691. if (!this._workingCanvas || !this._workingContext) {
  4692. return;
  4693. }
  4694. this._workingCanvas.width = width;
  4695. this._workingCanvas.height = height;
  4696. var faces = [
  4697. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4698. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4699. ];
  4700. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4701. this._unpackFlipY(false);
  4702. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  4703. for (var index = 0; index < faces.length; index++) {
  4704. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4705. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  4706. }
  4707. if (!noMipmap) {
  4708. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4709. }
  4710. this._setCubeMapTextureParams(!noMipmap);
  4711. texture.width = width;
  4712. texture.height = height;
  4713. texture.isReady = true;
  4714. if (format) {
  4715. texture.format = format;
  4716. }
  4717. texture.onLoadedObservable.notifyObservers(texture);
  4718. texture.onLoadedObservable.clear();
  4719. if (onLoad) {
  4720. onLoad();
  4721. }
  4722. }, files, onError);
  4723. }
  4724. this._internalTexturesCache.push(texture);
  4725. return texture;
  4726. }
  4727. /**
  4728. * @hidden
  4729. */
  4730. public _setCubeMapTextureParams(loadMipmap: boolean): void {
  4731. var gl = this._gl;
  4732. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4733. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4734. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4735. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4736. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4737. // this.resetTextureCache();
  4738. }
  4739. /**
  4740. * Update a raw cube texture
  4741. * @param texture defines the texture to udpdate
  4742. * @param data defines the data to store
  4743. * @param format defines the data format
  4744. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  4745. * @param invertY defines if data must be stored with Y axis inverted
  4746. * @param compression defines the compression used (null by default)
  4747. * @param level defines which level of the texture to update
  4748. */
  4749. public updateRawCubeTexture(texture: InternalTexture, data: ArrayBufferView[], format: number, type: number, invertY: boolean, compression: Nullable<string> = null, level = 0): void {
  4750. texture._bufferViewArray = data;
  4751. texture.format = format;
  4752. texture.type = type;
  4753. texture.invertY = invertY;
  4754. texture._compression = compression;
  4755. var gl = this._gl;
  4756. var textureType = this._getWebGLTextureType(type);
  4757. var internalFormat = this._getInternalFormat(format);
  4758. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  4759. var needConversion = false;
  4760. if (internalFormat === gl.RGB) {
  4761. internalFormat = gl.RGBA;
  4762. needConversion = true;
  4763. }
  4764. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4765. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  4766. if (texture.width % 4 !== 0) {
  4767. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  4768. }
  4769. // Data are known to be in +X +Y +Z -X -Y -Z
  4770. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  4771. let faceData = data[faceIndex];
  4772. if (compression) {
  4773. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (<any>(this.getCaps().s3tc))[compression], texture.width, texture.height, 0, <DataView>faceData);
  4774. } else {
  4775. if (needConversion) {
  4776. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  4777. }
  4778. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  4779. }
  4780. }
  4781. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  4782. if (isPot && texture.generateMipMaps && level === 0) {
  4783. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  4784. }
  4785. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  4786. // this.resetTextureCache();
  4787. texture.isReady = true;
  4788. }
  4789. /**
  4790. * Creates a new raw cube texture
  4791. * @param data defines the array of data to use to create each face
  4792. * @param size defines the size of the textures
  4793. * @param format defines the format of the data
  4794. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  4795. * @param generateMipMaps defines if the engine should generate the mip levels
  4796. * @param invertY defines if data must be stored with Y axis inverted
  4797. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  4798. * @param compression defines the compression used (null by default)
  4799. * @returns the cube texture as an InternalTexture
  4800. */
  4801. public createRawCubeTexture(data: Nullable<ArrayBufferView[]>, size: number, format: number, type: number,
  4802. generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  4803. compression: Nullable<string> = null): InternalTexture {
  4804. var gl = this._gl;
  4805. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBERAW);
  4806. texture.isCube = true;
  4807. texture.format = format;
  4808. texture.type = type;
  4809. if (!this._doNotHandleContextLost) {
  4810. texture._bufferViewArray = data;
  4811. }
  4812. var textureType = this._getWebGLTextureType(type);
  4813. var internalFormat = this._getInternalFormat(format);
  4814. if (internalFormat === gl.RGB) {
  4815. internalFormat = gl.RGBA;
  4816. }
  4817. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  4818. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  4819. generateMipMaps = false;
  4820. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4821. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  4822. }
  4823. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  4824. generateMipMaps = false;
  4825. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4826. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  4827. }
  4828. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  4829. generateMipMaps = false;
  4830. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  4831. }
  4832. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  4833. generateMipMaps = false;
  4834. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  4835. }
  4836. var width = size;
  4837. var height = width;
  4838. texture.width = width;
  4839. texture.height = height;
  4840. // Double check on POT to generate Mips.
  4841. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  4842. if (!isPot) {
  4843. generateMipMaps = false;
  4844. }
  4845. // Upload data if needed. The texture won't be ready until then.
  4846. if (data) {
  4847. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  4848. }
  4849. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  4850. // Filters
  4851. if (data && generateMipMaps) {
  4852. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  4853. }
  4854. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  4855. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  4856. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  4857. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4858. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4859. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4860. texture.generateMipMaps = generateMipMaps;
  4861. return texture;
  4862. }
  4863. /**
  4864. * Creates a new raw cube texture from a specified url
  4865. * @param url defines the url where the data is located
  4866. * @param scene defines the current scene
  4867. * @param size defines the size of the textures
  4868. * @param format defines the format of the data
  4869. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  4870. * @param noMipmap defines if the engine should avoid generating the mip levels
  4871. * @param callback defines a callback used to extract texture data from loaded data
  4872. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  4873. * @param onLoad defines a callback called when texture is loaded
  4874. * @param onError defines a callback called if there is an error
  4875. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  4876. * @param invertY defines if data must be stored with Y axis inverted
  4877. * @returns the cube texture as an InternalTexture
  4878. */
  4879. public createRawCubeTextureFromUrl(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  4880. callback: (ArrayBuffer: ArrayBuffer) => Nullable<ArrayBufferView[]>,
  4881. mipmapGenerator: Nullable<((faces: ArrayBufferView[]) => ArrayBufferView[][])>,
  4882. onLoad: Nullable<() => void> = null,
  4883. onError: Nullable<(message?: string, exception?: any) => void> = null,
  4884. samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE,
  4885. invertY = false): InternalTexture {
  4886. var gl = this._gl;
  4887. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  4888. scene._addPendingData(texture);
  4889. texture.url = url;
  4890. this._internalTexturesCache.push(texture);
  4891. var onerror = (request?: XMLHttpRequest, exception?: any) => {
  4892. scene._removePendingData(texture);
  4893. if (onError && request) {
  4894. onError(request.status + " " + request.statusText, exception);
  4895. }
  4896. };
  4897. var internalCallback = (data: any) => {
  4898. var width = texture.width;
  4899. var faceDataArrays = callback(data);
  4900. if (!faceDataArrays) {
  4901. return;
  4902. }
  4903. if (mipmapGenerator) {
  4904. var textureType = this._getWebGLTextureType(type);
  4905. var internalFormat = this._getInternalFormat(format);
  4906. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  4907. var needConversion = false;
  4908. if (internalFormat === gl.RGB) {
  4909. internalFormat = gl.RGBA;
  4910. needConversion = true;
  4911. }
  4912. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4913. this._unpackFlipY(false);
  4914. var mipData = mipmapGenerator(faceDataArrays);
  4915. for (var level = 0; level < mipData.length; level++) {
  4916. var mipSize = width >> level;
  4917. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  4918. let mipFaceData = mipData[level][faceIndex];
  4919. if (needConversion) {
  4920. mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  4921. }
  4922. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  4923. }
  4924. }
  4925. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4926. }
  4927. else {
  4928. this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  4929. }
  4930. texture.isReady = true;
  4931. // this.resetTextureCache();
  4932. scene._removePendingData(texture);
  4933. if (onLoad) {
  4934. onLoad();
  4935. }
  4936. };
  4937. this._loadFile(url, data => {
  4938. internalCallback(data);
  4939. }, undefined, scene.database, true, onerror);
  4940. return texture;
  4941. };
  4942. /**
  4943. * Update a raw 3D texture
  4944. * @param texture defines the texture to update
  4945. * @param data defines the data to store
  4946. * @param format defines the data format
  4947. * @param invertY defines if data must be stored with Y axis inverted
  4948. * @param compression defines the used compression (can be null)
  4949. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  4950. */
  4951. public updateRawTexture3D(texture: InternalTexture, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, textureType = Engine.TEXTURETYPE_UNSIGNED_INT): void {
  4952. var internalType = this._getWebGLTextureType(textureType);
  4953. var internalFormat = this._getInternalFormat(format);
  4954. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  4955. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  4956. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  4957. if (!this._doNotHandleContextLost) {
  4958. texture._bufferView = data;
  4959. texture.format = format;
  4960. texture.invertY = invertY;
  4961. texture._compression = compression;
  4962. }
  4963. if (texture.width % 4 !== 0) {
  4964. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  4965. }
  4966. if (compression && data) {
  4967. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, texture.depth, 0, data);
  4968. } else {
  4969. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  4970. }
  4971. if (texture.generateMipMaps) {
  4972. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  4973. }
  4974. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  4975. // this.resetTextureCache();
  4976. texture.isReady = true;
  4977. }
  4978. /**
  4979. * Creates a new raw 3D texture
  4980. * @param data defines the data used to create the texture
  4981. * @param width defines the width of the texture
  4982. * @param height defines the height of the texture
  4983. * @param depth defines the depth of the texture
  4984. * @param format defines the format of the texture
  4985. * @param generateMipMaps defines if the engine must generate mip levels
  4986. * @param invertY defines if data must be stored with Y axis inverted
  4987. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  4988. * @param compression defines the compressed used (can be null)
  4989. * @param textureType defines the compressed used (can be null)
  4990. * @returns a new raw 3D texture (stored in an InternalTexture)
  4991. */
  4992. public createRawTexture3D(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null, textureType = Engine.TEXTURETYPE_UNSIGNED_INT): InternalTexture {
  4993. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW3D);
  4994. texture.baseWidth = width;
  4995. texture.baseHeight = height;
  4996. texture.baseDepth = depth;
  4997. texture.width = width;
  4998. texture.height = height;
  4999. texture.depth = depth;
  5000. texture.format = format;
  5001. texture.type = textureType;
  5002. texture.generateMipMaps = generateMipMaps;
  5003. texture.samplingMode = samplingMode;
  5004. texture.is3D = true;
  5005. if (!this._doNotHandleContextLost) {
  5006. texture._bufferView = data;
  5007. }
  5008. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  5009. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  5010. // Filters
  5011. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  5012. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5013. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5014. if (generateMipMaps) {
  5015. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  5016. }
  5017. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5018. this._internalTexturesCache.push(texture);
  5019. return texture;
  5020. }
  5021. private _prepareWebGLTextureContinuation(texture: InternalTexture, scene: Nullable<Scene>, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  5022. var gl = this._gl;
  5023. if (!gl) {
  5024. return;
  5025. }
  5026. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  5027. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5028. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5029. if (!noMipmap && !isCompressed) {
  5030. gl.generateMipmap(gl.TEXTURE_2D);
  5031. }
  5032. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  5033. // this.resetTextureCache();
  5034. if (scene) {
  5035. scene._removePendingData(texture);
  5036. }
  5037. texture.onLoadedObservable.notifyObservers(texture);
  5038. texture.onLoadedObservable.clear();
  5039. }
  5040. private _prepareWebGLTexture(texture: InternalTexture, scene: Nullable<Scene>, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  5041. processFunction: (width: number, height: number, continuationCallback: () => void) => boolean, samplingMode: number = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE): void {
  5042. var maxTextureSize = this.getCaps().maxTextureSize;
  5043. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  5044. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  5045. var gl = this._gl;
  5046. if (!gl) {
  5047. return;
  5048. }
  5049. if (!texture._webGLTexture) {
  5050. // this.resetTextureCache();
  5051. if (scene) {
  5052. scene._removePendingData(texture);
  5053. }
  5054. return;
  5055. }
  5056. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  5057. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  5058. texture.baseWidth = width;
  5059. texture.baseHeight = height;
  5060. texture.width = potWidth;
  5061. texture.height = potHeight;
  5062. texture.isReady = true;
  5063. if (processFunction(potWidth, potHeight, () => {
  5064. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  5065. })) {
  5066. // Returning as texture needs extra async steps
  5067. return;
  5068. }
  5069. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  5070. }
  5071. private _convertRGBtoRGBATextureData(rgbData: any, width: number, height: number, textureType: number): ArrayBufferView {
  5072. // Create new RGBA data container.
  5073. var rgbaData: any;
  5074. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  5075. rgbaData = new Float32Array(width * height * 4);
  5076. }
  5077. else {
  5078. rgbaData = new Uint32Array(width * height * 4);
  5079. }
  5080. // Convert each pixel.
  5081. for (let x = 0; x < width; x++) {
  5082. for (let y = 0; y < height; y++) {
  5083. let index = (y * width + x) * 3;
  5084. let newIndex = (y * width + x) * 4;
  5085. // Map Old Value to new value.
  5086. rgbaData[newIndex + 0] = rgbData[index + 0];
  5087. rgbaData[newIndex + 1] = rgbData[index + 1];
  5088. rgbaData[newIndex + 2] = rgbData[index + 2];
  5089. // Add fully opaque alpha channel.
  5090. rgbaData[newIndex + 3] = 1;
  5091. }
  5092. }
  5093. return rgbaData;
  5094. }
  5095. /** @hidden */
  5096. public _releaseFramebufferObjects(texture: InternalTexture): void {
  5097. var gl = this._gl;
  5098. if (texture._framebuffer) {
  5099. gl.deleteFramebuffer(texture._framebuffer);
  5100. texture._framebuffer = null;
  5101. }
  5102. if (texture._depthStencilBuffer) {
  5103. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  5104. texture._depthStencilBuffer = null;
  5105. }
  5106. if (texture._MSAAFramebuffer) {
  5107. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  5108. texture._MSAAFramebuffer = null;
  5109. }
  5110. if (texture._MSAARenderBuffer) {
  5111. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  5112. texture._MSAARenderBuffer = null;
  5113. }
  5114. }
  5115. /** @hidden */
  5116. public _releaseTexture(texture: InternalTexture): void {
  5117. var gl = this._gl;
  5118. this._releaseFramebufferObjects(texture);
  5119. gl.deleteTexture(texture._webGLTexture);
  5120. // Unbind channels
  5121. this.unbindAllTextures();
  5122. var index = this._internalTexturesCache.indexOf(texture);
  5123. if (index !== -1) {
  5124. this._internalTexturesCache.splice(index, 1);
  5125. }
  5126. // Integrated fixed lod samplers.
  5127. if (texture._lodTextureHigh) {
  5128. texture._lodTextureHigh.dispose();
  5129. }
  5130. if (texture._lodTextureMid) {
  5131. texture._lodTextureMid.dispose();
  5132. }
  5133. if (texture._lodTextureLow) {
  5134. texture._lodTextureLow.dispose();
  5135. }
  5136. // Set output texture of post process to null if the texture has been released/disposed
  5137. this.scenes.forEach((scene)=>{
  5138. scene.postProcesses.forEach((postProcess)=>{
  5139. if(postProcess._outputTexture == texture){
  5140. postProcess._outputTexture = null;
  5141. }
  5142. });
  5143. scene.cameras.forEach((camera)=>{
  5144. camera._postProcesses.forEach((postProcess)=>{
  5145. if(postProcess){
  5146. if(postProcess._outputTexture == texture){
  5147. postProcess._outputTexture = null;
  5148. }
  5149. }
  5150. });
  5151. });
  5152. })
  5153. }
  5154. private setProgram(program: WebGLProgram): void {
  5155. if (this._currentProgram !== program) {
  5156. this._gl.useProgram(program);
  5157. this._currentProgram = program;
  5158. }
  5159. }
  5160. private _boundUniforms: { [key: number]: WebGLUniformLocation } = {};
  5161. /**
  5162. * Binds an effect to the webGL context
  5163. * @param effect defines the effect to bind
  5164. */
  5165. public bindSamplers(effect: Effect): void {
  5166. this.setProgram(effect.getProgram());
  5167. var samplers = effect.getSamplers();
  5168. for (var index = 0; index < samplers.length; index++) {
  5169. var uniform = effect.getUniform(samplers[index]);
  5170. if (uniform) {
  5171. this._boundUniforms[index] = uniform;
  5172. }
  5173. }
  5174. this._currentEffect = null;
  5175. }
  5176. private _moveBoundTextureOnTop(internalTexture: InternalTexture): void {
  5177. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  5178. return;
  5179. }
  5180. // Remove
  5181. this._linkTrackers(internalTexture.previous, internalTexture.next);
  5182. // Bind last to it
  5183. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  5184. // Bind to dummy
  5185. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  5186. }
  5187. private _getCorrectTextureChannel(channel: number, internalTexture: Nullable<InternalTexture>): number {
  5188. if (!internalTexture) {
  5189. return -1;
  5190. }
  5191. internalTexture._initialSlot = channel;
  5192. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  5193. if (channel !== internalTexture._designatedSlot) {
  5194. this._textureCollisions.addCount(1, false);
  5195. }
  5196. } else {
  5197. if (channel !== internalTexture._designatedSlot) {
  5198. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  5199. return internalTexture._designatedSlot;
  5200. } else {
  5201. // No slot for this texture, let's pick a new one (if we find a free slot)
  5202. if (this._nextFreeTextureSlots.length) {
  5203. return this._nextFreeTextureSlots[0];
  5204. }
  5205. // We need to recycle the oldest bound texture, sorry.
  5206. this._textureCollisions.addCount(1, false);
  5207. return this._removeDesignatedSlot(<InternalTexture>this._firstBoundInternalTextureTracker.next);
  5208. }
  5209. }
  5210. }
  5211. return channel;
  5212. }
  5213. private _linkTrackers(previous: Nullable<IInternalTextureTracker>, next: Nullable<IInternalTextureTracker>) {
  5214. previous!.next = next;
  5215. next!.previous = previous;
  5216. }
  5217. private _removeDesignatedSlot(internalTexture: InternalTexture): number {
  5218. let currentSlot = internalTexture._designatedSlot;
  5219. if (currentSlot === -1) {
  5220. return -1;
  5221. }
  5222. internalTexture._designatedSlot = -1;
  5223. if (this.disableTextureBindingOptimization) {
  5224. return -1;
  5225. }
  5226. // Remove from bound list
  5227. this._linkTrackers(internalTexture.previous, internalTexture.next);
  5228. // Free the slot
  5229. this._boundTexturesCache[currentSlot] = null;
  5230. this._nextFreeTextureSlots.push(currentSlot);
  5231. return currentSlot;
  5232. }
  5233. private _activateCurrentTexture() {
  5234. if (this._currentTextureChannel !== this._activeChannel) {
  5235. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  5236. this._currentTextureChannel = this._activeChannel;
  5237. }
  5238. }
  5239. /** @hidden */
  5240. protected _bindTextureDirectly(target: number, texture: Nullable<InternalTexture>, forTextureDataUpdate = false, force = false): boolean {
  5241. var wasPreviouslyBound = false;
  5242. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  5243. this._activeChannel = texture._designatedSlot;
  5244. }
  5245. let currentTextureBound = this._boundTexturesCache[this._activeChannel];
  5246. let isTextureForRendering = texture && texture._initialSlot > -1;
  5247. if (currentTextureBound !== texture || force) {
  5248. if (currentTextureBound) {
  5249. this._removeDesignatedSlot(currentTextureBound);
  5250. }
  5251. this._activateCurrentTexture();
  5252. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  5253. this._boundTexturesCache[this._activeChannel] = texture;
  5254. if (texture) {
  5255. if (!this.disableTextureBindingOptimization) {
  5256. let slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  5257. if (slotIndex > -1) {
  5258. this._nextFreeTextureSlots.splice(slotIndex, 1);
  5259. }
  5260. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  5261. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  5262. }
  5263. texture._designatedSlot = this._activeChannel;
  5264. }
  5265. } else if (forTextureDataUpdate) {
  5266. wasPreviouslyBound = true;
  5267. this._activateCurrentTexture();
  5268. }
  5269. if (isTextureForRendering && !forTextureDataUpdate) {
  5270. this._bindSamplerUniformToChannel(texture!._initialSlot, this._activeChannel);
  5271. }
  5272. return wasPreviouslyBound;
  5273. }
  5274. /** @hidden */
  5275. public _bindTexture(channel: number, texture: Nullable<InternalTexture>): void {
  5276. if (channel < 0) {
  5277. return;
  5278. }
  5279. if (texture) {
  5280. channel = this._getCorrectTextureChannel(channel, texture);
  5281. }
  5282. this._activeChannel = channel;
  5283. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  5284. }
  5285. /**
  5286. * Sets a texture to the webGL context from a postprocess
  5287. * @param channel defines the channel to use
  5288. * @param postProcess defines the source postprocess
  5289. */
  5290. public setTextureFromPostProcess(channel: number, postProcess: Nullable<PostProcess>): void {
  5291. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  5292. }
  5293. /**
  5294. * Binds the output of the passed in post process to the texture channel specified
  5295. * @param channel The channel the texture should be bound to
  5296. * @param postProcess The post process which's output should be bound
  5297. */
  5298. public setTextureFromPostProcessOutput(channel: number, postProcess: Nullable<PostProcess>): void {
  5299. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  5300. }
  5301. /**
  5302. * Unbind all textures from the webGL context
  5303. */
  5304. public unbindAllTextures(): void {
  5305. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  5306. this._activeChannel = channel;
  5307. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  5308. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  5309. if (this.webGLVersion > 1) {
  5310. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5311. }
  5312. }
  5313. }
  5314. /**
  5315. * Sets a texture to the according uniform.
  5316. * @param channel The texture channel
  5317. * @param uniform The uniform to set
  5318. * @param texture The texture to apply
  5319. */
  5320. public setTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>): void {
  5321. if (channel < 0) {
  5322. return;
  5323. }
  5324. if (uniform) {
  5325. this._boundUniforms[channel] = uniform;
  5326. }
  5327. this._setTexture(channel, texture);
  5328. }
  5329. /**
  5330. * Sets a depth stencil texture from a render target to the according uniform.
  5331. * @param channel The texture channel
  5332. * @param uniform The uniform to set
  5333. * @param texture The render target texture containing the depth stencil texture to apply
  5334. */
  5335. public setDepthStencilTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<RenderTargetTexture>): void {
  5336. if (channel < 0) {
  5337. return;
  5338. }
  5339. if (uniform) {
  5340. this._boundUniforms[channel] = uniform;
  5341. }
  5342. if (!texture || !texture.depthStencilTexture) {
  5343. this._setTexture(channel, null);
  5344. }
  5345. else {
  5346. this._setTexture(channel, texture, false, true);
  5347. }
  5348. }
  5349. private _bindSamplerUniformToChannel(sourceSlot: number, destination: number) {
  5350. let uniform = this._boundUniforms[sourceSlot];
  5351. if (uniform._currentState === destination) {
  5352. return;
  5353. }
  5354. this._gl.uniform1i(uniform, destination);
  5355. uniform._currentState = destination;
  5356. }
  5357. private _getTextureWrapMode(mode: number): number {
  5358. switch(mode) {
  5359. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  5360. return this._gl.REPEAT;
  5361. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  5362. return this._gl.CLAMP_TO_EDGE;
  5363. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  5364. return this._gl.MIRRORED_REPEAT;
  5365. }
  5366. return this._gl.REPEAT;
  5367. }
  5368. private _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false, depthStencilTexture = false): boolean {
  5369. // Not ready?
  5370. if (!texture) {
  5371. if (this._boundTexturesCache[channel] != null) {
  5372. this._activeChannel = channel;
  5373. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  5374. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  5375. if (this.webGLVersion > 1) {
  5376. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5377. }
  5378. }
  5379. return false;
  5380. }
  5381. // Video
  5382. if ((<VideoTexture>texture).video) {
  5383. this._activeChannel = channel;
  5384. (<VideoTexture>texture).update();
  5385. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  5386. texture.delayLoad();
  5387. return false;
  5388. }
  5389. let internalTexture: InternalTexture;
  5390. if (depthStencilTexture) {
  5391. internalTexture = (<RenderTargetTexture>texture).depthStencilTexture!;
  5392. }
  5393. else if (texture.isReady()) {
  5394. internalTexture = <InternalTexture>texture.getInternalTexture();
  5395. }
  5396. else if (texture.isCube) {
  5397. internalTexture = this.emptyCubeTexture;
  5398. }
  5399. else if (texture.is3D) {
  5400. internalTexture = this.emptyTexture3D;
  5401. }
  5402. else {
  5403. internalTexture = this.emptyTexture;
  5404. }
  5405. if (!isPartOfTextureArray) {
  5406. channel = this._getCorrectTextureChannel(channel, internalTexture);
  5407. }
  5408. let needToBind = true;
  5409. if (this._boundTexturesCache[channel] === internalTexture) {
  5410. this._moveBoundTextureOnTop(internalTexture);
  5411. if (!isPartOfTextureArray) {
  5412. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  5413. }
  5414. needToBind = false;
  5415. }
  5416. this._activeChannel = channel;
  5417. if (internalTexture && internalTexture.is3D) {
  5418. if (needToBind) {
  5419. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  5420. }
  5421. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  5422. internalTexture._cachedWrapU = texture.wrapU;
  5423. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  5424. }
  5425. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  5426. internalTexture._cachedWrapV = texture.wrapV;
  5427. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  5428. }
  5429. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  5430. internalTexture._cachedWrapR = texture.wrapR;
  5431. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  5432. }
  5433. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  5434. }
  5435. else if (internalTexture && internalTexture.isCube) {
  5436. if (needToBind) {
  5437. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  5438. }
  5439. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5440. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5441. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5442. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5443. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  5444. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5445. }
  5446. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5447. } else {
  5448. if (needToBind) {
  5449. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  5450. }
  5451. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  5452. internalTexture._cachedWrapU = texture.wrapU;
  5453. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  5454. }
  5455. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  5456. internalTexture._cachedWrapV = texture.wrapV;
  5457. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  5458. }
  5459. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5460. }
  5461. return true;
  5462. }
  5463. /**
  5464. * Sets an array of texture to the webGL context
  5465. * @param channel defines the channel where the texture array must be set
  5466. * @param uniform defines the associated uniform location
  5467. * @param textures defines the array of textures to bind
  5468. */
  5469. public setTextureArray(channel: number, uniform: Nullable<WebGLUniformLocation>, textures: BaseTexture[]): void {
  5470. if (channel < 0 || !uniform) {
  5471. return;
  5472. }
  5473. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  5474. this._textureUnits = new Int32Array(textures.length);
  5475. }
  5476. for (let i = 0; i < textures.length; i++) {
  5477. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  5478. }
  5479. this._gl.uniform1iv(uniform, this._textureUnits);
  5480. for (var index = 0; index < textures.length; index++) {
  5481. this._setTexture(this._textureUnits[index], textures[index], true);
  5482. }
  5483. }
  5484. /** @hidden */
  5485. public _setAnisotropicLevel(target: number, texture: BaseTexture) {
  5486. var internalTexture = texture.getInternalTexture();
  5487. if (!internalTexture) {
  5488. return;
  5489. }
  5490. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5491. var value = texture.anisotropicFilteringLevel;
  5492. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  5493. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  5494. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  5495. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  5496. }
  5497. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  5498. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  5499. internalTexture._cachedAnisotropicFilteringLevel = value;
  5500. }
  5501. }
  5502. private _setTextureParameterFloat(target: number, parameter: number, value: number, texture: InternalTexture): void {
  5503. this._bindTextureDirectly(target, texture, true, true);
  5504. this._gl.texParameterf(target, parameter, value);
  5505. }
  5506. private _setTextureParameterInteger(target: number, parameter: number, value: number, texture?: InternalTexture) {
  5507. if (texture) {
  5508. this._bindTextureDirectly(target, texture, true, true);
  5509. }
  5510. this._gl.texParameteri(target, parameter, value);
  5511. }
  5512. /**
  5513. * Reads pixels from the current frame buffer. Please note that this function can be slow
  5514. * @param x defines the x coordinate of the rectangle where pixels must be read
  5515. * @param y defines the y coordinate of the rectangle where pixels must be read
  5516. * @param width defines the width of the rectangle where pixels must be read
  5517. * @param height defines the height of the rectangle where pixels must be read
  5518. * @returns a Uint8Array containing RGBA colors
  5519. */
  5520. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  5521. var data = new Uint8Array(height * width * 4);
  5522. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5523. return data;
  5524. }
  5525. /**
  5526. * Add an externaly attached data from its key.
  5527. * This method call will fail and return false, if such key already exists.
  5528. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  5529. * @param key the unique key that identifies the data
  5530. * @param data the data object to associate to the key for this Engine instance
  5531. * @return true if no such key were already present and the data was added successfully, false otherwise
  5532. */
  5533. public addExternalData<T>(key: string, data: T): boolean {
  5534. if (!this._externalData) {
  5535. this._externalData = new StringDictionary<Object>();
  5536. }
  5537. return this._externalData.add(key, data);
  5538. }
  5539. /**
  5540. * Get an externaly attached data from its key
  5541. * @param key the unique key that identifies the data
  5542. * @return the associated data, if present (can be null), or undefined if not present
  5543. */
  5544. public getExternalData<T>(key: string): T {
  5545. if (!this._externalData) {
  5546. this._externalData = new StringDictionary<Object>();
  5547. }
  5548. return <T>this._externalData.get(key);
  5549. }
  5550. /**
  5551. * Get an externaly attached data from its key, create it using a factory if it's not already present
  5552. * @param key the unique key that identifies the data
  5553. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  5554. * @return the associated data, can be null if the factory returned null.
  5555. */
  5556. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  5557. if (!this._externalData) {
  5558. this._externalData = new StringDictionary<Object>();
  5559. }
  5560. return <T>this._externalData.getOrAddWithFactory(key, factory);
  5561. }
  5562. /**
  5563. * Remove an externaly attached data from the Engine instance
  5564. * @param key the unique key that identifies the data
  5565. * @return true if the data was successfully removed, false if it doesn't exist
  5566. */
  5567. public removeExternalData(key: string): boolean {
  5568. if (!this._externalData) {
  5569. this._externalData = new StringDictionary<Object>();
  5570. }
  5571. return this._externalData.remove(key);
  5572. }
  5573. /**
  5574. * Unbind all vertex attributes from the webGL context
  5575. */
  5576. public unbindAllAttributes() {
  5577. if (this._mustWipeVertexAttributes) {
  5578. this._mustWipeVertexAttributes = false;
  5579. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  5580. this._gl.disableVertexAttribArray(i);
  5581. this._vertexAttribArraysEnabled[i] = false;
  5582. this._currentBufferPointers[i].active = false;
  5583. }
  5584. return;
  5585. }
  5586. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  5587. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  5588. continue;
  5589. }
  5590. this._gl.disableVertexAttribArray(i);
  5591. this._vertexAttribArraysEnabled[i] = false;
  5592. this._currentBufferPointers[i].active = false;
  5593. }
  5594. }
  5595. /**
  5596. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  5597. */
  5598. public releaseEffects() {
  5599. for (var name in this._compiledEffects) {
  5600. this._deleteProgram(this._compiledEffects[name]._program)
  5601. }
  5602. this._compiledEffects = {};
  5603. }
  5604. /**
  5605. * Dispose and release all associated resources
  5606. */
  5607. public dispose(): void {
  5608. this.hideLoadingUI();
  5609. this.stopRenderLoop();
  5610. // Release postProcesses
  5611. while (this.postProcesses.length) {
  5612. this.postProcesses[0].dispose();
  5613. }
  5614. // Empty texture
  5615. if (this._emptyTexture) {
  5616. this._releaseTexture(this._emptyTexture);
  5617. this._emptyTexture = null;
  5618. }
  5619. if (this._emptyCubeTexture) {
  5620. this._releaseTexture(this._emptyCubeTexture);
  5621. this._emptyCubeTexture = null;
  5622. }
  5623. // Rescale PP
  5624. if (this._rescalePostProcess) {
  5625. this._rescalePostProcess.dispose();
  5626. }
  5627. // Release scenes
  5628. while (this.scenes.length) {
  5629. this.scenes[0].dispose();
  5630. }
  5631. // Release audio engine
  5632. if (Engine.audioEngine) {
  5633. Engine.audioEngine.dispose();
  5634. }
  5635. // Release effects
  5636. this.releaseEffects();
  5637. // Unbind
  5638. this.unbindAllAttributes();
  5639. this._boundUniforms = [];
  5640. if (this._dummyFramebuffer) {
  5641. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  5642. }
  5643. //WebVR
  5644. this.disableVR();
  5645. // Events
  5646. if (Tools.IsWindowObjectExist()) {
  5647. window.removeEventListener("blur", this._onBlur);
  5648. window.removeEventListener("focus", this._onFocus);
  5649. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  5650. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  5651. if (this._renderingCanvas) {
  5652. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  5653. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  5654. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  5655. if (!this._doNotHandleContextLost) {
  5656. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  5657. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  5658. }
  5659. }
  5660. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5661. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5662. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5663. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5664. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5665. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5666. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5667. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5668. if (this._onVrDisplayConnect) {
  5669. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  5670. if (this._onVrDisplayDisconnect) {
  5671. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  5672. }
  5673. if (this._onVrDisplayPresentChange) {
  5674. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  5675. }
  5676. this._onVrDisplayConnect = null;
  5677. this._onVrDisplayDisconnect = null;
  5678. }
  5679. }
  5680. // Remove from Instances
  5681. var index = Engine.Instances.indexOf(this);
  5682. if (index >= 0) {
  5683. Engine.Instances.splice(index, 1);
  5684. }
  5685. this._workingCanvas = null;
  5686. this._workingContext = null;
  5687. this._currentBufferPointers = [];
  5688. this._renderingCanvas = null;
  5689. this._currentProgram = null;
  5690. this._bindedRenderFunction = null;
  5691. this.onResizeObservable.clear();
  5692. this.onCanvasBlurObservable.clear();
  5693. this.onCanvasFocusObservable.clear();
  5694. this.onCanvasPointerOutObservable.clear();
  5695. this.onBeginFrameObservable.clear();
  5696. this.onEndFrameObservable.clear();
  5697. Effect.ResetCache();
  5698. // Abort active requests
  5699. for (let request of this._activeRequests) {
  5700. request.abort();
  5701. }
  5702. }
  5703. // Loading screen
  5704. /**
  5705. * Display the loading screen
  5706. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5707. */
  5708. public displayLoadingUI(): void {
  5709. if (!Tools.IsWindowObjectExist()) {
  5710. return;
  5711. }
  5712. const loadingScreen = this.loadingScreen;
  5713. if (loadingScreen) {
  5714. loadingScreen.displayLoadingUI();
  5715. }
  5716. }
  5717. /**
  5718. * Hide the loading screen
  5719. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5720. */
  5721. public hideLoadingUI(): void {
  5722. if (!Tools.IsWindowObjectExist()) {
  5723. return;
  5724. }
  5725. const loadingScreen = this.loadingScreen;
  5726. if (loadingScreen) {
  5727. loadingScreen.hideLoadingUI();
  5728. }
  5729. }
  5730. /**
  5731. * Gets the current loading screen object
  5732. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5733. */
  5734. public get loadingScreen(): ILoadingScreen {
  5735. if (!this._loadingScreen && DefaultLoadingScreen && this._renderingCanvas)
  5736. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas)
  5737. return this._loadingScreen;
  5738. }
  5739. /**
  5740. * Sets the current loading screen object
  5741. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5742. */
  5743. public set loadingScreen(loadingScreen: ILoadingScreen) {
  5744. this._loadingScreen = loadingScreen;
  5745. }
  5746. /**
  5747. * Sets the current loading screen text
  5748. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5749. */
  5750. public set loadingUIText(text: string) {
  5751. this.loadingScreen.loadingUIText = text;
  5752. }
  5753. /**
  5754. * Sets the current loading screen background color
  5755. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5756. */
  5757. public set loadingUIBackgroundColor(color: string) {
  5758. this.loadingScreen.loadingUIBackgroundColor = color;
  5759. }
  5760. /**
  5761. * Attach a new callback raised when context lost event is fired
  5762. * @param callback defines the callback to call
  5763. */
  5764. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  5765. if (this._renderingCanvas) {
  5766. this._renderingCanvas.addEventListener("webglcontextlost", <any>callback, false);
  5767. }
  5768. }
  5769. /**
  5770. * Attach a new callback raised when context restored event is fired
  5771. * @param callback defines the callback to call
  5772. */
  5773. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  5774. if (this._renderingCanvas) {
  5775. this._renderingCanvas.addEventListener("webglcontextrestored", <any>callback, false);
  5776. }
  5777. }
  5778. /**
  5779. * Gets the source code of the vertex shader associated with a specific webGL program
  5780. * @param program defines the program to use
  5781. * @returns a string containing the source code of the vertex shader associated with the program
  5782. */
  5783. public getVertexShaderSource(program: WebGLProgram): Nullable<string> {
  5784. var shaders = this._gl.getAttachedShaders(program);
  5785. if (!shaders) {
  5786. return null;
  5787. }
  5788. return this._gl.getShaderSource(shaders[0]);
  5789. }
  5790. /**
  5791. * Gets the source code of the fragment shader associated with a specific webGL program
  5792. * @param program defines the program to use
  5793. * @returns a string containing the source code of the fragment shader associated with the program
  5794. */
  5795. public getFragmentShaderSource(program: WebGLProgram): Nullable<string> {
  5796. var shaders = this._gl.getAttachedShaders(program);
  5797. if (!shaders) {
  5798. return null;
  5799. }
  5800. return this._gl.getShaderSource(shaders[1]);
  5801. }
  5802. /**
  5803. * Get the current error code of the webGL context
  5804. * @returns the error code
  5805. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  5806. */
  5807. public getError(): number {
  5808. return this._gl.getError();
  5809. }
  5810. // FPS
  5811. /**
  5812. * Gets the current framerate
  5813. * @returns a number representing the framerate
  5814. */
  5815. public getFps(): number {
  5816. return this._fps;
  5817. }
  5818. /**
  5819. * Gets the time spent between current and previous frame
  5820. * @returns a number representing the delta time in ms
  5821. */
  5822. public getDeltaTime(): number {
  5823. return this._deltaTime;
  5824. }
  5825. private _measureFps(): void {
  5826. this._performanceMonitor.sampleFrame();
  5827. this._fps = this._performanceMonitor.averageFPS;
  5828. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  5829. }
  5830. /** @hidden */
  5831. public _readTexturePixels(texture: InternalTexture, width: number, height: number, faceIndex = -1, level = 0): ArrayBufferView {
  5832. let gl = this._gl;
  5833. if (!this._dummyFramebuffer) {
  5834. let dummy = gl.createFramebuffer();
  5835. if (!dummy) {
  5836. throw new Error("Unable to create dummy framebuffer");
  5837. }
  5838. this._dummyFramebuffer = dummy;
  5839. }
  5840. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  5841. if (faceIndex > -1) {
  5842. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  5843. } else {
  5844. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  5845. }
  5846. let readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  5847. let buffer: ArrayBufferView;
  5848. switch (readType) {
  5849. case gl.UNSIGNED_BYTE:
  5850. buffer = new Uint8Array(4 * width * height);
  5851. readType = gl.UNSIGNED_BYTE;
  5852. break;
  5853. default:
  5854. buffer = new Float32Array(4 * width * height);
  5855. readType = gl.FLOAT;
  5856. break;
  5857. }
  5858. gl.readPixels(0, 0, width, height, gl.RGBA, readType, <DataView>buffer);
  5859. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  5860. return buffer;
  5861. }
  5862. private _canRenderToFloatFramebuffer(): boolean {
  5863. if (this._webGLVersion > 1) {
  5864. return this._caps.colorBufferFloat;
  5865. }
  5866. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  5867. }
  5868. private _canRenderToHalfFloatFramebuffer(): boolean {
  5869. if (this._webGLVersion > 1) {
  5870. return this._caps.colorBufferFloat;
  5871. }
  5872. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  5873. }
  5874. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  5875. private _canRenderToFramebuffer(type: number): boolean {
  5876. let gl = this._gl;
  5877. //clear existing errors
  5878. while (gl.getError() !== gl.NO_ERROR) { }
  5879. let successful = true;
  5880. let texture = gl.createTexture();
  5881. gl.bindTexture(gl.TEXTURE_2D, texture);
  5882. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  5883. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5884. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5885. let fb = gl.createFramebuffer();
  5886. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  5887. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5888. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  5889. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  5890. successful = successful && (gl.getError() === gl.NO_ERROR);
  5891. //try render by clearing frame buffer's color buffer
  5892. if (successful) {
  5893. gl.clear(gl.COLOR_BUFFER_BIT);
  5894. successful = successful && (gl.getError() === gl.NO_ERROR);
  5895. }
  5896. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  5897. if (successful) {
  5898. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  5899. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5900. let readFormat = gl.RGBA;
  5901. let readType = gl.UNSIGNED_BYTE;
  5902. let buffer = new Uint8Array(4);
  5903. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  5904. successful = successful && (gl.getError() === gl.NO_ERROR);
  5905. }
  5906. //clean up
  5907. gl.deleteTexture(texture);
  5908. gl.deleteFramebuffer(fb);
  5909. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5910. //clear accumulated errors
  5911. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  5912. return successful;
  5913. }
  5914. /** @hidden */
  5915. public _getWebGLTextureType(type: number): number {
  5916. if (type === Engine.TEXTURETYPE_FLOAT) {
  5917. return this._gl.FLOAT;
  5918. }
  5919. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  5920. // Add Half Float Constant.
  5921. return this._gl.HALF_FLOAT_OES;
  5922. }
  5923. return this._gl.UNSIGNED_BYTE;
  5924. };
  5925. private _getInternalFormat(format: number): number {
  5926. var internalFormat = this._gl.RGBA;
  5927. switch (format) {
  5928. case Engine.TEXTUREFORMAT_ALPHA:
  5929. internalFormat = this._gl.ALPHA;
  5930. break;
  5931. case Engine.TEXTUREFORMAT_LUMINANCE:
  5932. internalFormat = this._gl.LUMINANCE;
  5933. break;
  5934. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  5935. internalFormat = this._gl.LUMINANCE_ALPHA;
  5936. break;
  5937. case Engine.TEXTUREFORMAT_RGB:
  5938. internalFormat = this._gl.RGB;
  5939. break;
  5940. case Engine.TEXTUREFORMAT_RGBA:
  5941. internalFormat = this._gl.RGBA;
  5942. break;
  5943. case Engine.TEXTUREFORMAT_R:
  5944. internalFormat = this._gl.RED;
  5945. break;
  5946. case Engine.TEXTUREFORMAT_RG:
  5947. internalFormat = this._gl.RG;
  5948. break;
  5949. }
  5950. return internalFormat;
  5951. }
  5952. /** @hidden */
  5953. public _getRGBABufferInternalSizedFormat(type: number, format?: number): number {
  5954. if (this._webGLVersion === 1) {
  5955. if (format !== undefined) {
  5956. switch(format) {
  5957. case Engine.TEXTUREFORMAT_LUMINANCE:
  5958. return this._gl.LUMINANCE;
  5959. case Engine.TEXTUREFORMAT_ALPHA:
  5960. return this._gl.ALPHA;
  5961. }
  5962. }
  5963. return this._gl.RGBA;
  5964. }
  5965. if (type === Engine.TEXTURETYPE_FLOAT) {
  5966. if (format !== undefined) {
  5967. switch(format) {
  5968. case Engine.TEXTUREFORMAT_R:
  5969. return this._gl.R32F;
  5970. case Engine.TEXTUREFORMAT_RG:
  5971. return this._gl.RG32F;
  5972. case Engine.TEXTUREFORMAT_RGB:
  5973. return this._gl.RGB32F;
  5974. }
  5975. }
  5976. return this._gl.RGBA32F;
  5977. }
  5978. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  5979. if (format) {
  5980. switch(format) {
  5981. case Engine.TEXTUREFORMAT_R:
  5982. return this._gl.R16F;
  5983. case Engine.TEXTUREFORMAT_RG:
  5984. return this._gl.RG16F;
  5985. case Engine.TEXTUREFORMAT_RGB:
  5986. return this._gl.RGB16F;
  5987. }
  5988. }
  5989. return this._gl.RGBA16F;
  5990. }
  5991. if (format !== undefined) {
  5992. switch(format) {
  5993. case Engine.TEXTUREFORMAT_LUMINANCE:
  5994. return this._gl.LUMINANCE;
  5995. case Engine.TEXTUREFORMAT_RGB:
  5996. return this._gl.RGB;
  5997. case Engine.TEXTUREFORMAT_R:
  5998. return this._gl.R8;
  5999. case Engine.TEXTUREFORMAT_RG:
  6000. return this._gl.RG8;
  6001. case Engine.TEXTUREFORMAT_ALPHA:
  6002. return this._gl.ALPHA;
  6003. }
  6004. }
  6005. return this._gl.RGBA;
  6006. };
  6007. /** @hidden */
  6008. public _getRGBAMultiSampleBufferFormat(type: number): number {
  6009. if (type === Engine.TEXTURETYPE_FLOAT) {
  6010. return this._gl.RGBA32F;
  6011. }
  6012. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6013. return this._gl.RGBA16F;
  6014. }
  6015. return this._gl.RGBA8;
  6016. };
  6017. /** @hidden */
  6018. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, database?: Database, useArrayBuffer?: boolean, onError?: (request?: XMLHttpRequest, exception?: any) => void): IFileRequest {
  6019. let request = Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  6020. this._activeRequests.push(request);
  6021. request.onCompleteObservable.add(request => {
  6022. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  6023. });
  6024. return request;
  6025. }
  6026. /** @hidden */
  6027. public _loadFileAsync(url: string, database?: Database, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  6028. return new Promise((resolve, reject) => {
  6029. this._loadFile(url, (data) => {
  6030. resolve(data);
  6031. }, undefined, database, useArrayBuffer, (request, exception) => {
  6032. reject(exception);
  6033. })
  6034. });
  6035. }
  6036. private _partialLoadFile(url: string, index: number, loadedFiles: (string | ArrayBuffer)[], scene: Nullable<Scene>, onfinish: (files: (string | ArrayBuffer)[]) => void, onErrorCallBack: Nullable<(message?: string, exception?: any) => void> = null): void {
  6037. var onload = (data: string | ArrayBuffer) => {
  6038. loadedFiles[index] = data;
  6039. (<any>loadedFiles)._internalCount++;
  6040. if ((<any>loadedFiles)._internalCount === 6) {
  6041. onfinish(loadedFiles);
  6042. }
  6043. };
  6044. const onerror = (request?: XMLHttpRequest, exception?: any) => {
  6045. if (onErrorCallBack && request) {
  6046. onErrorCallBack(request.status + " " + request.statusText, exception);
  6047. }
  6048. };
  6049. this._loadFile(url, onload, undefined, undefined, true, onerror);
  6050. }
  6051. private _cascadeLoadFiles(scene: Nullable<Scene>, onfinish: (images: (string | ArrayBuffer)[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null): void {
  6052. var loadedFiles: (string | ArrayBuffer)[] = [];
  6053. (<any>loadedFiles)._internalCount = 0;
  6054. for (let index = 0; index < 6; index++) {
  6055. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  6056. }
  6057. }
  6058. // Statics
  6059. /**
  6060. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  6061. * @returns true if the engine can be created
  6062. * @ignorenaming
  6063. */
  6064. public static isSupported(): boolean {
  6065. try {
  6066. var tempcanvas = document.createElement("canvas");
  6067. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6068. return gl != null && !!window.WebGLRenderingContext;
  6069. } catch (e) {
  6070. return false;
  6071. }
  6072. }
  6073. }
  6074. }