babylon.engine.ts 322 KB

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