engine.ts 266 KB

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