babylon.engine.ts 320 KB

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