babylon.engine.ts 264 KB

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