babylon.engine.ts 329 KB

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