babylon.engine.ts 321 KB

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