babylon.engine.ts 328 KB

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