engine.ts 308 KB

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