babylon.engine.ts 247 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907
  1. module BABYLON {
  2. var compileShader = (gl: WebGLRenderingContext, source: string, type: string, defines: Nullable<string>, shaderVersion: string): WebGLShader => {
  3. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  4. };
  5. var compileRawShader = (gl: WebGLRenderingContext, source: string, type: string): WebGLShader => {
  6. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7. gl.shaderSource(shader, source);
  8. gl.compileShader(shader);
  9. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10. let log = gl.getShaderInfoLog(shader);
  11. if (log) {
  12. throw new Error(log);
  13. }
  14. }
  15. if (!shader) {
  16. throw new Error("Something went wrong while compile the shader.");
  17. }
  18. return shader;
  19. };
  20. var getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
  21. var magFilter = gl.NEAREST;
  22. var minFilter = gl.NEAREST;
  23. switch (samplingMode) {
  24. case Texture.BILINEAR_SAMPLINGMODE:
  25. magFilter = gl.LINEAR;
  26. if (generateMipMaps) {
  27. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  28. } else {
  29. minFilter = gl.LINEAR;
  30. }
  31. break;
  32. case Texture.TRILINEAR_SAMPLINGMODE:
  33. magFilter = gl.LINEAR;
  34. if (generateMipMaps) {
  35. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  36. } else {
  37. minFilter = gl.LINEAR;
  38. }
  39. break;
  40. case Texture.NEAREST_SAMPLINGMODE:
  41. magFilter = gl.NEAREST;
  42. if (generateMipMaps) {
  43. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  44. } else {
  45. minFilter = gl.NEAREST;
  46. }
  47. break;
  48. case Texture.NEAREST_NEAREST_MIPNEAREST:
  49. magFilter = gl.NEAREST;
  50. if (generateMipMaps) {
  51. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  52. } else {
  53. minFilter = gl.NEAREST;
  54. }
  55. break;
  56. case Texture.NEAREST_LINEAR_MIPNEAREST:
  57. magFilter = gl.NEAREST;
  58. if (generateMipMaps) {
  59. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  60. } else {
  61. minFilter = gl.LINEAR;
  62. }
  63. break;
  64. case Texture.NEAREST_LINEAR_MIPLINEAR:
  65. magFilter = gl.NEAREST;
  66. if (generateMipMaps) {
  67. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  68. } else {
  69. minFilter = gl.LINEAR;
  70. }
  71. break;
  72. case Texture.NEAREST_LINEAR:
  73. magFilter = gl.NEAREST;
  74. minFilter = gl.LINEAR;
  75. break;
  76. case Texture.NEAREST_NEAREST:
  77. magFilter = gl.NEAREST;
  78. minFilter = gl.NEAREST;
  79. break;
  80. case Texture.LINEAR_NEAREST_MIPNEAREST:
  81. magFilter = gl.LINEAR;
  82. if (generateMipMaps) {
  83. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  84. } else {
  85. minFilter = gl.NEAREST;
  86. }
  87. break;
  88. case Texture.LINEAR_NEAREST_MIPLINEAR:
  89. magFilter = gl.LINEAR;
  90. if (generateMipMaps) {
  91. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  92. } else {
  93. minFilter = gl.NEAREST;
  94. }
  95. break;
  96. case Texture.LINEAR_LINEAR:
  97. magFilter = gl.LINEAR;
  98. minFilter = gl.LINEAR;
  99. break;
  100. case Texture.LINEAR_NEAREST:
  101. magFilter = gl.LINEAR;
  102. minFilter = gl.NEAREST;
  103. break;
  104. }
  105. return {
  106. min: minFilter,
  107. mag: magFilter
  108. }
  109. }
  110. var partialLoadImg = (url: string, index: number, loadedImages: HTMLImageElement[], scene: Nullable<Scene>,
  111. onfinish: (images: HTMLImageElement[]) => void, onErrorCallBack: Nullable<(message?: string, exception?: any) => void> = null) => {
  112. var img: HTMLImageElement;
  113. var onload = () => {
  114. loadedImages[index] = img;
  115. (<any>loadedImages)._internalCount++;
  116. if (scene) {
  117. scene._removePendingData(img);
  118. }
  119. if ((<any>loadedImages)._internalCount === 6) {
  120. onfinish(loadedImages);
  121. }
  122. };
  123. var onerror = (message?: string, exception?: any) => {
  124. if (scene) {
  125. scene._removePendingData(img);
  126. }
  127. if (onErrorCallBack) {
  128. onErrorCallBack(message, exception);
  129. }
  130. };
  131. img = Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  132. if (scene) {
  133. scene._addPendingData(img);
  134. }
  135. }
  136. var cascadeLoadImgs = (rootUrl: string, scene: Nullable<Scene>,
  137. onfinish: (images: HTMLImageElement[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null) => {
  138. var loadedImages: HTMLImageElement[] = [];
  139. (<any>loadedImages)._internalCount = 0;
  140. for (let index = 0; index < 6; index++) {
  141. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  142. }
  143. };
  144. class BufferPointer {
  145. public active: boolean;
  146. public index: number;
  147. public size: number;
  148. public type: number;
  149. public normalized: boolean;
  150. public stride: number;
  151. public offset: number;
  152. public buffer: WebGLBuffer;
  153. }
  154. export class InstancingAttributeInfo {
  155. /**
  156. * Index/offset of the attribute in the vertex shader
  157. */
  158. index: number;
  159. /**
  160. * size of the attribute, 1, 2, 3 or 4
  161. */
  162. attributeSize: number;
  163. /**
  164. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  165. * default is FLOAT
  166. */
  167. attribyteType: number;
  168. /**
  169. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  170. */
  171. normalized: boolean;
  172. /**
  173. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  174. */
  175. offset: number;
  176. /**
  177. * Name of the GLSL attribute, for debugging purpose only
  178. */
  179. attributeName: string;
  180. }
  181. /**
  182. * Define options used to create a render target texture
  183. */
  184. export class RenderTargetCreationOptions {
  185. generateMipMaps?: boolean;
  186. generateDepthBuffer?: boolean;
  187. generateStencilBuffer?: boolean;
  188. type?: number;
  189. samplingMode?: number;
  190. }
  191. /**
  192. * Regroup several parameters relative to the browser in use
  193. */
  194. export class EngineCapabilities {
  195. /** The maximum textures image */
  196. public maxTexturesImageUnits: number;
  197. public maxVertexTextureImageUnits: number;
  198. public maxCombinedTexturesImageUnits: number;
  199. /** The maximum texture size */
  200. public maxTextureSize: number;
  201. public maxCubemapTextureSize: number;
  202. public maxRenderTextureSize: number;
  203. public maxVertexAttribs: number;
  204. public maxVaryingVectors: number;
  205. public maxVertexUniformVectors: number;
  206. public maxFragmentUniformVectors: number;
  207. public standardDerivatives: boolean;
  208. public s3tc: Nullable<WEBGL_compressed_texture_s3tc>;
  209. public pvrtc: any; //WEBGL_compressed_texture_pvrtc;
  210. public etc1: any; //WEBGL_compressed_texture_etc1;
  211. public etc2: any; //WEBGL_compressed_texture_etc;
  212. public astc: any; //WEBGL_compressed_texture_astc;
  213. public textureFloat: boolean;
  214. public vertexArrayObject: boolean;
  215. public textureAnisotropicFilterExtension: Nullable<EXT_texture_filter_anisotropic>;
  216. public maxAnisotropy: number;
  217. public instancedArrays: boolean;
  218. public uintIndices: boolean;
  219. public highPrecisionShaderSupported: boolean;
  220. public fragmentDepthSupported: boolean;
  221. public textureFloatLinearFiltering: boolean;
  222. public textureFloatRender: boolean;
  223. public textureHalfFloat: boolean;
  224. public textureHalfFloatLinearFiltering: boolean;
  225. public textureHalfFloatRender: boolean;
  226. public textureLOD: boolean;
  227. public drawBuffersExtension: boolean;
  228. public depthTextureExtension: boolean;
  229. public colorBufferFloat: boolean;
  230. public timerQuery: EXT_disjoint_timer_query;
  231. public canUseTimestampForTimerQuery: boolean;
  232. }
  233. export interface EngineOptions extends WebGLContextAttributes {
  234. limitDeviceRatio?: number;
  235. autoEnableWebVR?: boolean;
  236. disableWebGL2Support?: boolean;
  237. audioEngine?: boolean;
  238. deterministicLockstep?: boolean;
  239. lockstepMaxSteps?: number;
  240. doNotHandleContextLost?: boolean;
  241. }
  242. export interface IDisplayChangedEventArgs {
  243. vrDisplay: Nullable<any>;
  244. vrSupported: boolean;
  245. }
  246. /**
  247. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  248. */
  249. export class Engine {
  250. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  251. public static ExceptionList = [
  252. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  253. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  254. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  255. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  256. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  257. ];
  258. public static Instances = new Array<Engine>();
  259. public static get LastCreatedEngine(): Nullable<Engine> {
  260. if (Engine.Instances.length === 0) {
  261. return null;
  262. }
  263. return Engine.Instances[Engine.Instances.length - 1];
  264. }
  265. public static get LastCreatedScene(): Nullable<Scene> {
  266. var lastCreatedEngine = Engine.LastCreatedEngine;
  267. if (!lastCreatedEngine) {
  268. return null;
  269. }
  270. if (lastCreatedEngine.scenes.length === 0) {
  271. return null;
  272. }
  273. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  274. }
  275. /**
  276. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  277. */
  278. public static MarkAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  279. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  280. var engine = Engine.Instances[engineIndex];
  281. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  282. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  283. }
  284. }
  285. }
  286. // Const statics
  287. private static _ALPHA_DISABLE = 0;
  288. private static _ALPHA_ADD = 1;
  289. private static _ALPHA_COMBINE = 2;
  290. private static _ALPHA_SUBTRACT = 3;
  291. private static _ALPHA_MULTIPLY = 4;
  292. private static _ALPHA_MAXIMIZED = 5;
  293. private static _ALPHA_ONEONE = 6;
  294. private static _ALPHA_PREMULTIPLIED = 7;
  295. private static _ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  296. private static _ALPHA_INTERPOLATE = 9;
  297. private static _ALPHA_SCREENMODE = 10;
  298. private static _DELAYLOADSTATE_NONE = 0;
  299. private static _DELAYLOADSTATE_LOADED = 1;
  300. private static _DELAYLOADSTATE_LOADING = 2;
  301. private static _DELAYLOADSTATE_NOTLOADED = 4;
  302. private static _TEXTUREFORMAT_ALPHA = 0;
  303. private static _TEXTUREFORMAT_LUMINANCE = 1;
  304. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  305. private static _TEXTUREFORMAT_RGB = 4;
  306. private static _TEXTUREFORMAT_RGBA = 5;
  307. private static _TEXTUREFORMAT_R32F = 6;
  308. private static _TEXTUREFORMAT_RG32F = 7;
  309. private static _TEXTUREFORMAT_RGB32F = 8;
  310. private static _TEXTUREFORMAT_RGBA32F = 9;
  311. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  312. private static _TEXTURETYPE_FLOAT = 1;
  313. private static _TEXTURETYPE_HALF_FLOAT = 2;
  314. // Depht or Stencil test Constants.
  315. private static _NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  316. private static _ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  317. private static _LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  318. private static _EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  319. private static _LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  320. private static _GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  321. private static _GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  322. private static _NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  323. public static get NEVER(): number {
  324. return Engine._NEVER;
  325. }
  326. public static get ALWAYS(): number {
  327. return Engine._ALWAYS;
  328. }
  329. public static get LESS(): number {
  330. return Engine._LESS;
  331. }
  332. public static get EQUAL(): number {
  333. return Engine._EQUAL;
  334. }
  335. public static get LEQUAL(): number {
  336. return Engine._LEQUAL;
  337. }
  338. public static get GREATER(): number {
  339. return Engine._GREATER;
  340. }
  341. public static get GEQUAL(): number {
  342. return Engine._GEQUAL;
  343. }
  344. public static get NOTEQUAL(): number {
  345. return Engine._NOTEQUAL;
  346. }
  347. // Stencil Actions Constants.
  348. private static _KEEP = 0x1E00;
  349. private static _REPLACE = 0x1E01;
  350. private static _INCR = 0x1E02;
  351. private static _DECR = 0x1E03;
  352. private static _INVERT = 0x150A;
  353. private static _INCR_WRAP = 0x8507;
  354. private static _DECR_WRAP = 0x8508;
  355. public static get KEEP(): number {
  356. return Engine._KEEP;
  357. }
  358. public static get REPLACE(): number {
  359. return Engine._REPLACE;
  360. }
  361. public static get INCR(): number {
  362. return Engine._INCR;
  363. }
  364. public static get DECR(): number {
  365. return Engine._DECR;
  366. }
  367. public static get INVERT(): number {
  368. return Engine._INVERT;
  369. }
  370. public static get INCR_WRAP(): number {
  371. return Engine._INCR_WRAP;
  372. }
  373. public static get DECR_WRAP(): number {
  374. return Engine._DECR_WRAP;
  375. }
  376. public static get ALPHA_DISABLE(): number {
  377. return Engine._ALPHA_DISABLE;
  378. }
  379. public static get ALPHA_ONEONE(): number {
  380. return Engine._ALPHA_ONEONE;
  381. }
  382. public static get ALPHA_ADD(): number {
  383. return Engine._ALPHA_ADD;
  384. }
  385. public static get ALPHA_COMBINE(): number {
  386. return Engine._ALPHA_COMBINE;
  387. }
  388. public static get ALPHA_SUBTRACT(): number {
  389. return Engine._ALPHA_SUBTRACT;
  390. }
  391. public static get ALPHA_MULTIPLY(): number {
  392. return Engine._ALPHA_MULTIPLY;
  393. }
  394. public static get ALPHA_MAXIMIZED(): number {
  395. return Engine._ALPHA_MAXIMIZED;
  396. }
  397. public static get ALPHA_PREMULTIPLIED(): number {
  398. return Engine._ALPHA_PREMULTIPLIED;
  399. }
  400. public static get ALPHA_PREMULTIPLIED_PORTERDUFF(): number {
  401. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  402. }
  403. public static get ALPHA_INTERPOLATE(): number {
  404. return Engine._ALPHA_INTERPOLATE;
  405. }
  406. public static get ALPHA_SCREENMODE(): number {
  407. return Engine._ALPHA_SCREENMODE;
  408. }
  409. public static get DELAYLOADSTATE_NONE(): number {
  410. return Engine._DELAYLOADSTATE_NONE;
  411. }
  412. public static get DELAYLOADSTATE_LOADED(): number {
  413. return Engine._DELAYLOADSTATE_LOADED;
  414. }
  415. public static get DELAYLOADSTATE_LOADING(): number {
  416. return Engine._DELAYLOADSTATE_LOADING;
  417. }
  418. public static get DELAYLOADSTATE_NOTLOADED(): number {
  419. return Engine._DELAYLOADSTATE_NOTLOADED;
  420. }
  421. public static get TEXTUREFORMAT_ALPHA(): number {
  422. return Engine._TEXTUREFORMAT_ALPHA;
  423. }
  424. public static get TEXTUREFORMAT_LUMINANCE(): number {
  425. return Engine._TEXTUREFORMAT_LUMINANCE;
  426. }
  427. /**
  428. * R32F
  429. */
  430. public static get TEXTUREFORMAT_R32F(): number {
  431. return Engine._TEXTUREFORMAT_R32F;
  432. }
  433. /**
  434. * RG32F
  435. */
  436. public static get TEXTUREFORMAT_RG32F(): number {
  437. return Engine._TEXTUREFORMAT_RG32F;
  438. }
  439. /**
  440. * RGB32F
  441. */
  442. public static get TEXTUREFORMAT_RGB32F(): number {
  443. return Engine._TEXTUREFORMAT_RGB32F;
  444. }
  445. /**
  446. * RGBA32F
  447. */
  448. public static get TEXTUREFORMAT_RGBA32F(): number {
  449. return Engine._TEXTUREFORMAT_RGBA32F;
  450. }
  451. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  452. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  453. }
  454. public static get TEXTUREFORMAT_RGB(): number {
  455. return Engine._TEXTUREFORMAT_RGB;
  456. }
  457. public static get TEXTUREFORMAT_RGBA(): number {
  458. return Engine._TEXTUREFORMAT_RGBA;
  459. }
  460. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  461. return Engine._TEXTURETYPE_UNSIGNED_INT;
  462. }
  463. public static get TEXTURETYPE_FLOAT(): number {
  464. return Engine._TEXTURETYPE_FLOAT;
  465. }
  466. public static get TEXTURETYPE_HALF_FLOAT(): number {
  467. return Engine._TEXTURETYPE_HALF_FLOAT;
  468. }
  469. // Texture rescaling mode
  470. private static _SCALEMODE_FLOOR = 1;
  471. private static _SCALEMODE_NEAREST = 2;
  472. private static _SCALEMODE_CEILING = 3;
  473. public static get SCALEMODE_FLOOR(): number {
  474. return Engine._SCALEMODE_FLOOR;
  475. }
  476. public static get SCALEMODE_NEAREST(): number {
  477. return Engine._SCALEMODE_NEAREST;
  478. }
  479. public static get SCALEMODE_CEILING(): number {
  480. return Engine._SCALEMODE_CEILING;
  481. }
  482. public static get Version(): string {
  483. return "3.2.0-alpha8";
  484. }
  485. // Updatable statics so stick with vars here
  486. public static CollisionsEpsilon = 0.001;
  487. public static CodeRepository = "src/";
  488. public static ShadersRepository = "src/Shaders/";
  489. // Public members
  490. public forcePOTTextures = false;
  491. public isFullscreen = false;
  492. public isPointerLock = false;
  493. public cullBackFaces = true;
  494. public renderEvenInBackground = true;
  495. public preventCacheWipeBetweenFrames = false;
  496. // To enable/disable IDB support and avoid XHR on .manifest
  497. public enableOfflineSupport = false;
  498. public scenes = new Array<Scene>();
  499. public postProcesses = new Array<PostProcess>();
  500. // Observables
  501. /**
  502. * Observable event triggered each time the rendering canvas is resized
  503. */
  504. public onResizeObservable = new Observable<Engine>();
  505. /**
  506. * Observable event triggered each time the canvas loses focus
  507. */
  508. public onCanvasBlurObservable = new Observable<Engine>();
  509. /**
  510. * Observable event triggered each time the canvas gains focus
  511. */
  512. public onCanvasFocusObservable = new Observable<Engine>();
  513. /**
  514. * Observable event triggered each time the canvas receives pointerout event
  515. */
  516. public onCanvasPointerOutObservable = new Observable<PointerEvent>();
  517. /**
  518. * Observable event triggered before each texture is initialized
  519. */
  520. public onBeforeTextureInitObservable = new Observable<Texture>();
  521. //WebVR
  522. private _vrDisplay: any = undefined;
  523. private _vrSupported: boolean = false;
  524. private _oldSize: Size;
  525. private _oldHardwareScaleFactor: number;
  526. private _vrExclusivePointerMode = false;
  527. private _webVRInitPromise: Promise<IDisplayChangedEventArgs>;
  528. public get isInVRExclusivePointerMode(): boolean {
  529. return this._vrExclusivePointerMode;
  530. }
  531. // Uniform buffers list
  532. public disableUniformBuffers = false;
  533. public _uniformBuffers = new Array<UniformBuffer>();
  534. public get supportsUniformBuffers(): boolean {
  535. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  536. }
  537. // Observables
  538. /**
  539. * Observable raised when the engine begins a new frame
  540. */
  541. public onBeginFrameObservable = new Observable<Engine>();
  542. /**
  543. * Observable raised when the engine ends the current frame
  544. */
  545. public onEndFrameObservable = new Observable<Engine>();
  546. /**
  547. * Observable raised when the engine is about to compile a shader
  548. */
  549. public onBeforeShaderCompilationObservable = new Observable<Engine>();
  550. /**
  551. * Observable raised when the engine has jsut compiled a shader
  552. */
  553. public onAfterShaderCompilationObservable = new Observable<Engine>();
  554. // Private Members
  555. private _gl: WebGLRenderingContext;
  556. private _renderingCanvas: Nullable<HTMLCanvasElement>;
  557. private _windowIsBackground = false;
  558. private _webGLVersion = 1.0;
  559. public get needPOTTextures(): boolean {
  560. return this._webGLVersion < 2 || this.forcePOTTextures;
  561. }
  562. private _badOS = false;
  563. public get badOS(): boolean {
  564. return this._badOS;
  565. }
  566. private _badDesktopOS = false;
  567. public get badDesktopOS(): boolean {
  568. return this._badDesktopOS;
  569. }
  570. /**
  571. * Gets or sets a value indicating if we want to disable texture binding optmization.
  572. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  573. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  574. */
  575. public disableTextureBindingOptimization = false;
  576. public static audioEngine: AudioEngine;
  577. // Focus
  578. private _onFocus: () => void;
  579. private _onBlur: () => void;
  580. private _onCanvasPointerOut: (event: PointerEvent) => void;
  581. private _onCanvasBlur: () => void;
  582. private _onCanvasFocus: () => void;
  583. private _onFullscreenChange: () => void;
  584. private _onPointerLockChange: () => void;
  585. private _onVRDisplayPointerRestricted: () => void;
  586. private _onVRDisplayPointerUnrestricted: () => void;
  587. // VRDisplay connection
  588. private _onVrDisplayConnect: Nullable<(display: any) => void>;
  589. private _onVrDisplayDisconnect: Nullable<() => void>;
  590. private _onVrDisplayPresentChange: Nullable<() => void>;
  591. public onVRDisplayChangedObservable = new Observable<IDisplayChangedEventArgs>();
  592. public onVRRequestPresentComplete = new Observable<boolean>();
  593. public onVRRequestPresentStart = new Observable<Engine>();
  594. private _hardwareScalingLevel: number;
  595. protected _caps: EngineCapabilities;
  596. private _pointerLockRequested: boolean;
  597. private _isStencilEnable: boolean;
  598. private _colorWrite = true;
  599. private _loadingScreen: ILoadingScreen;
  600. public _drawCalls = new PerfCounter();
  601. public _textureCollisions = new PerfCounter();
  602. private _glVersion: string;
  603. private _glRenderer: string;
  604. private _glVendor: string;
  605. private _videoTextureSupported: boolean;
  606. private _renderingQueueLaunched = false;
  607. private _activeRenderLoops = new Array<() => void>();
  608. // Deterministic lockstepMaxSteps
  609. private _deterministicLockstep: boolean = false;
  610. private _lockstepMaxSteps: number = 4;
  611. // Lost context
  612. public onContextLostObservable = new Observable<Engine>();
  613. public onContextRestoredObservable = new Observable<Engine>();
  614. private _onContextLost: (evt: Event) => void;
  615. private _onContextRestored: (evt: Event) => void;
  616. private _contextWasLost = false;
  617. private _doNotHandleContextLost = false;
  618. // FPS
  619. private _performanceMonitor = new PerformanceMonitor();
  620. private _fps = 60;
  621. private _deltaTime = 0;
  622. /**
  623. * Turn this value on if you want to pause FPS computation when in background
  624. */
  625. public disablePerformanceMonitorInBackground = false;
  626. public get performanceMonitor(): PerformanceMonitor {
  627. return this._performanceMonitor;
  628. }
  629. // States
  630. protected _depthCullingState = new _DepthCullingState();
  631. protected _stencilState = new _StencilState();
  632. protected _alphaState = new _AlphaState();
  633. protected _alphaMode = Engine.ALPHA_DISABLE;
  634. // Cache
  635. private _internalTexturesCache = new Array<InternalTexture>();
  636. protected _activeChannel = 0;
  637. private _currentTextureChannel = -1;
  638. protected _boundTexturesCache: { [key: string]: Nullable<InternalTexture> } = {};
  639. protected _currentEffect: Nullable<Effect>;
  640. protected _currentProgram: Nullable<WebGLProgram>;
  641. private _compiledEffects: { [key: string]: Effect } = {}
  642. private _vertexAttribArraysEnabled: boolean[] = [];
  643. protected _cachedViewport: Nullable<Viewport>;
  644. private _cachedVertexArrayObject: Nullable<WebGLVertexArrayObject>;
  645. protected _cachedVertexBuffers: any;
  646. protected _cachedIndexBuffer: Nullable<WebGLBuffer>;
  647. protected _cachedEffectForVertexBuffers: Nullable<Effect>;
  648. protected _currentRenderTarget: Nullable<InternalTexture>;
  649. private _uintIndicesCurrentlySet = false;
  650. private _currentBoundBuffer = new Array<Nullable<WebGLBuffer>>();
  651. protected _currentFramebuffer: Nullable<WebGLFramebuffer>;
  652. private _currentBufferPointers = new Array<BufferPointer>();
  653. private _currentInstanceLocations = new Array<number>();
  654. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  655. private _textureUnits: Int32Array;
  656. private _firstBoundInternalTextureTracker = new DummyInternalTextureTracker();
  657. private _lastBoundInternalTextureTracker = new DummyInternalTextureTracker();
  658. private _workingCanvas: Nullable<HTMLCanvasElement>;
  659. private _workingContext: Nullable<CanvasRenderingContext2D>;
  660. private _rescalePostProcess: PassPostProcess;
  661. private _dummyFramebuffer: WebGLFramebuffer;
  662. private _externalData: StringDictionary<Object>;
  663. private _bindedRenderFunction: any;
  664. private _vaoRecordInProgress = false;
  665. private _mustWipeVertexAttributes = false;
  666. private _emptyTexture: Nullable<InternalTexture>;
  667. private _emptyCubeTexture: Nullable<InternalTexture>;
  668. private _emptyTexture3D: Nullable<InternalTexture>;
  669. private _frameHandler: number;
  670. private _nextFreeTextureSlots = new Array<number>();
  671. private _maxSimultaneousTextures = 0;
  672. private _activeRequests = new Array<IFileRequest>();
  673. // Hardware supported Compressed Textures
  674. private _texturesSupported = new Array<string>();
  675. private _textureFormatInUse: Nullable<string>;
  676. public get texturesSupported(): Array<string> {
  677. return this._texturesSupported;
  678. }
  679. public get textureFormatInUse(): Nullable<string> {
  680. return this._textureFormatInUse;
  681. }
  682. public get currentViewport(): Nullable<Viewport> {
  683. return this._cachedViewport;
  684. }
  685. // Empty texture
  686. public get emptyTexture(): InternalTexture {
  687. if (!this._emptyTexture) {
  688. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Texture.NEAREST_SAMPLINGMODE);
  689. }
  690. return this._emptyTexture;
  691. }
  692. public get emptyTexture3D(): InternalTexture {
  693. if (!this._emptyTexture3D) {
  694. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Texture.NEAREST_SAMPLINGMODE);
  695. }
  696. return this._emptyTexture3D;
  697. }
  698. public get emptyCubeTexture(): InternalTexture {
  699. if (!this._emptyCubeTexture) {
  700. var faceData = new Uint8Array(4);
  701. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  702. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Texture.NEAREST_SAMPLINGMODE);
  703. }
  704. return this._emptyCubeTexture;
  705. }
  706. /**
  707. * @constructor
  708. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  709. * @param antialias defines enable antialiasing (default: false)
  710. * @param options defines further options to be sent to the getContext() function
  711. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  712. */
  713. constructor(canvasOrContext: Nullable<HTMLCanvasElement | WebGLRenderingContext>, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio: boolean = false) {
  714. // Register promises
  715. PromisePolyfill.Apply();
  716. let canvas: Nullable<HTMLCanvasElement> = null;
  717. Engine.Instances.push(this);
  718. if (!canvasOrContext) {
  719. return;
  720. }
  721. options = options || {};
  722. if ((<HTMLCanvasElement>canvasOrContext).getContext) {
  723. canvas = <HTMLCanvasElement>canvasOrContext;
  724. this._renderingCanvas = canvas;
  725. if (antialias != null) {
  726. options.antialias = antialias;
  727. }
  728. if (options.deterministicLockstep === undefined) {
  729. options.deterministicLockstep = false;
  730. }
  731. if (options.lockstepMaxSteps === undefined) {
  732. options.lockstepMaxSteps = 4;
  733. }
  734. if (options.preserveDrawingBuffer === undefined) {
  735. options.preserveDrawingBuffer = false;
  736. }
  737. if (options.audioEngine === undefined) {
  738. options.audioEngine = true;
  739. }
  740. if (options.stencil === undefined) {
  741. options.stencil = true;
  742. }
  743. this._deterministicLockstep = options.deterministicLockstep;
  744. this._lockstepMaxSteps = options.lockstepMaxSteps;
  745. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  746. // Exceptions
  747. if (navigator && navigator.userAgent) {
  748. let ua = navigator.userAgent;
  749. for (var exception of Engine.ExceptionList) {
  750. let key = exception.key;
  751. let targets = exception.targets;
  752. if (ua.indexOf(key) > -1) {
  753. if (exception.capture && exception.captureConstraint) {
  754. let capture = exception.capture;
  755. let constraint = exception.captureConstraint;
  756. let regex = new RegExp(capture);
  757. let matches = regex.exec(ua);
  758. if (matches && matches.length > 0) {
  759. let capturedValue = parseInt(matches[matches.length - 1]);
  760. if (capturedValue >= constraint) {
  761. continue;
  762. }
  763. }
  764. }
  765. for (var target of targets) {
  766. switch (target) {
  767. case "uniformBuffer":
  768. this.disableUniformBuffers = true;
  769. break;
  770. case "textureBindingOptimization":
  771. this.disableTextureBindingOptimization = true;
  772. break;
  773. }
  774. }
  775. break;
  776. }
  777. }
  778. }
  779. // GL
  780. if (!options.disableWebGL2Support) {
  781. try {
  782. this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  783. if (this._gl) {
  784. this._webGLVersion = 2.0;
  785. }
  786. } catch (e) {
  787. // Do nothing
  788. }
  789. }
  790. if (!this._gl) {
  791. if (!canvas) {
  792. throw new Error("The provided canvas is null or undefined.");
  793. }
  794. try {
  795. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  796. } catch (e) {
  797. throw new Error("WebGL not supported");
  798. }
  799. }
  800. if (!this._gl) {
  801. throw new Error("WebGL not supported");
  802. }
  803. this._onCanvasFocus = () => {
  804. this.onCanvasFocusObservable.notifyObservers(this);
  805. }
  806. this._onCanvasBlur = () => {
  807. this.onCanvasBlurObservable.notifyObservers(this);
  808. }
  809. canvas.addEventListener("focus", this._onCanvasFocus);
  810. canvas.addEventListener("blur", this._onCanvasBlur);
  811. this._onBlur = () => {
  812. if (this.disablePerformanceMonitorInBackground) {
  813. this._performanceMonitor.disable();
  814. }
  815. this._windowIsBackground = true;
  816. };
  817. this._onFocus = () => {
  818. if (this.disablePerformanceMonitorInBackground) {
  819. this._performanceMonitor.enable();
  820. }
  821. this._windowIsBackground = false;
  822. };
  823. this._onCanvasPointerOut = (ev) => {
  824. this.onCanvasPointerOutObservable.notifyObservers(ev);
  825. };
  826. window.addEventListener("blur", this._onBlur);
  827. window.addEventListener("focus", this._onFocus);
  828. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  829. // Context lost
  830. if (!this._doNotHandleContextLost) {
  831. this._onContextLost = (evt: Event) => {
  832. evt.preventDefault();
  833. this._contextWasLost = true;
  834. Tools.Warn("WebGL context lost.");
  835. this.onContextLostObservable.notifyObservers(this);
  836. };
  837. this._onContextRestored = (evt: Event) => {
  838. // Adding a timeout to avoid race condition at browser level
  839. setTimeout(() => {
  840. // Rebuild gl context
  841. this._initGLContext();
  842. // Rebuild effects
  843. this._rebuildEffects();
  844. // Rebuild textures
  845. this._rebuildInternalTextures();
  846. // Rebuild buffers
  847. this._rebuildBuffers();
  848. // Cache
  849. this.wipeCaches(true);
  850. Tools.Warn("WebGL context successfully restored.");
  851. this.onContextRestoredObservable.notifyObservers(this);
  852. this._contextWasLost = false;
  853. }, 0);
  854. };
  855. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  856. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  857. }
  858. } else {
  859. this._gl = <WebGLRenderingContext>canvasOrContext;
  860. this._renderingCanvas = this._gl.canvas
  861. if (this._gl.renderbufferStorageMultisample) {
  862. this._webGLVersion = 2.0;
  863. }
  864. options.stencil = this._gl.getContextAttributes().stencil;
  865. }
  866. // Viewport
  867. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  868. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  869. this.resize();
  870. this._isStencilEnable = options.stencil ? true : false;
  871. this._initGLContext();
  872. if (canvas) {
  873. // Fullscreen
  874. this._onFullscreenChange = () => {
  875. if (document.fullscreen !== undefined) {
  876. this.isFullscreen = document.fullscreen;
  877. } else if (document.mozFullScreen !== undefined) {
  878. this.isFullscreen = document.mozFullScreen;
  879. } else if (document.webkitIsFullScreen !== undefined) {
  880. this.isFullscreen = document.webkitIsFullScreen;
  881. } else if (document.msIsFullScreen !== undefined) {
  882. this.isFullscreen = document.msIsFullScreen;
  883. }
  884. // Pointer lock
  885. if (this.isFullscreen && this._pointerLockRequested && canvas) {
  886. canvas.requestPointerLock = canvas.requestPointerLock ||
  887. canvas.msRequestPointerLock ||
  888. canvas.mozRequestPointerLock ||
  889. canvas.webkitRequestPointerLock;
  890. if (canvas.requestPointerLock) {
  891. canvas.requestPointerLock();
  892. }
  893. }
  894. };
  895. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  896. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  897. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  898. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  899. // Pointer lock
  900. this._onPointerLockChange = () => {
  901. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  902. document.webkitPointerLockElement === canvas ||
  903. document.msPointerLockElement === canvas ||
  904. document.pointerLockElement === canvas
  905. );
  906. };
  907. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  908. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  909. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  910. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  911. this._onVRDisplayPointerRestricted = () => {
  912. if (canvas) {
  913. canvas.requestPointerLock();
  914. }
  915. }
  916. this._onVRDisplayPointerUnrestricted = () => {
  917. document.exitPointerLock();
  918. }
  919. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  920. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  921. }
  922. if (options.audioEngine && AudioEngine && !Engine.audioEngine) {
  923. Engine.audioEngine = new AudioEngine();
  924. }
  925. // Prepare buffer pointers
  926. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  927. this._currentBufferPointers[i] = new BufferPointer();
  928. }
  929. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  930. // Load WebVR Devices
  931. if (options.autoEnableWebVR) {
  932. this.initWebVR();
  933. }
  934. // Detect if we are running on a faulty buggy OS.
  935. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  936. // Detect if we are running on a faulty buggy desktop OS.
  937. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  938. Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  939. this.enableOfflineSupport = (Database !== undefined);
  940. }
  941. private _rebuildInternalTextures(): void {
  942. let currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  943. for (var internalTexture of currentState) {
  944. internalTexture._rebuild();
  945. }
  946. }
  947. private _rebuildEffects(): void {
  948. for (var key in this._compiledEffects) {
  949. let effect = <Effect>this._compiledEffects[key];
  950. effect._prepareEffect();
  951. }
  952. Effect.ResetCache();
  953. }
  954. private _rebuildBuffers(): void {
  955. // Index / Vertex
  956. for (var scene of this.scenes) {
  957. scene.resetCachedMaterial();
  958. scene._rebuildGeometries();
  959. scene._rebuildTextures();
  960. }
  961. // Uniforms
  962. for (var uniformBuffer of this._uniformBuffers) {
  963. uniformBuffer._rebuild();
  964. }
  965. }
  966. private _initGLContext(): void {
  967. // Caps
  968. this._caps = new EngineCapabilities();
  969. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  970. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  971. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  972. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  973. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  974. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  975. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  976. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  977. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  978. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  979. // Infos
  980. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  981. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  982. if (rendererInfo != null) {
  983. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  984. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  985. }
  986. if (!this._glVendor) {
  987. this._glVendor = "Unknown vendor";
  988. }
  989. if (!this._glRenderer) {
  990. this._glRenderer = "Unknown renderer";
  991. }
  992. // Constants
  993. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  994. if (this._gl.RGBA16F !== 0x881A) {
  995. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  996. }
  997. if (this._gl.RGBA32F !== 0x8814) {
  998. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  999. }
  1000. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  1001. this._gl.DEPTH24_STENCIL8 = 35056;
  1002. }
  1003. // Extensions
  1004. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  1005. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  1006. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  1007. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  1008. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  1009. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  1010. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  1011. 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');
  1012. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  1013. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  1014. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  1015. this._caps.highPrecisionShaderSupported = true;
  1016. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  1017. if (this._caps.timerQuery) {
  1018. if (this._webGLVersion === 1) {
  1019. this._gl.getQuery = (<any>this._caps.timerQuery).getQueryEXT.bind(this._caps.timerQuery);
  1020. }
  1021. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  1022. }
  1023. // Checks if some of the format renders first to allow the use of webgl inspector.
  1024. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  1025. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  1026. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  1027. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  1028. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  1029. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  1030. if (this._webGLVersion > 1) {
  1031. this._gl.HALF_FLOAT_OES = 0x140B;
  1032. }
  1033. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  1034. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  1035. // Draw buffers
  1036. if (this._webGLVersion > 1) {
  1037. this._caps.drawBuffersExtension = true;
  1038. } else {
  1039. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  1040. if (drawBuffersExtension !== null) {
  1041. this._caps.drawBuffersExtension = true;
  1042. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  1043. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  1044. for (var i = 0; i < 16; i++) {
  1045. (<any>this._gl)["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  1046. }
  1047. } else {
  1048. this._caps.drawBuffersExtension = false;
  1049. }
  1050. }
  1051. // Depth Texture
  1052. if (this._webGLVersion > 1) {
  1053. this._caps.depthTextureExtension = true;
  1054. } else {
  1055. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  1056. if (depthTextureExtension != null) {
  1057. this._caps.depthTextureExtension = true;
  1058. }
  1059. }
  1060. // Vertex array object
  1061. if (this._webGLVersion > 1) {
  1062. this._caps.vertexArrayObject = true;
  1063. } else {
  1064. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  1065. if (vertexArrayObjectExtension != null) {
  1066. this._caps.vertexArrayObject = true;
  1067. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  1068. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  1069. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  1070. } else {
  1071. this._caps.vertexArrayObject = false;
  1072. }
  1073. }
  1074. // Instances count
  1075. if (this._webGLVersion > 1) {
  1076. this._caps.instancedArrays = true;
  1077. } else {
  1078. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  1079. if (instanceExtension != null) {
  1080. this._caps.instancedArrays = true;
  1081. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  1082. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  1083. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  1084. } else {
  1085. this._caps.instancedArrays = false;
  1086. }
  1087. }
  1088. // Intelligently add supported compressed formats in order to check for.
  1089. // Check for ASTC support first as it is most powerful and to be very cross platform.
  1090. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  1091. // Likely no hardware which supports both PVR & DXT, so order matters little.
  1092. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  1093. if (this._caps.astc) this.texturesSupported.push('-astc.ktx');
  1094. if (this._caps.s3tc) this.texturesSupported.push('-dxt.ktx');
  1095. if (this._caps.pvrtc) this.texturesSupported.push('-pvrtc.ktx');
  1096. if (this._caps.etc2) this.texturesSupported.push('-etc2.ktx');
  1097. if (this._caps.etc1) this.texturesSupported.push('-etc1.ktx');
  1098. if (this._gl.getShaderPrecisionFormat) {
  1099. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  1100. if (highp) {
  1101. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  1102. }
  1103. }
  1104. // Depth buffer
  1105. this.setDepthBuffer(true);
  1106. this.setDepthFunctionToLessOrEqual();
  1107. this.setDepthWrite(true);
  1108. // Texture maps
  1109. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  1110. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1111. this._nextFreeTextureSlots.push(slot);
  1112. }
  1113. }
  1114. public get webGLVersion(): number {
  1115. return this._webGLVersion;
  1116. }
  1117. /**
  1118. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  1119. */
  1120. public get isStencilEnable(): boolean {
  1121. return this._isStencilEnable;
  1122. }
  1123. private _prepareWorkingCanvas(): void {
  1124. if (this._workingCanvas) {
  1125. return;
  1126. }
  1127. this._workingCanvas = document.createElement("canvas");
  1128. let context = this._workingCanvas.getContext("2d");
  1129. if (context) {
  1130. this._workingContext = context;
  1131. }
  1132. }
  1133. public resetTextureCache() {
  1134. for (var key in this._boundTexturesCache) {
  1135. let boundTexture = this._boundTexturesCache[key];
  1136. if (boundTexture) {
  1137. this._removeDesignatedSlot(boundTexture);
  1138. }
  1139. this._boundTexturesCache[key] = null;
  1140. }
  1141. if (!this.disableTextureBindingOptimization) {
  1142. this._nextFreeTextureSlots = [];
  1143. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1144. this._nextFreeTextureSlots.push(slot);
  1145. }
  1146. }
  1147. this._currentTextureChannel = -1;
  1148. }
  1149. public isDeterministicLockStep(): boolean {
  1150. return this._deterministicLockstep;
  1151. }
  1152. public getLockstepMaxSteps(): number {
  1153. return this._lockstepMaxSteps;
  1154. }
  1155. public getGlInfo() {
  1156. return {
  1157. vendor: this._glVendor,
  1158. renderer: this._glRenderer,
  1159. version: this._glVersion
  1160. }
  1161. }
  1162. public getAspectRatio(camera: Camera, useScreen = false): number {
  1163. var viewport = camera.viewport;
  1164. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  1165. }
  1166. public getRenderWidth(useScreen = false): number {
  1167. if (!useScreen && this._currentRenderTarget) {
  1168. return this._currentRenderTarget.width;
  1169. }
  1170. return this._gl.drawingBufferWidth;
  1171. }
  1172. public getRenderHeight(useScreen = false): number {
  1173. if (!useScreen && this._currentRenderTarget) {
  1174. return this._currentRenderTarget.height;
  1175. }
  1176. return this._gl.drawingBufferHeight;
  1177. }
  1178. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  1179. return this._renderingCanvas;
  1180. }
  1181. public getRenderingCanvasClientRect(): Nullable<ClientRect> {
  1182. if (!this._renderingCanvas) {
  1183. return null;
  1184. }
  1185. return this._renderingCanvas.getBoundingClientRect();
  1186. }
  1187. public setHardwareScalingLevel(level: number): void {
  1188. this._hardwareScalingLevel = level;
  1189. this.resize();
  1190. }
  1191. public getHardwareScalingLevel(): number {
  1192. return this._hardwareScalingLevel;
  1193. }
  1194. public getLoadedTexturesCache(): InternalTexture[] {
  1195. return this._internalTexturesCache;
  1196. }
  1197. public getCaps(): EngineCapabilities {
  1198. return this._caps;
  1199. }
  1200. /** The number of draw calls submitted last frame */
  1201. public get drawCalls(): number {
  1202. Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  1203. return 0;
  1204. }
  1205. public get drawCallsPerfCounter(): Nullable<PerfCounter> {
  1206. Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  1207. return null;
  1208. }
  1209. public getDepthFunction(): Nullable<number> {
  1210. return this._depthCullingState.depthFunc;
  1211. }
  1212. public setDepthFunction(depthFunc: number) {
  1213. this._depthCullingState.depthFunc = depthFunc;
  1214. }
  1215. public setDepthFunctionToGreater(): void {
  1216. this._depthCullingState.depthFunc = this._gl.GREATER;
  1217. }
  1218. public setDepthFunctionToGreaterOrEqual(): void {
  1219. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  1220. }
  1221. public setDepthFunctionToLess(): void {
  1222. this._depthCullingState.depthFunc = this._gl.LESS;
  1223. }
  1224. public setDepthFunctionToLessOrEqual(): void {
  1225. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  1226. }
  1227. public getStencilBuffer(): boolean {
  1228. return this._stencilState.stencilTest;
  1229. }
  1230. public setStencilBuffer(enable: boolean): void {
  1231. this._stencilState.stencilTest = enable;
  1232. }
  1233. public getStencilMask(): number {
  1234. return this._stencilState.stencilMask;
  1235. }
  1236. public setStencilMask(mask: number): void {
  1237. this._stencilState.stencilMask = mask;
  1238. }
  1239. public getStencilFunction(): number {
  1240. return this._stencilState.stencilFunc;
  1241. }
  1242. public getStencilFunctionReference(): number {
  1243. return this._stencilState.stencilFuncRef;
  1244. }
  1245. public getStencilFunctionMask(): number {
  1246. return this._stencilState.stencilFuncMask;
  1247. }
  1248. public setStencilFunction(stencilFunc: number) {
  1249. this._stencilState.stencilFunc = stencilFunc;
  1250. }
  1251. public setStencilFunctionReference(reference: number) {
  1252. this._stencilState.stencilFuncRef = reference;
  1253. }
  1254. public setStencilFunctionMask(mask: number) {
  1255. this._stencilState.stencilFuncMask = mask;
  1256. }
  1257. public getStencilOperationFail(): number {
  1258. return this._stencilState.stencilOpStencilFail;
  1259. }
  1260. public getStencilOperationDepthFail(): number {
  1261. return this._stencilState.stencilOpDepthFail;
  1262. }
  1263. public getStencilOperationPass(): number {
  1264. return this._stencilState.stencilOpStencilDepthPass;
  1265. }
  1266. public setStencilOperationFail(operation: number): void {
  1267. this._stencilState.stencilOpStencilFail = operation;
  1268. }
  1269. public setStencilOperationDepthFail(operation: number): void {
  1270. this._stencilState.stencilOpDepthFail = operation;
  1271. }
  1272. public setStencilOperationPass(operation: number): void {
  1273. this._stencilState.stencilOpStencilDepthPass = operation;
  1274. }
  1275. public setDitheringState(value: boolean): void {
  1276. if (value) {
  1277. this._gl.enable(this._gl.DITHER);
  1278. } else {
  1279. this._gl.disable(this._gl.DITHER);
  1280. }
  1281. }
  1282. public setRasterizerState(value: boolean): void {
  1283. if (value) {
  1284. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  1285. } else {
  1286. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  1287. }
  1288. }
  1289. /**
  1290. * stop executing a render loop function and remove it from the execution array
  1291. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  1292. */
  1293. public stopRenderLoop(renderFunction?: () => void): void {
  1294. if (!renderFunction) {
  1295. this._activeRenderLoops = [];
  1296. return;
  1297. }
  1298. var index = this._activeRenderLoops.indexOf(renderFunction);
  1299. if (index >= 0) {
  1300. this._activeRenderLoops.splice(index, 1);
  1301. }
  1302. }
  1303. public _renderLoop(): void {
  1304. if (!this._contextWasLost) {
  1305. var shouldRender = true;
  1306. if (!this.renderEvenInBackground && this._windowIsBackground) {
  1307. shouldRender = false;
  1308. }
  1309. if (shouldRender) {
  1310. // Start new frame
  1311. this.beginFrame();
  1312. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  1313. var renderFunction = this._activeRenderLoops[index];
  1314. renderFunction();
  1315. }
  1316. // Present
  1317. this.endFrame();
  1318. }
  1319. }
  1320. if (this._activeRenderLoops.length > 0) {
  1321. // Register new frame
  1322. var requester = null;
  1323. if (this._vrDisplay && this._vrDisplay.isPresenting)
  1324. requester = this._vrDisplay;
  1325. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  1326. } else {
  1327. this._renderingQueueLaunched = false;
  1328. }
  1329. }
  1330. /**
  1331. * Register and execute a render loop. The engine can have more than one render function.
  1332. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  1333. * @example
  1334. * engine.runRenderLoop(function () {
  1335. * scene.render()
  1336. * })
  1337. */
  1338. public runRenderLoop(renderFunction: () => void): void {
  1339. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  1340. return;
  1341. }
  1342. this._activeRenderLoops.push(renderFunction);
  1343. if (!this._renderingQueueLaunched) {
  1344. this._renderingQueueLaunched = true;
  1345. this._bindedRenderFunction = this._renderLoop.bind(this);
  1346. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1347. }
  1348. }
  1349. /**
  1350. * Toggle full screen mode.
  1351. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  1352. * @param {any} options - an options object to be sent to the requestFullscreen function
  1353. */
  1354. public switchFullscreen(requestPointerLock: boolean): void {
  1355. if (this.isFullscreen) {
  1356. Tools.ExitFullscreen();
  1357. } else {
  1358. this._pointerLockRequested = requestPointerLock;
  1359. if (this._renderingCanvas) {
  1360. Tools.RequestFullscreen(this._renderingCanvas);
  1361. }
  1362. }
  1363. }
  1364. public clear(color: Nullable<Color4>, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  1365. this.applyStates();
  1366. var mode = 0;
  1367. if (backBuffer && color) {
  1368. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  1369. mode |= this._gl.COLOR_BUFFER_BIT;
  1370. }
  1371. if (depth) {
  1372. this._gl.clearDepth(1.0);
  1373. mode |= this._gl.DEPTH_BUFFER_BIT;
  1374. }
  1375. if (stencil) {
  1376. this._gl.clearStencil(0);
  1377. mode |= this._gl.STENCIL_BUFFER_BIT;
  1378. }
  1379. this._gl.clear(mode);
  1380. }
  1381. public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
  1382. let gl = this._gl;
  1383. // Save state
  1384. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  1385. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  1386. // Change state
  1387. gl.enable(gl.SCISSOR_TEST);
  1388. gl.scissor(x, y, width, height);
  1389. // Clear
  1390. this.clear(clearColor, true, true, true);
  1391. // Restore state
  1392. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  1393. if (curScissor === true) {
  1394. gl.enable(gl.SCISSOR_TEST);
  1395. } else {
  1396. gl.disable(gl.SCISSOR_TEST);
  1397. }
  1398. }
  1399. /**
  1400. * Set the WebGL's viewport
  1401. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  1402. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  1403. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  1404. */
  1405. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  1406. var width = requiredWidth || this.getRenderWidth();
  1407. var height = requiredHeight || this.getRenderHeight();
  1408. var x = viewport.x || 0;
  1409. var y = viewport.y || 0;
  1410. this._cachedViewport = viewport;
  1411. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  1412. }
  1413. /**
  1414. * Directly set the WebGL Viewport
  1415. * The x, y, width & height are directly passed to the WebGL call
  1416. * @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.
  1417. */
  1418. public setDirectViewport(x: number, y: number, width: number, height: number): Nullable<Viewport> {
  1419. let currentViewport = this._cachedViewport;
  1420. this._cachedViewport = null;
  1421. this._gl.viewport(x, y, width, height);
  1422. return currentViewport;
  1423. }
  1424. public beginFrame(): void {
  1425. this.onBeginFrameObservable.notifyObservers(this);
  1426. this._measureFps();
  1427. }
  1428. public endFrame(): void {
  1429. //force a flush in case we are using a bad OS.
  1430. if (this._badOS) {
  1431. this.flushFramebuffer();
  1432. }
  1433. //submit frame to the vr device, if enabled
  1434. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1435. // TODO: We should only submit the frame if we read frameData successfully.
  1436. this._vrDisplay.submitFrame();
  1437. }
  1438. this.onEndFrameObservable.notifyObservers(this);
  1439. }
  1440. /**
  1441. * resize the view according to the canvas' size.
  1442. * @example
  1443. * window.addEventListener("resize", function () {
  1444. * engine.resize();
  1445. * });
  1446. */
  1447. public resize(): void {
  1448. // We're not resizing the size of the canvas while in VR mode & presenting
  1449. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  1450. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  1451. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  1452. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  1453. }
  1454. }
  1455. /**
  1456. * force a specific size of the canvas
  1457. * @param {number} width - the new canvas' width
  1458. * @param {number} height - the new canvas' height
  1459. */
  1460. public setSize(width: number, height: number): void {
  1461. if (!this._renderingCanvas) {
  1462. return;
  1463. }
  1464. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  1465. return;
  1466. }
  1467. this._renderingCanvas.width = width;
  1468. this._renderingCanvas.height = height;
  1469. for (var index = 0; index < this.scenes.length; index++) {
  1470. var scene = this.scenes[index];
  1471. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  1472. var cam = scene.cameras[camIndex];
  1473. cam._currentRenderId = 0;
  1474. }
  1475. }
  1476. if (this.onResizeObservable.hasObservers) {
  1477. this.onResizeObservable.notifyObservers(this);
  1478. }
  1479. }
  1480. // WebVR functions
  1481. public isVRDevicePresent(): boolean {
  1482. return !!this._vrDisplay;
  1483. }
  1484. public getVRDevice(): any {
  1485. return this._vrDisplay;
  1486. }
  1487. /**
  1488. * Initializes a webVR display and starts listening to display change events.
  1489. * The onVRDisplayChangedObservable will be notified upon these changes.
  1490. * @returns The onVRDisplayChangedObservable.
  1491. */
  1492. public initWebVR(): Observable<IDisplayChangedEventArgs> {
  1493. this.initWebVRAsync();
  1494. return this.onVRDisplayChangedObservable;
  1495. }
  1496. /**
  1497. * Initializes a webVR display and starts listening to display change events.
  1498. * The onVRDisplayChangedObservable will be notified upon these changes.
  1499. * @returns A promise containing a VRDisplay and if vr is supported.
  1500. */
  1501. public initWebVRAsync(): Promise<IDisplayChangedEventArgs> {
  1502. var notifyObservers = () => {
  1503. var eventArgs = {
  1504. vrDisplay: this._vrDisplay,
  1505. vrSupported: this._vrSupported
  1506. };
  1507. this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  1508. this._webVRInitPromise = new Promise((res)=>{res(eventArgs)});
  1509. }
  1510. if (!this._onVrDisplayConnect) {
  1511. this._onVrDisplayConnect = (event) => {
  1512. this._vrDisplay = event.display;
  1513. notifyObservers();
  1514. };
  1515. this._onVrDisplayDisconnect = () => {
  1516. this._vrDisplay.cancelAnimationFrame(this._frameHandler);
  1517. this._vrDisplay = undefined;
  1518. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1519. notifyObservers();
  1520. };
  1521. this._onVrDisplayPresentChange = () => {
  1522. this._vrExclusivePointerMode = this._vrDisplay && this._vrDisplay.isPresenting;
  1523. }
  1524. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  1525. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  1526. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  1527. }
  1528. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  1529. this._webVRInitPromise.then(notifyObservers);
  1530. return this._webVRInitPromise;
  1531. }
  1532. public enableVR() {
  1533. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  1534. var onResolved = () => {
  1535. this.onVRRequestPresentComplete.notifyObservers(true);
  1536. this._onVRFullScreenTriggered();
  1537. };
  1538. var onRejected = () => {
  1539. this.onVRRequestPresentComplete.notifyObservers(false);
  1540. };
  1541. this.onVRRequestPresentStart.notifyObservers(this);
  1542. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  1543. }
  1544. }
  1545. public disableVR() {
  1546. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1547. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  1548. }
  1549. }
  1550. private _onVRFullScreenTriggered = () => {
  1551. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1552. //get the old size before we change
  1553. this._oldSize = new Size(this.getRenderWidth(), this.getRenderHeight());
  1554. this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
  1555. //get the width and height, change the render size
  1556. var leftEye = this._vrDisplay.getEyeParameters('left');
  1557. this.setHardwareScalingLevel(1);
  1558. this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  1559. } else {
  1560. this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
  1561. this.setSize(this._oldSize.width, this._oldSize.height);
  1562. }
  1563. }
  1564. private _getVRDisplaysAsync():Promise<IDisplayChangedEventArgs> {
  1565. return new Promise((res, rej)=>{
  1566. if (navigator.getVRDisplays) {
  1567. navigator.getVRDisplays().then((devices: Array<any>)=>{
  1568. this._vrSupported = true;
  1569. // note that devices may actually be an empty array. This is fine;
  1570. // we expect this._vrDisplay to be undefined in this case.
  1571. this._vrDisplay = devices[0];
  1572. res({
  1573. vrDisplay: this._vrDisplay,
  1574. vrSupported: this._vrSupported
  1575. });
  1576. });
  1577. } else {
  1578. this._vrDisplay = undefined;
  1579. this._vrSupported = false;
  1580. res({
  1581. vrDisplay: this._vrDisplay,
  1582. vrSupported: this._vrSupported
  1583. });
  1584. }
  1585. });
  1586. }
  1587. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean): void {
  1588. if (this._currentRenderTarget) {
  1589. this.unBindFramebuffer(this._currentRenderTarget);
  1590. }
  1591. this._currentRenderTarget = texture;
  1592. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  1593. var gl = this._gl;
  1594. if (texture.isCube) {
  1595. if (faceIndex === undefined) {
  1596. faceIndex = 0;
  1597. }
  1598. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  1599. }
  1600. if (this._cachedViewport && !forceFullscreenViewport) {
  1601. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  1602. } else {
  1603. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  1604. }
  1605. this.wipeCaches();
  1606. }
  1607. private bindUnboundFramebuffer(framebuffer: Nullable<WebGLFramebuffer>) {
  1608. if (this._currentFramebuffer !== framebuffer) {
  1609. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  1610. this._currentFramebuffer = framebuffer;
  1611. }
  1612. }
  1613. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1614. this._currentRenderTarget = null;
  1615. // If MSAA, we need to bitblt back to main texture
  1616. var gl = this._gl;
  1617. if (texture._MSAAFramebuffer) {
  1618. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  1619. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  1620. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  1621. 0, 0, texture.width, texture.height,
  1622. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1623. }
  1624. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1625. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  1626. gl.generateMipmap(gl.TEXTURE_2D);
  1627. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1628. }
  1629. if (onBeforeUnbind) {
  1630. if (texture._MSAAFramebuffer) {
  1631. // Bind the correct framebuffer
  1632. this.bindUnboundFramebuffer(texture._framebuffer);
  1633. }
  1634. onBeforeUnbind();
  1635. }
  1636. this.bindUnboundFramebuffer(null);
  1637. }
  1638. public unBindMultiColorAttachmentFramebuffer(textures: InternalTexture[], disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1639. this._currentRenderTarget = null;
  1640. // If MSAA, we need to bitblt back to main texture
  1641. var gl = this._gl;
  1642. if (textures[0]._MSAAFramebuffer) {
  1643. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  1644. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  1645. var attachments = textures[0]._attachments;
  1646. if (!attachments) {
  1647. attachments = new Array(textures.length);
  1648. textures[0]._attachments = attachments;
  1649. }
  1650. for (var i = 0; i < textures.length; i++) {
  1651. var texture = textures[i];
  1652. for (var j = 0; j < attachments.length; j++) {
  1653. attachments[j] = gl.NONE;
  1654. }
  1655. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  1656. gl.readBuffer(attachments[i]);
  1657. gl.drawBuffers(attachments);
  1658. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  1659. 0, 0, texture.width, texture.height,
  1660. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1661. }
  1662. for (var i = 0; i < attachments.length; i++) {
  1663. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  1664. }
  1665. gl.drawBuffers(attachments);
  1666. }
  1667. for (var i = 0; i < textures.length; i++) {
  1668. var texture = textures[i];
  1669. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1670. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  1671. gl.generateMipmap(gl.TEXTURE_2D);
  1672. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1673. }
  1674. }
  1675. if (onBeforeUnbind) {
  1676. if (textures[0]._MSAAFramebuffer) {
  1677. // Bind the correct framebuffer
  1678. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  1679. }
  1680. onBeforeUnbind();
  1681. }
  1682. this.bindUnboundFramebuffer(null);
  1683. }
  1684. public generateMipMapsForCubemap(texture: InternalTexture) {
  1685. if (texture.generateMipMaps) {
  1686. var gl = this._gl;
  1687. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  1688. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1689. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1690. }
  1691. }
  1692. public flushFramebuffer(): void {
  1693. this._gl.flush();
  1694. }
  1695. public restoreDefaultFramebuffer(): void {
  1696. if (this._currentRenderTarget) {
  1697. this.unBindFramebuffer(this._currentRenderTarget);
  1698. } else {
  1699. this.bindUnboundFramebuffer(null);
  1700. }
  1701. if (this._cachedViewport) {
  1702. this.setViewport(this._cachedViewport);
  1703. }
  1704. this.wipeCaches();
  1705. }
  1706. // UBOs
  1707. public createUniformBuffer(elements: FloatArray): WebGLBuffer {
  1708. var ubo = this._gl.createBuffer();
  1709. if (!ubo) {
  1710. throw new Error("Unable to create uniform buffer");
  1711. }
  1712. this.bindUniformBuffer(ubo);
  1713. if (elements instanceof Float32Array) {
  1714. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.STATIC_DRAW);
  1715. } else {
  1716. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.STATIC_DRAW);
  1717. }
  1718. this.bindUniformBuffer(null);
  1719. ubo.references = 1;
  1720. return ubo;
  1721. }
  1722. public createDynamicUniformBuffer(elements: FloatArray): WebGLBuffer {
  1723. var ubo = this._gl.createBuffer();
  1724. if (!ubo) {
  1725. throw new Error("Unable to create dynamic uniform buffer");
  1726. }
  1727. this.bindUniformBuffer(ubo);
  1728. if (elements instanceof Float32Array) {
  1729. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.DYNAMIC_DRAW);
  1730. } else {
  1731. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.DYNAMIC_DRAW);
  1732. }
  1733. this.bindUniformBuffer(null);
  1734. ubo.references = 1;
  1735. return ubo;
  1736. }
  1737. public updateUniformBuffer(uniformBuffer: WebGLBuffer, elements: FloatArray, offset?: number, count?: number): void {
  1738. this.bindUniformBuffer(uniformBuffer);
  1739. if (offset === undefined) {
  1740. offset = 0;
  1741. }
  1742. if (count === undefined) {
  1743. if (elements instanceof Float32Array) {
  1744. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, <Float32Array>elements);
  1745. } else {
  1746. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(<number[]>elements));
  1747. }
  1748. } else {
  1749. if (elements instanceof Float32Array) {
  1750. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, <Float32Array>elements.subarray(offset, offset + count));
  1751. } else {
  1752. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(<number[]>elements).subarray(offset, offset + count));
  1753. }
  1754. }
  1755. this.bindUniformBuffer(null);
  1756. }
  1757. // VBOs
  1758. private _resetVertexBufferBinding(): void {
  1759. this.bindArrayBuffer(null);
  1760. this._cachedVertexBuffers = null;
  1761. }
  1762. public createVertexBuffer(vertices: FloatArray): WebGLBuffer {
  1763. var vbo = this._gl.createBuffer();
  1764. if (!vbo) {
  1765. throw new Error("Unable to create vertex buffer");
  1766. }
  1767. this.bindArrayBuffer(vbo);
  1768. if (vertices instanceof Float32Array) {
  1769. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.STATIC_DRAW);
  1770. } else {
  1771. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.STATIC_DRAW);
  1772. }
  1773. this._resetVertexBufferBinding();
  1774. vbo.references = 1;
  1775. return vbo;
  1776. }
  1777. public createDynamicVertexBuffer(vertices: FloatArray): WebGLBuffer {
  1778. var vbo = this._gl.createBuffer();
  1779. if (!vbo) {
  1780. throw new Error("Unable to create dynamic vertex buffer");
  1781. }
  1782. this.bindArrayBuffer(vbo);
  1783. if (vertices instanceof Float32Array) {
  1784. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.DYNAMIC_DRAW);
  1785. } else {
  1786. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.DYNAMIC_DRAW);
  1787. }
  1788. this._resetVertexBufferBinding();
  1789. vbo.references = 1;
  1790. return vbo;
  1791. }
  1792. public updateDynamicIndexBuffer(indexBuffer: WebGLBuffer, indices: IndicesArray, offset: number = 0): void {
  1793. // Force cache update
  1794. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  1795. this.bindIndexBuffer(indexBuffer);
  1796. var arrayBuffer;
  1797. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  1798. arrayBuffer = indices;
  1799. } else {
  1800. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  1801. }
  1802. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  1803. this._resetIndexBufferBinding();
  1804. }
  1805. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: FloatArray, offset?: number, count?: number): void {
  1806. this.bindArrayBuffer(vertexBuffer);
  1807. if (offset === undefined) {
  1808. offset = 0;
  1809. }
  1810. if (count === undefined) {
  1811. if (vertices instanceof Float32Array) {
  1812. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, <Float32Array>vertices);
  1813. } else {
  1814. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(<number[]>vertices));
  1815. }
  1816. } else {
  1817. if (vertices instanceof Float32Array) {
  1818. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <Float32Array>vertices.subarray(offset, offset + count));
  1819. } else {
  1820. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(<number[]>vertices).subarray(offset, offset + count));
  1821. }
  1822. }
  1823. this._resetVertexBufferBinding();
  1824. }
  1825. private _resetIndexBufferBinding(): void {
  1826. this.bindIndexBuffer(null);
  1827. this._cachedIndexBuffer = null;
  1828. }
  1829. public createIndexBuffer(indices: IndicesArray, updatable?: boolean): WebGLBuffer {
  1830. var vbo = this._gl.createBuffer();
  1831. if (!vbo) {
  1832. throw new Error("Unable to create index buffer");
  1833. }
  1834. this.bindIndexBuffer(vbo);
  1835. // Check for 32 bits indices
  1836. var arrayBuffer;
  1837. var need32Bits = false;
  1838. if (indices instanceof Uint16Array) {
  1839. arrayBuffer = indices;
  1840. } else {
  1841. //check 32 bit support
  1842. if (this._caps.uintIndices) {
  1843. if (indices instanceof Uint32Array) {
  1844. arrayBuffer = indices;
  1845. need32Bits = true;
  1846. } else {
  1847. //number[] or Int32Array, check if 32 bit is necessary
  1848. for (var index = 0; index < indices.length; index++) {
  1849. if (indices[index] > 65535) {
  1850. need32Bits = true;
  1851. break;
  1852. }
  1853. }
  1854. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  1855. }
  1856. } else {
  1857. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  1858. arrayBuffer = new Uint16Array(indices);
  1859. }
  1860. }
  1861. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  1862. this._resetIndexBufferBinding();
  1863. vbo.references = 1;
  1864. vbo.is32Bits = need32Bits;
  1865. return vbo;
  1866. }
  1867. public bindArrayBuffer(buffer: Nullable<WebGLBuffer>): void {
  1868. if (!this._vaoRecordInProgress) {
  1869. this._unbindVertexArrayObject();
  1870. }
  1871. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  1872. }
  1873. public bindUniformBuffer(buffer: Nullable<WebGLBuffer>): void {
  1874. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  1875. }
  1876. public bindUniformBufferBase(buffer: WebGLBuffer, location: number): void {
  1877. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  1878. }
  1879. public bindUniformBlock(shaderProgram: WebGLProgram, blockName: string, index: number): void {
  1880. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  1881. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  1882. };
  1883. private bindIndexBuffer(buffer: Nullable<WebGLBuffer>): void {
  1884. if (!this._vaoRecordInProgress) {
  1885. this._unbindVertexArrayObject();
  1886. }
  1887. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  1888. }
  1889. private bindBuffer(buffer: Nullable<WebGLBuffer>, target: number): void {
  1890. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  1891. this._gl.bindBuffer(target, buffer);
  1892. this._currentBoundBuffer[target] = buffer;
  1893. }
  1894. }
  1895. public updateArrayBuffer(data: Float32Array): void {
  1896. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1897. }
  1898. private vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  1899. var pointer = this._currentBufferPointers[indx];
  1900. var changed = false;
  1901. if (!pointer.active) {
  1902. changed = true;
  1903. pointer.active = true;
  1904. pointer.index = indx;
  1905. pointer.size = size;
  1906. pointer.type = type;
  1907. pointer.normalized = normalized;
  1908. pointer.stride = stride;
  1909. pointer.offset = offset;
  1910. pointer.buffer = buffer;
  1911. } else {
  1912. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  1913. if (pointer.size !== size) { pointer.size = size; changed = true; }
  1914. if (pointer.type !== type) { pointer.type = type; changed = true; }
  1915. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  1916. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  1917. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  1918. }
  1919. if (changed || this._vaoRecordInProgress) {
  1920. this.bindArrayBuffer(buffer);
  1921. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  1922. }
  1923. }
  1924. private _bindIndexBufferWithCache(indexBuffer: Nullable<WebGLBuffer>): void {
  1925. if (indexBuffer == null) {
  1926. return;
  1927. }
  1928. if (this._cachedIndexBuffer !== indexBuffer) {
  1929. this._cachedIndexBuffer = indexBuffer;
  1930. this.bindIndexBuffer(indexBuffer);
  1931. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  1932. }
  1933. }
  1934. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, effect: Effect): void {
  1935. var attributes = effect.getAttributesNames();
  1936. if (!this._vaoRecordInProgress) {
  1937. this._unbindVertexArrayObject();
  1938. }
  1939. this.unbindAllAttributes();
  1940. for (var index = 0; index < attributes.length; index++) {
  1941. var order = effect.getAttributeLocation(index);
  1942. if (order >= 0) {
  1943. var vertexBuffer = vertexBuffers[attributes[index]];
  1944. if (!vertexBuffer) {
  1945. continue;
  1946. }
  1947. this._gl.enableVertexAttribArray(order);
  1948. if (!this._vaoRecordInProgress) {
  1949. this._vertexAttribArraysEnabled[order] = true;
  1950. }
  1951. var buffer = vertexBuffer.getBuffer();
  1952. if (buffer) {
  1953. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  1954. if (vertexBuffer.getIsInstanced()) {
  1955. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  1956. if (!this._vaoRecordInProgress) {
  1957. this._currentInstanceLocations.push(order);
  1958. this._currentInstanceBuffers.push(buffer);
  1959. }
  1960. }
  1961. }
  1962. }
  1963. }
  1964. }
  1965. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): WebGLVertexArrayObject {
  1966. var vao = this._gl.createVertexArray();
  1967. this._vaoRecordInProgress = true;
  1968. this._gl.bindVertexArray(vao);
  1969. this._mustWipeVertexAttributes = true;
  1970. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1971. this.bindIndexBuffer(indexBuffer);
  1972. this._vaoRecordInProgress = false;
  1973. this._gl.bindVertexArray(null);
  1974. return vao;
  1975. }
  1976. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: Nullable<WebGLBuffer>): void {
  1977. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  1978. this._cachedVertexArrayObject = vertexArrayObject;
  1979. this._gl.bindVertexArray(vertexArrayObject);
  1980. this._cachedVertexBuffers = null;
  1981. this._cachedIndexBuffer = null;
  1982. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  1983. this._mustWipeVertexAttributes = true;
  1984. }
  1985. }
  1986. public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  1987. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  1988. this._cachedVertexBuffers = vertexBuffer;
  1989. this._cachedEffectForVertexBuffers = effect;
  1990. let attributesCount = effect.getAttributesCount();
  1991. this._unbindVertexArrayObject();
  1992. this.unbindAllAttributes();
  1993. var offset = 0;
  1994. for (var index = 0; index < attributesCount; index++) {
  1995. if (index < vertexDeclaration.length) {
  1996. var order = effect.getAttributeLocation(index);
  1997. if (order >= 0) {
  1998. this._gl.enableVertexAttribArray(order);
  1999. this._vertexAttribArraysEnabled[order] = true;
  2000. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2001. }
  2002. offset += vertexDeclaration[index] * 4;
  2003. }
  2004. }
  2005. }
  2006. this._bindIndexBufferWithCache(indexBuffer);
  2007. }
  2008. private _unbindVertexArrayObject(): void {
  2009. if (!this._cachedVertexArrayObject) {
  2010. return;
  2011. }
  2012. this._cachedVertexArrayObject = null;
  2013. this._gl.bindVertexArray(null);
  2014. }
  2015. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): void {
  2016. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2017. this._cachedVertexBuffers = vertexBuffers;
  2018. this._cachedEffectForVertexBuffers = effect;
  2019. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  2020. }
  2021. this._bindIndexBufferWithCache(indexBuffer);
  2022. }
  2023. public unbindInstanceAttributes() {
  2024. var boundBuffer;
  2025. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  2026. var instancesBuffer = this._currentInstanceBuffers[i];
  2027. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  2028. boundBuffer = instancesBuffer;
  2029. this.bindArrayBuffer(instancesBuffer);
  2030. }
  2031. var offsetLocation = this._currentInstanceLocations[i];
  2032. this._gl.vertexAttribDivisor(offsetLocation, 0);
  2033. }
  2034. this._currentInstanceBuffers.length = 0;
  2035. this._currentInstanceLocations.length = 0;
  2036. }
  2037. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  2038. this._gl.deleteVertexArray(vao);
  2039. }
  2040. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  2041. buffer.references--;
  2042. if (buffer.references === 0) {
  2043. this._gl.deleteBuffer(buffer);
  2044. return true;
  2045. }
  2046. return false;
  2047. }
  2048. public createInstancesBuffer(capacity: number): WebGLBuffer {
  2049. var buffer = this._gl.createBuffer();
  2050. if (!buffer) {
  2051. throw new Error("Unable to create instance buffer");
  2052. }
  2053. buffer.capacity = capacity;
  2054. this.bindArrayBuffer(buffer);
  2055. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2056. return buffer;
  2057. }
  2058. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  2059. this._gl.deleteBuffer(buffer);
  2060. }
  2061. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  2062. this.bindArrayBuffer(instancesBuffer);
  2063. if (data) {
  2064. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2065. }
  2066. if ((<any>offsetLocations[0]).index !== undefined) {
  2067. let stride = 0;
  2068. for (let i = 0; i < offsetLocations.length; i++) {
  2069. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2070. stride += ai.attributeSize * 4;
  2071. }
  2072. for (let i = 0; i < offsetLocations.length; i++) {
  2073. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2074. if (!this._vertexAttribArraysEnabled[ai.index]) {
  2075. this._gl.enableVertexAttribArray(ai.index);
  2076. this._vertexAttribArraysEnabled[ai.index] = true;
  2077. }
  2078. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  2079. this._gl.vertexAttribDivisor(ai.index, 1);
  2080. this._currentInstanceLocations.push(ai.index);
  2081. this._currentInstanceBuffers.push(instancesBuffer);
  2082. }
  2083. } else {
  2084. for (let index = 0; index < 4; index++) {
  2085. let offsetLocation = <number>offsetLocations[index];
  2086. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  2087. this._gl.enableVertexAttribArray(offsetLocation);
  2088. this._vertexAttribArraysEnabled[offsetLocation] = true;
  2089. }
  2090. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2091. this._gl.vertexAttribDivisor(offsetLocation, 1);
  2092. this._currentInstanceLocations.push(offsetLocation);
  2093. this._currentInstanceBuffers.push(instancesBuffer);
  2094. }
  2095. }
  2096. }
  2097. public applyStates() {
  2098. this._depthCullingState.apply(this._gl);
  2099. this._stencilState.apply(this._gl);
  2100. this._alphaState.apply(this._gl);
  2101. }
  2102. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  2103. this.drawElementsType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  2104. }
  2105. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2106. this.drawArraysType(Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  2107. }
  2108. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2109. this.drawArraysType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  2110. }
  2111. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount?: number): void {
  2112. // Apply states
  2113. this.applyStates();
  2114. this._drawCalls.addCount(1, false);
  2115. // Render
  2116. const drawMode = this.DrawMode(fillMode);
  2117. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  2118. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  2119. if (instancesCount) {
  2120. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  2121. } else {
  2122. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  2123. }
  2124. }
  2125. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2126. // Apply states
  2127. this.applyStates();
  2128. this._drawCalls.addCount(1, false);
  2129. const drawMode = this.DrawMode(fillMode);
  2130. if (instancesCount) {
  2131. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  2132. } else {
  2133. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  2134. }
  2135. }
  2136. private DrawMode(fillMode: number): number {
  2137. switch (fillMode) {
  2138. // Triangle views
  2139. case Material.TriangleFillMode:
  2140. return this._gl.TRIANGLES;
  2141. case Material.PointFillMode:
  2142. return this._gl.POINTS;
  2143. case Material.WireFrameFillMode:
  2144. return this._gl.LINES;
  2145. // Draw modes
  2146. case Material.PointListDrawMode:
  2147. return this._gl.POINTS
  2148. case Material.LineListDrawMode:
  2149. return this._gl.LINES;
  2150. case Material.LineLoopDrawMode:
  2151. return this._gl.LINE_LOOP
  2152. case Material.LineStripDrawMode:
  2153. return this._gl.LINE_STRIP
  2154. case Material.TriangleStripDrawMode:
  2155. return this._gl.TRIANGLE_STRIP
  2156. case Material.TriangleFanDrawMode:
  2157. return this._gl.TRIANGLE_FAN;
  2158. default:
  2159. return this._gl.TRIANGLES;
  2160. }
  2161. }
  2162. // Shaders
  2163. public _releaseEffect(effect: Effect): void {
  2164. if (this._compiledEffects[effect._key]) {
  2165. delete this._compiledEffects[effect._key];
  2166. this._deleteProgram(effect.getProgram());
  2167. }
  2168. }
  2169. public _deleteProgram(program: WebGLProgram): void {
  2170. if (program) {
  2171. program.__SPECTOR_rebuildProgram = null;
  2172. if (program.transformFeedback) {
  2173. this.deleteTransformFeedback(program.transformFeedback);
  2174. program.transformFeedback = null;
  2175. }
  2176. this._gl.deleteProgram(program);
  2177. }
  2178. }
  2179. /**
  2180. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  2181. * @param samplers An array of string used to represent textures
  2182. */
  2183. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  2184. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  2185. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2186. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2187. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  2188. if (this._compiledEffects[name]) {
  2189. var compiledEffect = <Effect>this._compiledEffects[name];
  2190. if (onCompiled && compiledEffect.isReady()) {
  2191. onCompiled(compiledEffect);
  2192. }
  2193. return compiledEffect;
  2194. }
  2195. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  2196. effect._key = name;
  2197. this._compiledEffects[name] = effect;
  2198. return effect;
  2199. }
  2200. public createEffectForParticles(fragmentName: string, uniformsNames: string[] = [], samplers: string[] = [], defines = "", fallbacks?: EffectFallbacks,
  2201. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  2202. return this.createEffect(
  2203. {
  2204. vertex: "particles",
  2205. fragmentElement: fragmentName
  2206. },
  2207. ["position", "color", "options"],
  2208. ["view", "projection"].concat(uniformsNames),
  2209. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  2210. }
  2211. public createRawShaderProgram(vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2212. context = context || this._gl;
  2213. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  2214. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  2215. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2216. }
  2217. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2218. context = context || this._gl;
  2219. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  2220. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  2221. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  2222. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  2223. let program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2224. this.onAfterShaderCompilationObservable.notifyObservers(this);
  2225. return program;
  2226. }
  2227. private _createShaderProgram(vertexShader: WebGLShader, fragmentShader: WebGLShader, context: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2228. var shaderProgram = context.createProgram();
  2229. if (!shaderProgram) {
  2230. throw new Error("Unable to create program");
  2231. }
  2232. context.attachShader(shaderProgram, vertexShader);
  2233. context.attachShader(shaderProgram, fragmentShader);
  2234. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2235. let transformFeedback = this.createTransformFeedback();
  2236. this.bindTransformFeedback(transformFeedback);
  2237. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  2238. shaderProgram.transformFeedback = transformFeedback;
  2239. }
  2240. context.linkProgram(shaderProgram);
  2241. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2242. this.bindTransformFeedback(null);
  2243. }
  2244. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  2245. if (!linked) {
  2246. context.validateProgram(shaderProgram);
  2247. var error = context.getProgramInfoLog(shaderProgram);
  2248. if (error) {
  2249. throw new Error(error);
  2250. }
  2251. }
  2252. context.deleteShader(vertexShader);
  2253. context.deleteShader(fragmentShader);
  2254. return shaderProgram;
  2255. }
  2256. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  2257. var results = new Array<Nullable<WebGLUniformLocation>>();
  2258. for (var index = 0; index < uniformsNames.length; index++) {
  2259. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  2260. }
  2261. return results;
  2262. }
  2263. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  2264. var results = [];
  2265. for (var index = 0; index < attributesNames.length; index++) {
  2266. try {
  2267. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  2268. } catch (e) {
  2269. results.push(-1);
  2270. }
  2271. }
  2272. return results;
  2273. }
  2274. public enableEffect(effect: Nullable<Effect>): void {
  2275. if (!effect) {
  2276. return;
  2277. }
  2278. // Use program
  2279. this.bindSamplers(effect);
  2280. this._currentEffect = effect;
  2281. if (effect.onBind) {
  2282. effect.onBind(effect);
  2283. }
  2284. effect.onBindObservable.notifyObservers(effect);
  2285. }
  2286. public setIntArray(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2287. if (!uniform)
  2288. return;
  2289. this._gl.uniform1iv(uniform, array);
  2290. }
  2291. public setIntArray2(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2292. if (!uniform || array.length % 2 !== 0)
  2293. return;
  2294. this._gl.uniform2iv(uniform, array);
  2295. }
  2296. public setIntArray3(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2297. if (!uniform || array.length % 3 !== 0)
  2298. return;
  2299. this._gl.uniform3iv(uniform, array);
  2300. }
  2301. public setIntArray4(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2302. if (!uniform || array.length % 4 !== 0)
  2303. return;
  2304. this._gl.uniform4iv(uniform, array);
  2305. }
  2306. public setFloatArray(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2307. if (!uniform)
  2308. return;
  2309. this._gl.uniform1fv(uniform, array);
  2310. }
  2311. public setFloatArray2(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2312. if (!uniform || array.length % 2 !== 0)
  2313. return;
  2314. this._gl.uniform2fv(uniform, array);
  2315. }
  2316. public setFloatArray3(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2317. if (!uniform || array.length % 3 !== 0)
  2318. return;
  2319. this._gl.uniform3fv(uniform, array);
  2320. }
  2321. public setFloatArray4(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2322. if (!uniform || array.length % 4 !== 0)
  2323. return;
  2324. this._gl.uniform4fv(uniform, array);
  2325. }
  2326. public setArray(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2327. if (!uniform)
  2328. return;
  2329. this._gl.uniform1fv(uniform, <any>array);
  2330. }
  2331. public setArray2(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2332. if (!uniform || array.length % 2 !== 0)
  2333. return;
  2334. this._gl.uniform2fv(uniform, <any>array);
  2335. }
  2336. public setArray3(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2337. if (!uniform || array.length % 3 !== 0)
  2338. return;
  2339. this._gl.uniform3fv(uniform, <any>array);
  2340. }
  2341. public setArray4(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2342. if (!uniform || array.length % 4 !== 0)
  2343. return;
  2344. this._gl.uniform4fv(uniform, <any>array);
  2345. }
  2346. public setMatrices(uniform: Nullable<WebGLUniformLocation>, matrices: Float32Array): void {
  2347. if (!uniform)
  2348. return;
  2349. this._gl.uniformMatrix4fv(uniform, false, matrices);
  2350. }
  2351. public setMatrix(uniform: Nullable<WebGLUniformLocation>, matrix: Matrix): void {
  2352. if (!uniform)
  2353. return;
  2354. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  2355. }
  2356. public setMatrix3x3(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  2357. if (!uniform)
  2358. return;
  2359. this._gl.uniformMatrix3fv(uniform, false, matrix);
  2360. }
  2361. public setMatrix2x2(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  2362. if (!uniform)
  2363. return;
  2364. this._gl.uniformMatrix2fv(uniform, false, matrix);
  2365. }
  2366. public setInt(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  2367. if (!uniform)
  2368. return;
  2369. this._gl.uniform1i(uniform, value);
  2370. }
  2371. public setFloat(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  2372. if (!uniform)
  2373. return;
  2374. this._gl.uniform1f(uniform, value);
  2375. }
  2376. public setFloat2(uniform: Nullable<WebGLUniformLocation>, x: number, y: number): void {
  2377. if (!uniform)
  2378. return;
  2379. this._gl.uniform2f(uniform, x, y);
  2380. }
  2381. public setFloat3(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number): void {
  2382. if (!uniform)
  2383. return;
  2384. this._gl.uniform3f(uniform, x, y, z);
  2385. }
  2386. public setBool(uniform: Nullable<WebGLUniformLocation>, bool: number): void {
  2387. if (!uniform)
  2388. return;
  2389. this._gl.uniform1i(uniform, bool);
  2390. }
  2391. public setFloat4(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number, w: number): void {
  2392. if (!uniform)
  2393. return;
  2394. this._gl.uniform4f(uniform, x, y, z, w);
  2395. }
  2396. public setColor3(uniform: Nullable<WebGLUniformLocation>, color3: Color3): void {
  2397. if (!uniform)
  2398. return;
  2399. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  2400. }
  2401. public setColor4(uniform: Nullable<WebGLUniformLocation>, color3: Color3, alpha: number): void {
  2402. if (!uniform)
  2403. return;
  2404. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  2405. }
  2406. /**
  2407. * Sets a Color4 on a uniform variable
  2408. * @param uniform defines the uniform location
  2409. * @param color4 defines the value to be set
  2410. */
  2411. public setDirectColor4(uniform: Nullable<WebGLUniformLocation>, color4: Color4): void {
  2412. if (!uniform)
  2413. return;
  2414. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  2415. }
  2416. // States
  2417. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  2418. // Culling
  2419. if (this._depthCullingState.cull !== culling || force) {
  2420. this._depthCullingState.cull = culling;
  2421. }
  2422. // Cull face
  2423. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  2424. if (this._depthCullingState.cullFace !== cullFace || force) {
  2425. this._depthCullingState.cullFace = cullFace;
  2426. }
  2427. // Z offset
  2428. this.setZOffset(zOffset);
  2429. // Front face
  2430. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  2431. if (this._depthCullingState.frontFace !== frontFace || force) {
  2432. this._depthCullingState.frontFace = frontFace;
  2433. }
  2434. }
  2435. public setZOffset(value: number): void {
  2436. this._depthCullingState.zOffset = value;
  2437. }
  2438. public getZOffset(): number {
  2439. return this._depthCullingState.zOffset;
  2440. }
  2441. public setDepthBuffer(enable: boolean): void {
  2442. this._depthCullingState.depthTest = enable;
  2443. }
  2444. public getDepthWrite(): boolean {
  2445. return this._depthCullingState.depthMask;
  2446. }
  2447. public setDepthWrite(enable: boolean): void {
  2448. this._depthCullingState.depthMask = enable;
  2449. }
  2450. public setColorWrite(enable: boolean): void {
  2451. this._gl.colorMask(enable, enable, enable, enable);
  2452. this._colorWrite = enable;
  2453. }
  2454. public getColorWrite(): boolean {
  2455. return this._colorWrite;
  2456. }
  2457. public setAlphaConstants(r: number, g: number, b: number, a: number) {
  2458. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  2459. }
  2460. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  2461. if (this._alphaMode === mode) {
  2462. return;
  2463. }
  2464. switch (mode) {
  2465. case Engine.ALPHA_DISABLE:
  2466. this._alphaState.alphaBlend = false;
  2467. break;
  2468. case Engine.ALPHA_PREMULTIPLIED:
  2469. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  2470. this._alphaState.alphaBlend = true;
  2471. break;
  2472. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  2473. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  2474. this._alphaState.alphaBlend = true;
  2475. break;
  2476. case Engine.ALPHA_COMBINE:
  2477. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  2478. this._alphaState.alphaBlend = true;
  2479. break;
  2480. case Engine.ALPHA_ONEONE:
  2481. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  2482. this._alphaState.alphaBlend = true;
  2483. break;
  2484. case Engine.ALPHA_ADD:
  2485. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  2486. this._alphaState.alphaBlend = true;
  2487. break;
  2488. case Engine.ALPHA_SUBTRACT:
  2489. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  2490. this._alphaState.alphaBlend = true;
  2491. break;
  2492. case Engine.ALPHA_MULTIPLY:
  2493. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  2494. this._alphaState.alphaBlend = true;
  2495. break;
  2496. case Engine.ALPHA_MAXIMIZED:
  2497. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  2498. this._alphaState.alphaBlend = true;
  2499. break;
  2500. case Engine.ALPHA_INTERPOLATE:
  2501. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  2502. this._alphaState.alphaBlend = true;
  2503. break;
  2504. case Engine.ALPHA_SCREENMODE:
  2505. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  2506. this._alphaState.alphaBlend = true;
  2507. break;
  2508. }
  2509. if (!noDepthWriteChange) {
  2510. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  2511. }
  2512. this._alphaMode = mode;
  2513. }
  2514. public getAlphaMode(): number {
  2515. return this._alphaMode;
  2516. }
  2517. // Textures
  2518. public wipeCaches(bruteForce?: boolean): void {
  2519. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  2520. return;
  2521. }
  2522. this._currentEffect = null;
  2523. // 6/8/2017: deltakosh: Should not be required anymore.
  2524. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  2525. if (bruteForce) {
  2526. this.resetTextureCache();
  2527. this._currentProgram = null;
  2528. this._stencilState.reset();
  2529. this._depthCullingState.reset();
  2530. this.setDepthFunctionToLessOrEqual();
  2531. this._alphaState.reset();
  2532. }
  2533. this._resetVertexBufferBinding();
  2534. this._cachedIndexBuffer = null;
  2535. this._cachedEffectForVertexBuffers = null;
  2536. this._unbindVertexArrayObject();
  2537. this.bindIndexBuffer(null);
  2538. }
  2539. /**
  2540. * Set the compressed texture format to use, based on the formats you have, and the formats
  2541. * supported by the hardware / browser.
  2542. *
  2543. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  2544. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  2545. * to API arguments needed to compressed textures. This puts the burden on the container
  2546. * generator to house the arcane code for determining these for current & future formats.
  2547. *
  2548. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  2549. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  2550. *
  2551. * Note: The result of this call is not taken into account when a texture is base64.
  2552. *
  2553. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  2554. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  2555. *
  2556. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  2557. * @returns The extension selected.
  2558. */
  2559. public setTextureFormatToUse(formatsAvailable: Array<string>): Nullable<string> {
  2560. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  2561. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  2562. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  2563. return this._textureFormatInUse = this._texturesSupported[i];
  2564. }
  2565. }
  2566. }
  2567. // actively set format to nothing, to allow this to be called more than once
  2568. // and possibly fail the 2nd time
  2569. this._textureFormatInUse = null;
  2570. return null;
  2571. }
  2572. public _createTexture(): WebGLTexture {
  2573. let texture = this._gl.createTexture();
  2574. if (!texture) {
  2575. throw new Error("Unable to create texture");
  2576. }
  2577. return texture;
  2578. }
  2579. /**
  2580. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  2581. * @param {string} urlArg- This contains one of the following:
  2582. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  2583. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  2584. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  2585. *
  2586. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  2587. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  2588. * @param {Scene} scene- Needed for loading to the correct scene.
  2589. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  2590. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  2591. * @param {callback} onError- Optional callback to be called upon failure.
  2592. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  2593. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  2594. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  2595. *
  2596. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  2597. */
  2598. public createTexture(urlArg: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<Scene>, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE,
  2599. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  2600. buffer: Nullable<ArrayBuffer | HTMLImageElement> = null, fallBack: Nullable<InternalTexture> = null, format: Nullable<number> = null): InternalTexture {
  2601. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  2602. var fromData = url.substr(0, 5) === "data:";
  2603. var fromBlob = url.substr(0, 5) === "blob:";
  2604. var isBase64 = fromData && url.indexOf("base64") !== -1;
  2605. let texture = fallBack ? fallBack : new InternalTexture(this, InternalTexture.DATASOURCE_URL);
  2606. // establish the file extension, if possible
  2607. var lastDot = url.lastIndexOf('.');
  2608. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  2609. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  2610. var isTGA = (extension.indexOf(".tga") === 0);
  2611. // determine if a ktx file should be substituted
  2612. var isKTX = false;
  2613. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  2614. url = url.substring(0, lastDot) + this._textureFormatInUse;
  2615. isKTX = true;
  2616. }
  2617. if (scene) {
  2618. scene._addPendingData(texture);
  2619. }
  2620. texture.url = url;
  2621. texture.generateMipMaps = !noMipmap;
  2622. texture.samplingMode = samplingMode;
  2623. texture.invertY = invertY;
  2624. if (!this._doNotHandleContextLost) {
  2625. // Keep a link to the buffer only if we plan to handle context lost
  2626. texture._buffer = buffer;
  2627. }
  2628. let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
  2629. if (onLoad && !fallBack) {
  2630. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  2631. }
  2632. if (!fallBack) this._internalTexturesCache.push(texture);
  2633. var onerror = (message?: string, exception?: any) => {
  2634. if (scene) {
  2635. scene._removePendingData(texture);
  2636. }
  2637. if (onLoadObserver) {
  2638. texture.onLoadedObservable.remove(onLoadObserver);
  2639. }
  2640. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  2641. if (isKTX) {
  2642. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  2643. } else if (Tools.UseFallbackTexture) {
  2644. this.createTexture(Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  2645. }
  2646. if (onError) {
  2647. onError(message || "Unknown error", exception);
  2648. }
  2649. };
  2650. var callback: Nullable<(arrayBuffer: any) => void> = null;
  2651. // processing for non-image formats
  2652. if (isKTX || isTGA || isDDS) {
  2653. if (isKTX) {
  2654. callback = (data) => {
  2655. var ktx = new KhronosTextureContainer(data, 1);
  2656. this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, () => {
  2657. ktx.uploadLevels(this._gl, !noMipmap);
  2658. return false;
  2659. }, samplingMode);
  2660. };
  2661. } else if (isTGA) {
  2662. callback = (arrayBuffer) => {
  2663. var data = new Uint8Array(arrayBuffer);
  2664. var header = TGATools.GetTGAHeader(data);
  2665. this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, () => {
  2666. TGATools.UploadContent(this._gl, data);
  2667. return false;
  2668. }, samplingMode);
  2669. };
  2670. } else if (isDDS) {
  2671. callback = (data) => {
  2672. var info = DDSTools.GetDDSInfo(data);
  2673. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  2674. this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  2675. DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 1);
  2676. return false;
  2677. }, samplingMode);
  2678. };
  2679. }
  2680. if (!buffer) {
  2681. this._loadFile(url, data => {
  2682. if (callback) {
  2683. callback(data);
  2684. }
  2685. }, undefined, scene ? scene.database : undefined, true, (request?: XMLHttpRequest, exception?: any) => {
  2686. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  2687. });
  2688. } else {
  2689. if (callback) {
  2690. callback(buffer);
  2691. }
  2692. }
  2693. // image format processing
  2694. } else {
  2695. var onload = (img: HTMLImageElement) => {
  2696. if (fromBlob && !this._doNotHandleContextLost) {
  2697. // We need to store the image if we need to rebuild the texture
  2698. // in case of a webgl context lost
  2699. texture._buffer = img;
  2700. }
  2701. this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight, continuationCallback) => {
  2702. let gl = this._gl;
  2703. var isPot = (img.width === potWidth && img.height === potHeight);
  2704. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  2705. if (isPot) {
  2706. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2707. return false;
  2708. }
  2709. // Using shaders to rescale because canvas.drawImage is lossy
  2710. let source = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  2711. this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  2712. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2713. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2714. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  2715. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2716. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2717. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  2718. this._releaseTexture(source);
  2719. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  2720. continuationCallback();
  2721. });
  2722. return true;
  2723. }, samplingMode);
  2724. };
  2725. if (!fromData || isBase64)
  2726. if (buffer instanceof HTMLImageElement) {
  2727. onload(buffer);
  2728. } else {
  2729. Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  2730. }
  2731. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  2732. Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  2733. else
  2734. onload(<HTMLImageElement>buffer);
  2735. }
  2736. return texture;
  2737. }
  2738. private _rescaleTexture(source: InternalTexture, destination: InternalTexture, scene: Nullable<Scene>, internalFormat: number, onComplete: () => void): void {
  2739. let rtt = this.createRenderTargetTexture({
  2740. width: destination.width,
  2741. height: destination.height,
  2742. }, {
  2743. generateMipMaps: false,
  2744. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  2745. samplingMode: Texture.BILINEAR_SAMPLINGMODE,
  2746. generateDepthBuffer: false,
  2747. generateStencilBuffer: false
  2748. }
  2749. );
  2750. if (!this._rescalePostProcess) {
  2751. this._rescalePostProcess = new PassPostProcess("rescale", 1, null, Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  2752. }
  2753. this._rescalePostProcess.getEffect().executeWhenCompiled(() => {
  2754. this._rescalePostProcess.onApply = function (effect) {
  2755. effect._bindTexture("textureSampler", source);
  2756. }
  2757. let hostingScene = scene;
  2758. if (!hostingScene) {
  2759. hostingScene = this.scenes[this.scenes.length - 1];
  2760. }
  2761. hostingScene.postProcessManager.directRender([this._rescalePostProcess], rtt, true);
  2762. this._bindTextureDirectly(this._gl.TEXTURE_2D, destination, true);
  2763. this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  2764. this.unBindFramebuffer(rtt);
  2765. this._releaseTexture(rtt);
  2766. if (onComplete) {
  2767. onComplete();
  2768. }
  2769. });
  2770. }
  2771. private _getInternalFormat(format: number): number {
  2772. var internalFormat = this._gl.RGBA;
  2773. switch (format) {
  2774. case Engine.TEXTUREFORMAT_ALPHA:
  2775. internalFormat = this._gl.ALPHA;
  2776. break;
  2777. case Engine.TEXTUREFORMAT_LUMINANCE:
  2778. internalFormat = this._gl.LUMINANCE;
  2779. break;
  2780. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  2781. internalFormat = this._gl.LUMINANCE_ALPHA;
  2782. break;
  2783. case Engine.TEXTUREFORMAT_RGB:
  2784. case Engine.TEXTUREFORMAT_RGB32F:
  2785. internalFormat = this._gl.RGB;
  2786. break;
  2787. case Engine.TEXTUREFORMAT_RGBA:
  2788. case Engine.TEXTUREFORMAT_RGBA32F:
  2789. internalFormat = this._gl.RGBA;
  2790. break;
  2791. case Engine.TEXTUREFORMAT_R32F:
  2792. internalFormat = this._gl.RED;
  2793. break;
  2794. case Engine.TEXTUREFORMAT_RG32F:
  2795. internalFormat = this._gl.RG;
  2796. break;
  2797. }
  2798. return internalFormat;
  2799. }
  2800. public updateRawTexture(texture: Nullable<InternalTexture>, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, type = Engine.TEXTURETYPE_UNSIGNED_INT): void {
  2801. if (!texture) {
  2802. return;
  2803. }
  2804. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  2805. var internalFormat = this._getInternalFormat(format);
  2806. var textureType = this._getWebGLTextureType(type);
  2807. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2808. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2809. if (!this._doNotHandleContextLost) {
  2810. texture._bufferView = data;
  2811. texture.format = format;
  2812. texture.type = type;
  2813. texture.invertY = invertY;
  2814. texture._compression = compression;
  2815. }
  2816. if (texture.width % 4 !== 0) {
  2817. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  2818. }
  2819. if (compression && data) {
  2820. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, 0, data);
  2821. } else {
  2822. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  2823. }
  2824. if (texture.generateMipMaps) {
  2825. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2826. }
  2827. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2828. // this.resetTextureCache();
  2829. texture.isReady = true;
  2830. }
  2831. 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 {
  2832. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW);
  2833. texture.baseWidth = width;
  2834. texture.baseHeight = height;
  2835. texture.width = width;
  2836. texture.height = height;
  2837. texture.format = format;
  2838. texture.generateMipMaps = generateMipMaps;
  2839. texture.samplingMode = samplingMode;
  2840. texture.invertY = invertY;
  2841. texture._compression = compression;
  2842. texture.type = type;
  2843. if (!this._doNotHandleContextLost) {
  2844. texture._bufferView = data;
  2845. }
  2846. this.updateRawTexture(texture, data, format, invertY, compression, type);
  2847. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2848. // Filters
  2849. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  2850. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2851. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2852. if (generateMipMaps) {
  2853. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2854. }
  2855. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2856. this._internalTexturesCache.push(texture);
  2857. return texture;
  2858. }
  2859. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): InternalTexture {
  2860. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_DYNAMIC)
  2861. texture.baseWidth = width;
  2862. texture.baseHeight = height;
  2863. if (generateMipMaps) {
  2864. width = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  2865. height = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  2866. }
  2867. // this.resetTextureCache();
  2868. texture.width = width;
  2869. texture.height = height;
  2870. texture.isReady = false;
  2871. texture.generateMipMaps = generateMipMaps;
  2872. texture.samplingMode = samplingMode;
  2873. this.updateTextureSamplingMode(samplingMode, texture);
  2874. this._internalTexturesCache.push(texture);
  2875. return texture;
  2876. }
  2877. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  2878. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  2879. if (texture.isCube) {
  2880. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  2881. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2882. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2883. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2884. } else if (texture.is3D) {
  2885. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  2886. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2887. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2888. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  2889. } else {
  2890. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2891. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2892. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2893. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2894. }
  2895. texture.samplingMode = samplingMode;
  2896. }
  2897. public updateDynamicTexture(texture: Nullable<InternalTexture>, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  2898. if (!texture) {
  2899. return;
  2900. }
  2901. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2902. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  2903. if (premulAlpha) {
  2904. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  2905. }
  2906. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  2907. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  2908. if (texture.generateMipMaps) {
  2909. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2910. }
  2911. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2912. if (premulAlpha) {
  2913. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  2914. }
  2915. texture.isReady = true;
  2916. }
  2917. public updateVideoTexture(texture: Nullable<InternalTexture>, video: HTMLVideoElement, invertY: boolean): void {
  2918. if (!texture || texture._isDisabled) {
  2919. return;
  2920. }
  2921. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2922. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  2923. try {
  2924. // Testing video texture support
  2925. if (this._videoTextureSupported === undefined) {
  2926. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  2927. if (this._gl.getError() !== 0) {
  2928. this._videoTextureSupported = false;
  2929. } else {
  2930. this._videoTextureSupported = true;
  2931. }
  2932. }
  2933. // Copy video through the current working canvas if video texture is not supported
  2934. if (!this._videoTextureSupported) {
  2935. if (!texture._workingCanvas) {
  2936. texture._workingCanvas = document.createElement("canvas");
  2937. let context = texture._workingCanvas.getContext("2d");
  2938. if (!context) {
  2939. throw new Error("Unable to get 2d context");
  2940. }
  2941. texture._workingContext = context;
  2942. texture._workingCanvas.width = texture.width;
  2943. texture._workingCanvas.height = texture.height;
  2944. }
  2945. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  2946. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  2947. } else {
  2948. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  2949. }
  2950. if (texture.generateMipMaps) {
  2951. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2952. }
  2953. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2954. // this.resetTextureCache();
  2955. texture.isReady = true;
  2956. } catch (ex) {
  2957. // Something unexpected
  2958. // Let's disable the texture
  2959. texture._isDisabled = true;
  2960. }
  2961. }
  2962. public createRenderTargetTexture(size: number | { width: number, height: number }, options: boolean | RenderTargetCreationOptions): InternalTexture {
  2963. let fullOptions = new RenderTargetCreationOptions();
  2964. if (options !== undefined && typeof options === "object") {
  2965. fullOptions.generateMipMaps = options.generateMipMaps;
  2966. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2967. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  2968. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  2969. fullOptions.samplingMode = options.samplingMode === undefined ? Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  2970. } else {
  2971. fullOptions.generateMipMaps = <boolean>options;
  2972. fullOptions.generateDepthBuffer = true;
  2973. fullOptions.generateStencilBuffer = false;
  2974. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2975. fullOptions.samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2976. }
  2977. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  2978. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  2979. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2980. }
  2981. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  2982. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  2983. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2984. }
  2985. var gl = this._gl;
  2986. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  2987. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  2988. var width = (<{ width: number, height: number }>size).width || <number>size;
  2989. var height = (<{ width: number, height: number }>size).height || <number>size;
  2990. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  2991. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  2992. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2993. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  2994. }
  2995. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2996. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2997. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2998. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2999. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  3000. // Create the framebuffer
  3001. var framebuffer = gl.createFramebuffer();
  3002. this.bindUnboundFramebuffer(framebuffer);
  3003. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  3004. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  3005. if (fullOptions.generateMipMaps) {
  3006. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3007. }
  3008. // Unbind
  3009. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  3010. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3011. this.bindUnboundFramebuffer(null);
  3012. texture._framebuffer = framebuffer;
  3013. texture.baseWidth = width;
  3014. texture.baseHeight = height;
  3015. texture.width = width;
  3016. texture.height = height;
  3017. texture.isReady = true;
  3018. texture.samples = 1;
  3019. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  3020. texture.samplingMode = fullOptions.samplingMode;
  3021. texture.type = fullOptions.type;
  3022. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  3023. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  3024. // this.resetTextureCache();
  3025. this._internalTexturesCache.push(texture);
  3026. return texture;
  3027. }
  3028. public createMultipleRenderTarget(size: any, options: any): InternalTexture[] {
  3029. var generateMipMaps = false;
  3030. var generateDepthBuffer = true;
  3031. var generateStencilBuffer = false;
  3032. var generateDepthTexture = false;
  3033. var textureCount = 1;
  3034. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  3035. var defaultSamplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  3036. var types = [], samplingModes = [];
  3037. if (options !== undefined) {
  3038. generateMipMaps = options.generateMipMaps;
  3039. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3040. generateStencilBuffer = options.generateStencilBuffer;
  3041. generateDepthTexture = options.generateDepthTexture;
  3042. textureCount = options.textureCount || 1;
  3043. if (options.types) {
  3044. types = options.types;
  3045. }
  3046. if (options.samplingModes) {
  3047. samplingModes = options.samplingModes;
  3048. }
  3049. }
  3050. var gl = this._gl;
  3051. // Create the framebuffer
  3052. var framebuffer = gl.createFramebuffer();
  3053. this.bindUnboundFramebuffer(framebuffer);
  3054. var width = size.width || size;
  3055. var height = size.height || size;
  3056. var textures = [];
  3057. var attachments = []
  3058. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  3059. for (var i = 0; i < textureCount; i++) {
  3060. var samplingMode = samplingModes[i] || defaultSamplingMode;
  3061. var type = types[i] || defaultType;
  3062. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  3063. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  3064. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  3065. }
  3066. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  3067. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  3068. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  3069. }
  3070. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3071. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  3072. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  3073. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  3074. }
  3075. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  3076. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  3077. textures.push(texture);
  3078. attachments.push(attachment);
  3079. gl.activeTexture((<any>gl)["TEXTURE" + i]);
  3080. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  3081. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3082. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3083. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3084. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3085. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  3086. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  3087. if (generateMipMaps) {
  3088. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3089. }
  3090. // Unbind
  3091. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  3092. texture._framebuffer = framebuffer;
  3093. texture._depthStencilBuffer = depthStencilBuffer;
  3094. texture.baseWidth = width;
  3095. texture.baseHeight = height;
  3096. texture.width = width;
  3097. texture.height = height;
  3098. texture.isReady = true;
  3099. texture.samples = 1;
  3100. texture.generateMipMaps = generateMipMaps;
  3101. texture.samplingMode = samplingMode;
  3102. texture.type = type;
  3103. texture._generateDepthBuffer = generateDepthBuffer;
  3104. texture._generateStencilBuffer = generateStencilBuffer;
  3105. texture._attachments = attachments;
  3106. this._internalTexturesCache.push(texture);
  3107. }
  3108. if (generateDepthTexture && this._caps.depthTextureExtension) {
  3109. // Depth texture
  3110. var depthTexture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  3111. gl.activeTexture(gl.TEXTURE0);
  3112. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  3113. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3114. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3115. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3116. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3117. gl.texImage2D(
  3118. gl.TEXTURE_2D,
  3119. 0,
  3120. this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16,
  3121. width,
  3122. height,
  3123. 0,
  3124. gl.DEPTH_COMPONENT,
  3125. gl.UNSIGNED_SHORT,
  3126. null
  3127. );
  3128. gl.framebufferTexture2D(
  3129. gl.FRAMEBUFFER,
  3130. gl.DEPTH_ATTACHMENT,
  3131. gl.TEXTURE_2D,
  3132. depthTexture._webGLTexture,
  3133. 0
  3134. );
  3135. depthTexture._framebuffer = framebuffer;
  3136. depthTexture.baseWidth = width;
  3137. depthTexture.baseHeight = height;
  3138. depthTexture.width = width;
  3139. depthTexture.height = height;
  3140. depthTexture.isReady = true;
  3141. depthTexture.samples = 1;
  3142. depthTexture.generateMipMaps = generateMipMaps;
  3143. depthTexture.samplingMode = gl.NEAREST;
  3144. depthTexture._generateDepthBuffer = generateDepthBuffer;
  3145. depthTexture._generateStencilBuffer = generateStencilBuffer;
  3146. textures.push(depthTexture)
  3147. this._internalTexturesCache.push(depthTexture);
  3148. }
  3149. gl.drawBuffers(attachments);
  3150. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3151. this.bindUnboundFramebuffer(null);
  3152. this.resetTextureCache();
  3153. return textures;
  3154. }
  3155. private _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): Nullable<WebGLRenderbuffer> {
  3156. var depthStencilBuffer: Nullable<WebGLRenderbuffer> = null;
  3157. var gl = this._gl;
  3158. // Create the depth/stencil buffer
  3159. if (generateStencilBuffer) {
  3160. depthStencilBuffer = gl.createRenderbuffer();
  3161. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  3162. if (samples > 1) {
  3163. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  3164. } else {
  3165. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  3166. }
  3167. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  3168. }
  3169. else if (generateDepthBuffer) {
  3170. depthStencilBuffer = gl.createRenderbuffer();
  3171. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  3172. if (samples > 1) {
  3173. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  3174. } else {
  3175. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3176. }
  3177. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  3178. }
  3179. return depthStencilBuffer;
  3180. }
  3181. public updateRenderTargetTextureSampleCount(texture: Nullable<InternalTexture>, samples: number): number {
  3182. if (this.webGLVersion < 2 || !texture) {
  3183. return 1;
  3184. }
  3185. if (texture.samples === samples) {
  3186. return samples;
  3187. }
  3188. var gl = this._gl;
  3189. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  3190. // Dispose previous render buffers
  3191. if (texture._depthStencilBuffer) {
  3192. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  3193. texture._depthStencilBuffer = null;
  3194. }
  3195. if (texture._MSAAFramebuffer) {
  3196. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  3197. texture._MSAAFramebuffer = null;
  3198. }
  3199. if (texture._MSAARenderBuffer) {
  3200. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  3201. texture._MSAARenderBuffer = null;
  3202. }
  3203. if (samples > 1) {
  3204. let framebuffer = gl.createFramebuffer();
  3205. if (!framebuffer) {
  3206. throw new Error("Unable to create multi sampled framebuffer");
  3207. }
  3208. texture._MSAAFramebuffer = framebuffer;
  3209. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  3210. var colorRenderbuffer = gl.createRenderbuffer();
  3211. if (!colorRenderbuffer) {
  3212. throw new Error("Unable to create multi sampled framebuffer");
  3213. }
  3214. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  3215. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  3216. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  3217. texture._MSAARenderBuffer = colorRenderbuffer;
  3218. } else {
  3219. this.bindUnboundFramebuffer(texture._framebuffer);
  3220. }
  3221. texture.samples = samples;
  3222. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  3223. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3224. this.bindUnboundFramebuffer(null);
  3225. return samples;
  3226. }
  3227. public updateMultipleRenderTargetTextureSampleCount(textures: Nullable<InternalTexture[]>, samples: number): number {
  3228. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  3229. return 1;
  3230. }
  3231. if (textures[0].samples === samples) {
  3232. return samples;
  3233. }
  3234. var gl = this._gl;
  3235. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  3236. // Dispose previous render buffers
  3237. if (textures[0]._depthStencilBuffer) {
  3238. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  3239. textures[0]._depthStencilBuffer = null;
  3240. }
  3241. if (textures[0]._MSAAFramebuffer) {
  3242. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  3243. textures[0]._MSAAFramebuffer = null;
  3244. }
  3245. for (var i = 0; i < textures.length; i++) {
  3246. if (textures[i]._MSAARenderBuffer) {
  3247. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  3248. textures[i]._MSAARenderBuffer = null;
  3249. }
  3250. }
  3251. if (samples > 1) {
  3252. let framebuffer = gl.createFramebuffer();
  3253. if (!framebuffer) {
  3254. throw new Error("Unable to create multi sampled framebuffer");
  3255. }
  3256. this.bindUnboundFramebuffer(framebuffer);
  3257. let depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  3258. var attachments = [];
  3259. for (var i = 0; i < textures.length; i++) {
  3260. var texture = textures[i];
  3261. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  3262. var colorRenderbuffer = gl.createRenderbuffer();
  3263. if (!colorRenderbuffer) {
  3264. throw new Error("Unable to create multi sampled framebuffer");
  3265. }
  3266. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  3267. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  3268. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  3269. texture._MSAAFramebuffer = framebuffer;
  3270. texture._MSAARenderBuffer = colorRenderbuffer;
  3271. texture.samples = samples;
  3272. texture._depthStencilBuffer = depthStencilBuffer;
  3273. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3274. attachments.push(attachment);
  3275. }
  3276. gl.drawBuffers(attachments);
  3277. } else {
  3278. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  3279. }
  3280. this.bindUnboundFramebuffer(null);
  3281. return samples;
  3282. }
  3283. public _uploadDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, format: number, type: number, data: ArrayBufferView) {
  3284. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  3285. }
  3286. public _uploadCompressedDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, data: ArrayBufferView) {
  3287. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  3288. }
  3289. public createRenderTargetCubeTexture(size: number, options?: Partial<RenderTargetCreationOptions>): InternalTexture {
  3290. let fullOptions = {
  3291. generateMipMaps: true,
  3292. generateDepthBuffer: true,
  3293. generateStencilBuffer: false,
  3294. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  3295. samplingMode: Texture.TRILINEAR_SAMPLINGMODE,
  3296. ...options
  3297. };
  3298. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  3299. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  3300. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  3301. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  3302. }
  3303. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  3304. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  3305. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  3306. }
  3307. var gl = this._gl
  3308. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  3309. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3310. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  3311. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  3312. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  3313. Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  3314. }
  3315. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  3316. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  3317. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3318. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3319. for (var face = 0; face < 6; face++) {
  3320. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  3321. }
  3322. // Create the framebuffer
  3323. var framebuffer = gl.createFramebuffer();
  3324. this.bindUnboundFramebuffer(framebuffer);
  3325. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  3326. // MipMaps
  3327. if (fullOptions.generateMipMaps) {
  3328. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3329. }
  3330. // Unbind
  3331. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3332. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3333. this.bindUnboundFramebuffer(null);
  3334. texture._framebuffer = framebuffer;
  3335. texture.width = size;
  3336. texture.height = size;
  3337. texture.isReady = true;
  3338. texture.isCube = true;
  3339. texture.samples = 1;
  3340. texture.generateMipMaps = fullOptions.generateMipMaps;
  3341. texture.samplingMode = fullOptions.samplingMode;
  3342. texture.type = fullOptions.type;
  3343. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  3344. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  3345. this._internalTexturesCache.push(texture);
  3346. return texture;
  3347. }
  3348. public createPrefilteredCubeTexture(rootUrl: string, scene: Nullable<Scene>, scale: number, offset: number,
  3349. onLoad: Nullable<(internalTexture: Nullable<InternalTexture>) => void> = null,
  3350. onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null): InternalTexture {
  3351. var callback = (loadData: any) => {
  3352. if (!loadData) {
  3353. if (onLoad) {
  3354. onLoad(null);
  3355. }
  3356. return;
  3357. }
  3358. let texture = loadData.texture as InternalTexture;
  3359. texture._dataSource = InternalTexture.DATASOURCE_CUBEPREFILTERED;
  3360. texture._lodGenerationScale = scale;
  3361. texture._lodGenerationOffset = offset;
  3362. if (this._caps.textureLOD) {
  3363. // Do not add extra process if texture lod is supported.
  3364. if (onLoad) {
  3365. onLoad(texture);
  3366. }
  3367. return;
  3368. }
  3369. const mipSlices = 3;
  3370. var gl = this._gl;
  3371. const width = loadData.width;
  3372. if (!width) {
  3373. return;
  3374. }
  3375. const textures: BaseTexture[] = [];
  3376. for (let i = 0; i < mipSlices; i++) {
  3377. //compute LOD from even spacing in smoothness (matching shader calculation)
  3378. let smoothness = i / (mipSlices - 1);
  3379. let roughness = 1 - smoothness;
  3380. let minLODIndex = offset; // roughness = 0
  3381. let maxLODIndex = Scalar.Log2(width) * scale + offset; // roughness = 1
  3382. let lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  3383. let mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  3384. var glTextureFromLod = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  3385. glTextureFromLod.isCube = true;
  3386. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  3387. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3388. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  3389. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3390. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3391. if (loadData.isDDS) {
  3392. var info: DDSInfo = loadData.info;
  3393. var data: any = loadData.data;
  3394. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  3395. DDSTools.UploadDDSLevels(this, this._gl, data, info, true, 6, mipmapIndex);
  3396. }
  3397. else {
  3398. Tools.Warn("DDS is the only prefiltered cube map supported so far.")
  3399. }
  3400. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3401. // Wrap in a base texture for easy binding.
  3402. const lodTexture = new BaseTexture(scene);
  3403. lodTexture.isCube = true;
  3404. lodTexture._texture = glTextureFromLod;
  3405. glTextureFromLod.isReady = true;
  3406. textures.push(lodTexture);
  3407. }
  3408. texture._lodTextureHigh = textures[2];
  3409. texture._lodTextureMid = textures[1];
  3410. texture._lodTextureLow = textures[0];
  3411. if (onLoad) {
  3412. onLoad(texture);
  3413. }
  3414. };
  3415. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  3416. }
  3417. public createCubeTexture(rootUrl: string, scene: Nullable<Scene>, files: Nullable<string[]>, noMipmap?: boolean, onLoad: Nullable<(data?: any) => void> = null, onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null): InternalTexture {
  3418. var gl = this._gl;
  3419. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
  3420. texture.isCube = true;
  3421. texture.url = rootUrl;
  3422. texture.generateMipMaps = !noMipmap;
  3423. if (!this._doNotHandleContextLost) {
  3424. texture._extension = forcedExtension;
  3425. texture._files = files;
  3426. }
  3427. var isKTX = false;
  3428. var isDDS = false;
  3429. var lastDot = rootUrl.lastIndexOf('.');
  3430. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  3431. if (this._textureFormatInUse) {
  3432. extension = this._textureFormatInUse;
  3433. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  3434. isKTX = true;
  3435. } else {
  3436. isDDS = (extension === ".dds");
  3437. }
  3438. let onerror = (request?: XMLHttpRequest, exception?: any) => {
  3439. if (onError && request) {
  3440. onError(request.status + " " + request.statusText, exception);
  3441. }
  3442. }
  3443. if (isKTX) {
  3444. this._loadFile(rootUrl, data => {
  3445. var ktx = new KhronosTextureContainer(data, 6);
  3446. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  3447. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3448. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3449. ktx.uploadLevels(this._gl, !noMipmap);
  3450. this.setCubeMapTextureParams(gl, loadMipmap);
  3451. texture.width = ktx.pixelWidth;
  3452. texture.height = ktx.pixelHeight;
  3453. texture.isReady = true;
  3454. }, undefined, undefined, true, onerror);
  3455. } else if (isDDS) {
  3456. if (files && files.length === 6) {
  3457. this._cascadeLoadFiles(
  3458. scene,
  3459. imgs => {
  3460. var info: DDSInfo | undefined;
  3461. var loadMipmap: boolean = false;
  3462. var width: number = 0;
  3463. for (let index = 0; index < imgs.length; index++) {
  3464. let data = imgs[index];
  3465. info = DDSTools.GetDDSInfo(data);
  3466. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3467. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3468. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  3469. DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 6, -1, index);
  3470. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  3471. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3472. }
  3473. texture.width = info.width;
  3474. texture.height = info.height;
  3475. texture.type = info.textureType;
  3476. width = info.width;
  3477. }
  3478. this.setCubeMapTextureParams(gl, loadMipmap);
  3479. texture.isReady = true;
  3480. if (onLoad) {
  3481. onLoad({ isDDS: true, width: width, info, imgs, texture });
  3482. }
  3483. },
  3484. files,
  3485. onError);
  3486. } else {
  3487. this._loadFile(rootUrl,
  3488. data => {
  3489. var info = DDSTools.GetDDSInfo(data);
  3490. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3491. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3492. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  3493. DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 6);
  3494. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  3495. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3496. }
  3497. this.setCubeMapTextureParams(gl, loadMipmap);
  3498. texture.width = info.width;
  3499. texture.height = info.height;
  3500. texture.isReady = true;
  3501. texture.type = info.textureType;
  3502. if (onLoad) {
  3503. onLoad({ isDDS: true, width: info.width, info, data, texture });
  3504. }
  3505. },
  3506. undefined,
  3507. undefined,
  3508. true,
  3509. onerror);
  3510. }
  3511. } else {
  3512. if (!files) {
  3513. throw new Error("Cannot load cubemap because files were not defined");
  3514. }
  3515. cascadeLoadImgs(rootUrl, scene, imgs => {
  3516. var width = this.needPOTTextures ? Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width;
  3517. var height = width;
  3518. this._prepareWorkingCanvas();
  3519. if (!this._workingCanvas || !this._workingContext) {
  3520. return;
  3521. }
  3522. this._workingCanvas.width = width;
  3523. this._workingCanvas.height = height;
  3524. var faces = [
  3525. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3526. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3527. ];
  3528. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3529. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3530. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  3531. for (var index = 0; index < faces.length; index++) {
  3532. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3533. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  3534. }
  3535. if (!noMipmap) {
  3536. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3537. }
  3538. this.setCubeMapTextureParams(gl, !noMipmap);
  3539. texture.width = width;
  3540. texture.height = height;
  3541. texture.isReady = true;
  3542. if (format) {
  3543. texture.format = format;
  3544. }
  3545. texture.onLoadedObservable.notifyObservers(texture);
  3546. texture.onLoadedObservable.clear();
  3547. if (onLoad) {
  3548. onLoad();
  3549. }
  3550. }, files, onError);
  3551. }
  3552. this._internalTexturesCache.push(texture);
  3553. return texture;
  3554. }
  3555. private setCubeMapTextureParams(gl: WebGLRenderingContext, loadMipmap: boolean) {
  3556. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3557. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3558. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3559. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3560. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3561. // this.resetTextureCache();
  3562. }
  3563. public updateRawCubeTexture(texture: InternalTexture, data: ArrayBufferView[], format: number, type: number, invertY: boolean, compression: Nullable<string> = null, level = 0): void {
  3564. texture._bufferViewArray = data;
  3565. texture.format = format;
  3566. texture.type = type;
  3567. texture.invertY = invertY;
  3568. texture._compression = compression;
  3569. var gl = this._gl;
  3570. var textureType = this._getWebGLTextureType(type);
  3571. var internalFormat = this._getInternalFormat(format);
  3572. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  3573. var needConversion = false;
  3574. if (internalFormat === gl.RGB) {
  3575. internalFormat = gl.RGBA;
  3576. needConversion = true;
  3577. }
  3578. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3579. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3580. if (texture.width % 4 !== 0) {
  3581. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  3582. }
  3583. // Data are known to be in +X +Y +Z -X -Y -Z
  3584. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  3585. let faceData = data[faceIndex];
  3586. if (compression) {
  3587. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (<any>(this.getCaps().s3tc))[compression], texture.width, texture.height, 0, faceData);
  3588. } else {
  3589. if (needConversion) {
  3590. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  3591. }
  3592. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  3593. }
  3594. }
  3595. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  3596. if (isPot && texture.generateMipMaps && level === 0) {
  3597. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  3598. }
  3599. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3600. // this.resetTextureCache();
  3601. texture.isReady = true;
  3602. }
  3603. public createRawCubeTexture(data: Nullable<ArrayBufferView[]>, size: number, format: number, type: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null): InternalTexture {
  3604. var gl = this._gl;
  3605. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBERAW);
  3606. texture.isCube = true;
  3607. texture.generateMipMaps = generateMipMaps;
  3608. texture.format = format;
  3609. texture.type = type;
  3610. if (!this._doNotHandleContextLost) {
  3611. texture._bufferViewArray = data;
  3612. }
  3613. var textureType = this._getWebGLTextureType(type);
  3614. var internalFormat = this._getInternalFormat(format);
  3615. if (internalFormat === gl.RGB) {
  3616. internalFormat = gl.RGBA;
  3617. }
  3618. var width = size;
  3619. var height = width;
  3620. texture.width = width;
  3621. texture.height = height;
  3622. // Double check on POT to generate Mips.
  3623. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  3624. if (!isPot) {
  3625. generateMipMaps = false;
  3626. }
  3627. // Upload data if needed. The texture won't be ready until then.
  3628. if (data) {
  3629. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  3630. }
  3631. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  3632. // Filters
  3633. if (data && generateMipMaps) {
  3634. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  3635. }
  3636. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  3637. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3638. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3639. }
  3640. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  3641. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3642. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3643. }
  3644. else {
  3645. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3646. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  3647. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  3648. }
  3649. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3650. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3651. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3652. return texture;
  3653. }
  3654. public createRawCubeTextureFromUrl(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  3655. callback: (ArrayBuffer: ArrayBuffer) => Nullable<ArrayBufferView[]>,
  3656. mipmmapGenerator: Nullable<((faces: ArrayBufferView[]) => ArrayBufferView[][])>,
  3657. onLoad: Nullable<() => void> = null,
  3658. onError: Nullable<(message?: string, exception?: any) => void> = null,
  3659. samplingMode = Texture.TRILINEAR_SAMPLINGMODE,
  3660. invertY = false): InternalTexture {
  3661. var gl = this._gl;
  3662. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  3663. scene._addPendingData(texture);
  3664. texture.url = url;
  3665. this._internalTexturesCache.push(texture);
  3666. var onerror = (request?: XMLHttpRequest, exception?: any) => {
  3667. scene._removePendingData(texture);
  3668. if (onError && request) {
  3669. onError(request.status + " " + request.statusText, exception);
  3670. }
  3671. };
  3672. var internalCallback = (data: any) => {
  3673. var width = texture.width;
  3674. var faceDataArrays = callback(data);
  3675. if (!faceDataArrays) {
  3676. return;
  3677. }
  3678. if (mipmmapGenerator) {
  3679. var textureType = this._getWebGLTextureType(type);
  3680. var internalFormat = this._getInternalFormat(format);
  3681. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  3682. var needConversion = false;
  3683. if (internalFormat === gl.RGB) {
  3684. internalFormat = gl.RGBA;
  3685. needConversion = true;
  3686. }
  3687. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3688. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3689. var mipData = mipmmapGenerator(faceDataArrays);
  3690. for (var level = 0; level < mipData.length; level++) {
  3691. var mipSize = width >> level;
  3692. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  3693. let mipFaceData = mipData[level][faceIndex];
  3694. if (needConversion) {
  3695. mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  3696. }
  3697. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  3698. }
  3699. }
  3700. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3701. }
  3702. else {
  3703. texture.generateMipMaps = !noMipmap;
  3704. this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  3705. }
  3706. texture.isReady = true;
  3707. // this.resetTextureCache();
  3708. scene._removePendingData(texture);
  3709. if (onLoad) {
  3710. onLoad();
  3711. }
  3712. };
  3713. this._loadFile(url, data => {
  3714. internalCallback(data);
  3715. }, undefined, scene.database, true, onerror);
  3716. return texture;
  3717. };
  3718. public updateRawTexture3D(texture: InternalTexture, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null): void {
  3719. var internalFormat = this._getInternalFormat(format);
  3720. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  3721. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3722. if (!this._doNotHandleContextLost) {
  3723. texture._bufferView = data;
  3724. texture.format = format;
  3725. texture.invertY = invertY;
  3726. texture._compression = compression;
  3727. }
  3728. if (texture.width % 4 !== 0) {
  3729. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  3730. }
  3731. if (compression && data) {
  3732. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, texture.depth, 0, data);
  3733. } else {
  3734. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  3735. }
  3736. if (texture.generateMipMaps) {
  3737. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  3738. }
  3739. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3740. // this.resetTextureCache();
  3741. texture.isReady = true;
  3742. }
  3743. public createRawTexture3D(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null): InternalTexture {
  3744. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW3D);
  3745. texture.baseWidth = width;
  3746. texture.baseHeight = height;
  3747. texture.baseDepth = depth;
  3748. texture.width = width;
  3749. texture.height = height;
  3750. texture.depth = depth;
  3751. texture.format = format;
  3752. texture.generateMipMaps = generateMipMaps;
  3753. texture.samplingMode = samplingMode;
  3754. texture.is3D = true;
  3755. if (!this._doNotHandleContextLost) {
  3756. texture._bufferView = data;
  3757. }
  3758. this.updateRawTexture3D(texture, data, format, invertY, compression);
  3759. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  3760. // Filters
  3761. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3762. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3763. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3764. if (generateMipMaps) {
  3765. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  3766. }
  3767. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3768. this._internalTexturesCache.push(texture);
  3769. return texture;
  3770. }
  3771. private _prepareWebGLTextureContinuation(texture: InternalTexture, scene: Nullable<Scene>, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  3772. var gl = this._gl;
  3773. if (!gl) {
  3774. return;
  3775. }
  3776. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3777. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3778. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3779. if (!noMipmap && !isCompressed) {
  3780. gl.generateMipmap(gl.TEXTURE_2D);
  3781. }
  3782. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  3783. // this.resetTextureCache();
  3784. if (scene) {
  3785. scene._removePendingData(texture);
  3786. }
  3787. texture.onLoadedObservable.notifyObservers(texture);
  3788. texture.onLoadedObservable.clear();
  3789. }
  3790. private _prepareWebGLTexture(texture: InternalTexture, scene: Nullable<Scene>, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  3791. processFunction: (width: number, height: number, continuationCallback: () => void) => boolean, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE): void {
  3792. var potWidth = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  3793. var potHeight = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  3794. var gl = this._gl;
  3795. if (!gl) {
  3796. return;
  3797. }
  3798. if (!texture._webGLTexture) {
  3799. // this.resetTextureCache();
  3800. if (scene) {
  3801. scene._removePendingData(texture);
  3802. }
  3803. return;
  3804. }
  3805. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  3806. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3807. texture.baseWidth = width;
  3808. texture.baseHeight = height;
  3809. texture.width = potWidth;
  3810. texture.height = potHeight;
  3811. texture.isReady = true;
  3812. if (processFunction(potWidth, potHeight, () => {
  3813. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  3814. })) {
  3815. // Returning as texture needs extra async steps
  3816. return;
  3817. }
  3818. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  3819. }
  3820. private _convertRGBtoRGBATextureData(rgbData: any, width: number, height: number, textureType: number): ArrayBufferView {
  3821. // Create new RGBA data container.
  3822. var rgbaData: any;
  3823. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  3824. rgbaData = new Float32Array(width * height * 4);
  3825. }
  3826. else {
  3827. rgbaData = new Uint32Array(width * height * 4);
  3828. }
  3829. // Convert each pixel.
  3830. for (let x = 0; x < width; x++) {
  3831. for (let y = 0; y < height; y++) {
  3832. let index = (y * width + x) * 3;
  3833. let newIndex = (y * width + x) * 4;
  3834. // Map Old Value to new value.
  3835. rgbaData[newIndex + 0] = rgbData[index + 0];
  3836. rgbaData[newIndex + 1] = rgbData[index + 1];
  3837. rgbaData[newIndex + 2] = rgbData[index + 2];
  3838. // Add fully opaque alpha channel.
  3839. rgbaData[newIndex + 3] = 1;
  3840. }
  3841. }
  3842. return rgbaData;
  3843. }
  3844. public _releaseFramebufferObjects(texture: InternalTexture): void {
  3845. var gl = this._gl;
  3846. if (texture._framebuffer) {
  3847. gl.deleteFramebuffer(texture._framebuffer);
  3848. texture._framebuffer = null;
  3849. }
  3850. if (texture._depthStencilBuffer) {
  3851. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  3852. texture._depthStencilBuffer = null;
  3853. }
  3854. if (texture._MSAAFramebuffer) {
  3855. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  3856. texture._MSAAFramebuffer = null;
  3857. }
  3858. if (texture._MSAARenderBuffer) {
  3859. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  3860. texture._MSAARenderBuffer = null;
  3861. }
  3862. }
  3863. public _releaseTexture(texture: InternalTexture): void {
  3864. var gl = this._gl;
  3865. this._releaseFramebufferObjects(texture);
  3866. gl.deleteTexture(texture._webGLTexture);
  3867. // Unbind channels
  3868. this.unbindAllTextures();
  3869. var index = this._internalTexturesCache.indexOf(texture);
  3870. if (index !== -1) {
  3871. this._internalTexturesCache.splice(index, 1);
  3872. }
  3873. // Integrated fixed lod samplers.
  3874. if (texture._lodTextureHigh) {
  3875. texture._lodTextureHigh.dispose();
  3876. }
  3877. if (texture._lodTextureMid) {
  3878. texture._lodTextureMid.dispose();
  3879. }
  3880. if (texture._lodTextureLow) {
  3881. texture._lodTextureLow.dispose();
  3882. }
  3883. }
  3884. private setProgram(program: WebGLProgram): void {
  3885. if (this._currentProgram !== program) {
  3886. this._gl.useProgram(program);
  3887. this._currentProgram = program;
  3888. }
  3889. }
  3890. private _boundUniforms: { [key: number]: WebGLUniformLocation } = {};
  3891. public bindSamplers(effect: Effect): void {
  3892. this.setProgram(effect.getProgram());
  3893. var samplers = effect.getSamplers();
  3894. for (var index = 0; index < samplers.length; index++) {
  3895. var uniform = effect.getUniform(samplers[index]);
  3896. if (uniform) {
  3897. this._boundUniforms[index] = uniform;
  3898. }
  3899. }
  3900. this._currentEffect = null;
  3901. }
  3902. private _moveBoundTextureOnTop(internalTexture: InternalTexture): void {
  3903. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  3904. return;
  3905. }
  3906. // Remove
  3907. this._linkTrackers(internalTexture.previous, internalTexture.next);
  3908. // Bind last to it
  3909. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  3910. // Bind to dummy
  3911. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  3912. }
  3913. private _getCorrectTextureChannel(channel: number, internalTexture: Nullable<InternalTexture>): number {
  3914. if (!internalTexture) {
  3915. return -1;
  3916. }
  3917. internalTexture._initialSlot = channel;
  3918. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  3919. if (channel !== internalTexture._designatedSlot) {
  3920. this._textureCollisions.addCount(1, false);
  3921. }
  3922. } else {
  3923. if (channel !== internalTexture._designatedSlot) {
  3924. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  3925. return internalTexture._designatedSlot;
  3926. } else {
  3927. // No slot for this texture, let's pick a new one (if we find a free slot)
  3928. if (this._nextFreeTextureSlots.length) {
  3929. return this._nextFreeTextureSlots[0];
  3930. }
  3931. // We need to recycle the oldest bound texture, sorry.
  3932. this._textureCollisions.addCount(1, false);
  3933. return this._removeDesignatedSlot(<InternalTexture>this._firstBoundInternalTextureTracker.next);
  3934. }
  3935. }
  3936. }
  3937. return channel;
  3938. }
  3939. private _linkTrackers(previous: Nullable<IInternalTextureTracker>, next: Nullable<IInternalTextureTracker>) {
  3940. previous!.next = next;
  3941. next!.previous = previous;
  3942. }
  3943. private _removeDesignatedSlot(internalTexture: InternalTexture): number {
  3944. let currentSlot = internalTexture._designatedSlot;
  3945. if (currentSlot === -1) {
  3946. return -1;
  3947. }
  3948. internalTexture._designatedSlot = -1;
  3949. if (this.disableTextureBindingOptimization) {
  3950. return -1;
  3951. }
  3952. // Remove from bound list
  3953. this._linkTrackers(internalTexture.previous, internalTexture.next);
  3954. // Free the slot
  3955. this._boundTexturesCache[currentSlot] = null;
  3956. this._nextFreeTextureSlots.push(currentSlot);
  3957. return currentSlot;
  3958. }
  3959. private _activateCurrentTexture() {
  3960. if (this._currentTextureChannel !== this._activeChannel) {
  3961. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  3962. this._currentTextureChannel = this._activeChannel;
  3963. }
  3964. }
  3965. protected _bindTextureDirectly(target: number, texture: Nullable<InternalTexture>, forTextureDataUpdate = false): void {
  3966. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  3967. this._activeChannel = texture._designatedSlot;
  3968. }
  3969. let currentTextureBound = this._boundTexturesCache[this._activeChannel];
  3970. let isTextureForRendering = texture && texture._initialSlot > -1;
  3971. if (currentTextureBound !== texture) {
  3972. if (currentTextureBound) {
  3973. this._removeDesignatedSlot(currentTextureBound);
  3974. }
  3975. this._activateCurrentTexture();
  3976. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  3977. this._boundTexturesCache[this._activeChannel] = texture;
  3978. if (texture) {
  3979. if (!this.disableTextureBindingOptimization) {
  3980. let slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  3981. if (slotIndex > -1) {
  3982. this._nextFreeTextureSlots.splice(slotIndex, 1);
  3983. }
  3984. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  3985. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  3986. }
  3987. texture._designatedSlot = this._activeChannel;
  3988. }
  3989. } else if (forTextureDataUpdate) {
  3990. this._activateCurrentTexture();
  3991. }
  3992. if (isTextureForRendering && !forTextureDataUpdate) {
  3993. this._bindSamplerUniformToChannel(texture!._initialSlot, this._activeChannel);
  3994. }
  3995. }
  3996. public _bindTexture(channel: number, texture: Nullable<InternalTexture>): void {
  3997. if (channel < 0) {
  3998. return;
  3999. }
  4000. if (texture) {
  4001. channel = this._getCorrectTextureChannel(channel, texture);
  4002. }
  4003. this._activeChannel = channel;
  4004. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  4005. }
  4006. public setTextureFromPostProcess(channel: number, postProcess: Nullable<PostProcess>): void {
  4007. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  4008. }
  4009. public unbindAllTextures(): void {
  4010. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  4011. this._activeChannel = channel;
  4012. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  4013. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  4014. if (this.webGLVersion > 1) {
  4015. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  4016. }
  4017. }
  4018. }
  4019. public setTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>): void {
  4020. if (channel < 0) {
  4021. return;
  4022. }
  4023. if (uniform) {
  4024. this._boundUniforms[channel] = uniform;
  4025. }
  4026. this._setTexture(channel, texture);
  4027. }
  4028. private _bindSamplerUniformToChannel(sourceSlot: number, destination: number) {
  4029. let uniform = this._boundUniforms[sourceSlot];
  4030. if (uniform._currentState === destination) {
  4031. return;
  4032. }
  4033. this._gl.uniform1i(uniform, destination);
  4034. uniform._currentState = destination;
  4035. }
  4036. private _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false): boolean {
  4037. // Not ready?
  4038. if (!texture) {
  4039. if (this._boundTexturesCache[channel] != null) {
  4040. this._activeChannel = channel;
  4041. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  4042. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  4043. if (this.webGLVersion > 1) {
  4044. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  4045. }
  4046. }
  4047. return false;
  4048. }
  4049. // Video
  4050. if ((<VideoTexture>texture).video) {
  4051. this._activeChannel = channel;
  4052. (<VideoTexture>texture).update();
  4053. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  4054. texture.delayLoad();
  4055. return false;
  4056. }
  4057. let internalTexture: InternalTexture;
  4058. if (texture.isReady()) {
  4059. internalTexture = <InternalTexture>texture.getInternalTexture();
  4060. }
  4061. else if (texture.isCube) {
  4062. internalTexture = this.emptyCubeTexture;
  4063. }
  4064. else if (texture.is3D) {
  4065. internalTexture = this.emptyTexture3D;
  4066. }
  4067. else {
  4068. internalTexture = this.emptyTexture;
  4069. }
  4070. if (!isPartOfTextureArray) {
  4071. channel = this._getCorrectTextureChannel(channel, internalTexture);
  4072. }
  4073. if (this._boundTexturesCache[channel] === internalTexture) {
  4074. this._moveBoundTextureOnTop(internalTexture);
  4075. if (!isPartOfTextureArray) {
  4076. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  4077. }
  4078. return false;
  4079. }
  4080. this._activeChannel = channel;
  4081. if (internalTexture && internalTexture.is3D) {
  4082. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  4083. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  4084. internalTexture._cachedWrapU = texture.wrapU;
  4085. switch (texture.wrapU) {
  4086. case Texture.WRAP_ADDRESSMODE:
  4087. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4088. break;
  4089. case Texture.CLAMP_ADDRESSMODE:
  4090. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4091. break;
  4092. case Texture.MIRROR_ADDRESSMODE:
  4093. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4094. break;
  4095. }
  4096. }
  4097. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  4098. internalTexture._cachedWrapV = texture.wrapV;
  4099. switch (texture.wrapV) {
  4100. case Texture.WRAP_ADDRESSMODE:
  4101. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4102. break;
  4103. case Texture.CLAMP_ADDRESSMODE:
  4104. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4105. break;
  4106. case Texture.MIRROR_ADDRESSMODE:
  4107. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4108. break;
  4109. }
  4110. }
  4111. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  4112. internalTexture._cachedWrapR = texture.wrapR;
  4113. switch (texture.wrapR) {
  4114. case Texture.WRAP_ADDRESSMODE:
  4115. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  4116. break;
  4117. case Texture.CLAMP_ADDRESSMODE:
  4118. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  4119. break;
  4120. case Texture.MIRROR_ADDRESSMODE:
  4121. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  4122. break;
  4123. }
  4124. }
  4125. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  4126. }
  4127. else if (internalTexture && internalTexture.isCube) {
  4128. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  4129. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4130. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4131. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4132. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4133. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4134. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4135. }
  4136. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4137. } else {
  4138. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  4139. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  4140. internalTexture._cachedWrapU = texture.wrapU;
  4141. switch (texture.wrapU) {
  4142. case Texture.WRAP_ADDRESSMODE:
  4143. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4144. break;
  4145. case Texture.CLAMP_ADDRESSMODE:
  4146. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4147. break;
  4148. case Texture.MIRROR_ADDRESSMODE:
  4149. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4150. break;
  4151. }
  4152. }
  4153. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  4154. internalTexture._cachedWrapV = texture.wrapV;
  4155. switch (texture.wrapV) {
  4156. case Texture.WRAP_ADDRESSMODE:
  4157. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4158. break;
  4159. case Texture.CLAMP_ADDRESSMODE:
  4160. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4161. break;
  4162. case Texture.MIRROR_ADDRESSMODE:
  4163. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4164. break;
  4165. }
  4166. }
  4167. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4168. }
  4169. return true;
  4170. }
  4171. public setTextureArray(channel: number, uniform: Nullable<WebGLUniformLocation>, textures: BaseTexture[]): void {
  4172. if (channel < 0 || !uniform) {
  4173. return;
  4174. }
  4175. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  4176. this._textureUnits = new Int32Array(textures.length);
  4177. }
  4178. for (let i = 0; i < textures.length; i++) {
  4179. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  4180. }
  4181. this._gl.uniform1iv(uniform, this._textureUnits);
  4182. for (var index = 0; index < textures.length; index++) {
  4183. this._setTexture(this._textureUnits[index], textures[index], true);
  4184. }
  4185. }
  4186. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  4187. var internalTexture = texture.getInternalTexture();
  4188. if (!internalTexture) {
  4189. return;
  4190. }
  4191. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4192. var value = texture.anisotropicFilteringLevel;
  4193. if (internalTexture.samplingMode !== Texture.LINEAR_LINEAR_MIPNEAREST
  4194. && internalTexture.samplingMode !== Texture.LINEAR_LINEAR_MIPLINEAR
  4195. && internalTexture.samplingMode !== Texture.LINEAR_LINEAR) {
  4196. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  4197. }
  4198. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  4199. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  4200. internalTexture._cachedAnisotropicFilteringLevel = value;
  4201. }
  4202. }
  4203. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  4204. var data = new Uint8Array(height * width * 4);
  4205. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4206. return data;
  4207. }
  4208. /**
  4209. * Add an externaly attached data from its key.
  4210. * This method call will fail and return false, if such key already exists.
  4211. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  4212. * @param key the unique key that identifies the data
  4213. * @param data the data object to associate to the key for this Engine instance
  4214. * @return true if no such key were already present and the data was added successfully, false otherwise
  4215. */
  4216. public addExternalData<T>(key: string, data: T): boolean {
  4217. if (!this._externalData) {
  4218. this._externalData = new StringDictionary<Object>();
  4219. }
  4220. return this._externalData.add(key, data);
  4221. }
  4222. /**
  4223. * Get an externaly attached data from its key
  4224. * @param key the unique key that identifies the data
  4225. * @return the associated data, if present (can be null), or undefined if not present
  4226. */
  4227. public getExternalData<T>(key: string): T {
  4228. if (!this._externalData) {
  4229. this._externalData = new StringDictionary<Object>();
  4230. }
  4231. return <T>this._externalData.get(key);
  4232. }
  4233. /**
  4234. * Get an externaly attached data from its key, create it using a factory if it's not already present
  4235. * @param key the unique key that identifies the data
  4236. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  4237. * @return the associated data, can be null if the factory returned null.
  4238. */
  4239. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  4240. if (!this._externalData) {
  4241. this._externalData = new StringDictionary<Object>();
  4242. }
  4243. return <T>this._externalData.getOrAddWithFactory(key, factory);
  4244. }
  4245. /**
  4246. * Remove an externaly attached data from the Engine instance
  4247. * @param key the unique key that identifies the data
  4248. * @return true if the data was successfully removed, false if it doesn't exist
  4249. */
  4250. public removeExternalData(key: string): boolean {
  4251. if (!this._externalData) {
  4252. this._externalData = new StringDictionary<Object>();
  4253. }
  4254. return this._externalData.remove(key);
  4255. }
  4256. public unbindAllAttributes() {
  4257. if (this._mustWipeVertexAttributes) {
  4258. this._mustWipeVertexAttributes = false;
  4259. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  4260. this._gl.disableVertexAttribArray(i);
  4261. this._vertexAttribArraysEnabled[i] = false;
  4262. this._currentBufferPointers[i].active = false;
  4263. }
  4264. return;
  4265. }
  4266. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  4267. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  4268. continue;
  4269. }
  4270. this._gl.disableVertexAttribArray(i);
  4271. this._vertexAttribArraysEnabled[i] = false;
  4272. this._currentBufferPointers[i].active = false;
  4273. }
  4274. }
  4275. public releaseEffects() {
  4276. for (var name in this._compiledEffects) {
  4277. this._deleteProgram(this._compiledEffects[name]._program)
  4278. }
  4279. this._compiledEffects = {};
  4280. }
  4281. // Dispose
  4282. public dispose(): void {
  4283. this.hideLoadingUI();
  4284. this.stopRenderLoop();
  4285. // Release postProcesses
  4286. while (this.postProcesses.length) {
  4287. this.postProcesses[0].dispose();
  4288. }
  4289. // Empty texture
  4290. if (this._emptyTexture) {
  4291. this._releaseTexture(this._emptyTexture);
  4292. this._emptyTexture = null;
  4293. }
  4294. if (this._emptyCubeTexture) {
  4295. this._releaseTexture(this._emptyCubeTexture);
  4296. this._emptyCubeTexture = null;
  4297. }
  4298. // Rescale PP
  4299. if (this._rescalePostProcess) {
  4300. this._rescalePostProcess.dispose();
  4301. }
  4302. // Release scenes
  4303. while (this.scenes.length) {
  4304. this.scenes[0].dispose();
  4305. }
  4306. // Release audio engine
  4307. if (Engine.audioEngine) {
  4308. Engine.audioEngine.dispose();
  4309. }
  4310. // Release effects
  4311. this.releaseEffects();
  4312. // Unbind
  4313. this.unbindAllAttributes();
  4314. if (this._dummyFramebuffer) {
  4315. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  4316. }
  4317. //WebVR
  4318. this.disableVR();
  4319. // Events
  4320. if (Tools.IsWindowObjectExist()) {
  4321. window.removeEventListener("blur", this._onBlur);
  4322. window.removeEventListener("focus", this._onFocus);
  4323. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  4324. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  4325. if (this._renderingCanvas) {
  4326. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  4327. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  4328. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  4329. if (!this._doNotHandleContextLost) {
  4330. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  4331. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  4332. }
  4333. }
  4334. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4335. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4336. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4337. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4338. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4339. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4340. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4341. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4342. if (this._onVrDisplayConnect) {
  4343. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  4344. if (this._onVrDisplayDisconnect) {
  4345. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  4346. }
  4347. if (this._onVrDisplayPresentChange) {
  4348. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  4349. }
  4350. this._onVrDisplayConnect = null;
  4351. this._onVrDisplayDisconnect = null;
  4352. }
  4353. }
  4354. // Remove from Instances
  4355. var index = Engine.Instances.indexOf(this);
  4356. if (index >= 0) {
  4357. Engine.Instances.splice(index, 1);
  4358. }
  4359. this._workingCanvas = null;
  4360. this._workingContext = null;
  4361. this._currentBufferPointers = [];
  4362. this._renderingCanvas = null;
  4363. this._currentProgram = null;
  4364. this.onResizeObservable.clear();
  4365. this.onCanvasBlurObservable.clear();
  4366. this.onCanvasFocusObservable.clear();
  4367. this.onCanvasPointerOutObservable.clear();
  4368. this.onBeginFrameObservable.clear();
  4369. this.onEndFrameObservable.clear();
  4370. Effect.ResetCache();
  4371. // Abort active requests
  4372. for (let request of this._activeRequests) {
  4373. request.abort();
  4374. }
  4375. }
  4376. // Loading screen
  4377. public displayLoadingUI(): void {
  4378. if (!Tools.IsWindowObjectExist()) {
  4379. return;
  4380. }
  4381. const loadingScreen = this.loadingScreen;
  4382. if (loadingScreen) {
  4383. loadingScreen.displayLoadingUI();
  4384. }
  4385. }
  4386. public hideLoadingUI(): void {
  4387. if (!Tools.IsWindowObjectExist()) {
  4388. return;
  4389. }
  4390. const loadingScreen = this.loadingScreen;
  4391. if (loadingScreen) {
  4392. loadingScreen.hideLoadingUI();
  4393. }
  4394. }
  4395. public get loadingScreen(): ILoadingScreen {
  4396. if (!this._loadingScreen && DefaultLoadingScreen && this._renderingCanvas)
  4397. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas)
  4398. return this._loadingScreen;
  4399. }
  4400. public set loadingScreen(loadingScreen: ILoadingScreen) {
  4401. this._loadingScreen = loadingScreen;
  4402. }
  4403. public set loadingUIText(text: string) {
  4404. this.loadingScreen.loadingUIText = text;
  4405. }
  4406. public set loadingUIBackgroundColor(color: string) {
  4407. this.loadingScreen.loadingUIBackgroundColor = color;
  4408. }
  4409. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  4410. if (this._renderingCanvas) {
  4411. this._renderingCanvas.addEventListener("webglcontextlost", <any>callback, false);
  4412. }
  4413. }
  4414. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  4415. if (this._renderingCanvas) {
  4416. this._renderingCanvas.addEventListener("webglcontextrestored", <any>callback, false);
  4417. }
  4418. }
  4419. public getVertexShaderSource(program: WebGLProgram): Nullable<string> {
  4420. var shaders = this._gl.getAttachedShaders(program);
  4421. if (!shaders) {
  4422. return null;
  4423. }
  4424. return this._gl.getShaderSource(shaders[0]);
  4425. }
  4426. public getFragmentShaderSource(program: WebGLProgram): Nullable<string> {
  4427. var shaders = this._gl.getAttachedShaders(program);
  4428. if (!shaders) {
  4429. return null;
  4430. }
  4431. return this._gl.getShaderSource(shaders[1]);
  4432. }
  4433. public getError(): number {
  4434. return this._gl.getError();
  4435. }
  4436. // FPS
  4437. public getFps(): number {
  4438. return this._fps;
  4439. }
  4440. public getDeltaTime(): number {
  4441. return this._deltaTime;
  4442. }
  4443. private _measureFps(): void {
  4444. this._performanceMonitor.sampleFrame();
  4445. this._fps = this._performanceMonitor.averageFPS;
  4446. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  4447. }
  4448. public _readTexturePixels(texture: InternalTexture, width: number, height: number, faceIndex = -1): ArrayBufferView {
  4449. let gl = this._gl;
  4450. if (!this._dummyFramebuffer) {
  4451. let dummy = gl.createFramebuffer();
  4452. if (!dummy) {
  4453. throw new Error("Unable to create dummy framebuffer");
  4454. }
  4455. this._dummyFramebuffer = dummy;
  4456. }
  4457. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  4458. if (faceIndex > -1) {
  4459. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  4460. } else {
  4461. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  4462. }
  4463. let readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  4464. let buffer: ArrayBufferView;
  4465. switch (readType) {
  4466. case gl.UNSIGNED_BYTE:
  4467. buffer = new Uint8Array(4 * width * height);
  4468. readType = gl.UNSIGNED_BYTE;
  4469. break;
  4470. default:
  4471. buffer = new Float32Array(4 * width * height);
  4472. readType = gl.FLOAT;
  4473. break;
  4474. }
  4475. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  4476. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  4477. return buffer;
  4478. }
  4479. private _canRenderToFloatFramebuffer(): boolean {
  4480. if (this._webGLVersion > 1) {
  4481. return this._caps.colorBufferFloat;
  4482. }
  4483. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  4484. }
  4485. private _canRenderToHalfFloatFramebuffer(): boolean {
  4486. if (this._webGLVersion > 1) {
  4487. return this._caps.colorBufferFloat;
  4488. }
  4489. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  4490. }
  4491. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  4492. private _canRenderToFramebuffer(type: number): boolean {
  4493. let gl = this._gl;
  4494. //clear existing errors
  4495. while (gl.getError() !== gl.NO_ERROR) { }
  4496. let successful = true;
  4497. let texture = gl.createTexture();
  4498. gl.bindTexture(gl.TEXTURE_2D, texture);
  4499. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  4500. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4501. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4502. let fb = gl.createFramebuffer();
  4503. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  4504. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4505. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  4506. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  4507. successful = successful && (gl.getError() === gl.NO_ERROR);
  4508. //try render by clearing frame buffer's color buffer
  4509. if (successful) {
  4510. gl.clear(gl.COLOR_BUFFER_BIT);
  4511. successful = successful && (gl.getError() === gl.NO_ERROR);
  4512. }
  4513. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  4514. if (successful) {
  4515. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  4516. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4517. let readFormat = gl.RGBA;
  4518. let readType = gl.UNSIGNED_BYTE;
  4519. let buffer = new Uint8Array(4);
  4520. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  4521. successful = successful && (gl.getError() === gl.NO_ERROR);
  4522. }
  4523. //clean up
  4524. gl.deleteTexture(texture);
  4525. gl.deleteFramebuffer(fb);
  4526. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4527. //clear accumulated errors
  4528. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  4529. return successful;
  4530. }
  4531. public _getWebGLTextureType(type: number): number {
  4532. if (type === Engine.TEXTURETYPE_FLOAT) {
  4533. return this._gl.FLOAT;
  4534. }
  4535. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  4536. // Add Half Float Constant.
  4537. return this._gl.HALF_FLOAT_OES;
  4538. }
  4539. return this._gl.UNSIGNED_BYTE;
  4540. };
  4541. /** @ignore */
  4542. public _getRGBABufferInternalSizedFormat(type: number, format?: number): number {
  4543. if (this._webGLVersion === 1) {
  4544. return this._gl.RGBA;
  4545. }
  4546. if (type === Engine.TEXTURETYPE_FLOAT) {
  4547. if (format) {
  4548. switch(format) {
  4549. case Engine.TEXTUREFORMAT_R32F:
  4550. return this._gl.R32F;
  4551. case Engine.TEXTUREFORMAT_RG32F:
  4552. return this._gl.RG32F;
  4553. case Engine.TEXTUREFORMAT_RGB32F:
  4554. return this._gl.RGB32F;
  4555. }
  4556. }
  4557. return this._gl.RGBA32F;
  4558. }
  4559. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  4560. return this._gl.RGBA16F;
  4561. }
  4562. return this._gl.RGBA;
  4563. };
  4564. public _getRGBAMultiSampleBufferFormat(type: number): number {
  4565. if (type === Engine.TEXTURETYPE_FLOAT) {
  4566. return this._gl.RGBA32F;
  4567. }
  4568. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  4569. return this._gl.RGBA16F;
  4570. }
  4571. return this._gl.RGBA8;
  4572. };
  4573. public createQuery(): WebGLQuery {
  4574. return this._gl.createQuery();
  4575. }
  4576. public deleteQuery(query: WebGLQuery): Engine {
  4577. this._gl.deleteQuery(query);
  4578. return this;
  4579. }
  4580. public isQueryResultAvailable(query: WebGLQuery): boolean {
  4581. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE) as boolean;
  4582. }
  4583. public getQueryResult(query: WebGLQuery): number {
  4584. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT) as number;
  4585. }
  4586. public beginOcclusionQuery(algorithmType: number, query: WebGLQuery): Engine {
  4587. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  4588. this._gl.beginQuery(glAlgorithm, query);
  4589. return this;
  4590. }
  4591. public endOcclusionQuery(algorithmType: number): Engine {
  4592. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  4593. this._gl.endQuery(glAlgorithm);
  4594. return this;
  4595. }
  4596. /* Time queries */
  4597. private _createTimeQuery(): WebGLQuery {
  4598. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  4599. if (timerQuery.createQueryEXT) {
  4600. return timerQuery.createQueryEXT();
  4601. }
  4602. return this.createQuery();
  4603. }
  4604. private _deleteTimeQuery(query: WebGLQuery): void {
  4605. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  4606. if (timerQuery.deleteQueryEXT) {
  4607. timerQuery.deleteQueryEXT(query);
  4608. return;
  4609. }
  4610. this.deleteQuery(query);
  4611. }
  4612. private _getTimeQueryResult(query: WebGLQuery): any {
  4613. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  4614. if (timerQuery.getQueryObjectEXT) {
  4615. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  4616. }
  4617. return this.getQueryResult(query);
  4618. }
  4619. private _getTimeQueryAvailability(query: WebGLQuery): any {
  4620. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  4621. if (timerQuery.getQueryObjectEXT) {
  4622. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  4623. }
  4624. return this.isQueryResultAvailable(query);
  4625. }
  4626. private _currentNonTimestampToken: Nullable<_TimeToken>;
  4627. public startTimeQuery(): Nullable<_TimeToken> {
  4628. let timerQuery = this._caps.timerQuery;
  4629. if (!timerQuery) {
  4630. return null;
  4631. }
  4632. let token = new _TimeToken();
  4633. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  4634. if (this._caps.canUseTimestampForTimerQuery) {
  4635. token._startTimeQuery = this._createTimeQuery();
  4636. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  4637. } else {
  4638. if (this._currentNonTimestampToken) {
  4639. return this._currentNonTimestampToken;
  4640. }
  4641. token._timeElapsedQuery = this._createTimeQuery();
  4642. if (timerQuery.beginQueryEXT) {
  4643. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  4644. } else {
  4645. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  4646. }
  4647. this._currentNonTimestampToken = token;
  4648. }
  4649. return token;
  4650. }
  4651. public endTimeQuery(token: _TimeToken): int {
  4652. let timerQuery = this._caps.timerQuery;
  4653. if (!timerQuery || !token) {
  4654. return -1;
  4655. }
  4656. if (this._caps.canUseTimestampForTimerQuery) {
  4657. if (!token._startTimeQuery) {
  4658. return -1;
  4659. }
  4660. if (!token._endTimeQuery) {
  4661. token._endTimeQuery = this._createTimeQuery();
  4662. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  4663. }
  4664. } else if (!token._timeElapsedQueryEnded) {
  4665. if (!token._timeElapsedQuery) {
  4666. return -1;
  4667. }
  4668. if (timerQuery.endQueryEXT) {
  4669. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  4670. } else {
  4671. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  4672. }
  4673. token._timeElapsedQueryEnded = true;
  4674. }
  4675. let disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  4676. let available: boolean = false;
  4677. if (token._endTimeQuery) {
  4678. available = this._getTimeQueryAvailability(token._endTimeQuery);
  4679. } else if (token._timeElapsedQuery) {
  4680. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  4681. }
  4682. if (available && !disjoint) {
  4683. let result = 0;
  4684. if (this._caps.canUseTimestampForTimerQuery) {
  4685. if (!token._startTimeQuery || !token._endTimeQuery) {
  4686. return -1;
  4687. }
  4688. let timeStart = this._getTimeQueryResult(token._startTimeQuery);
  4689. let timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  4690. result = timeEnd - timeStart;
  4691. this._deleteTimeQuery(token._startTimeQuery);
  4692. this._deleteTimeQuery(token._endTimeQuery);
  4693. token._startTimeQuery = null;
  4694. token._endTimeQuery = null;
  4695. } else {
  4696. if (!token._timeElapsedQuery) {
  4697. return -1;
  4698. }
  4699. result = this._getTimeQueryResult(token._timeElapsedQuery);
  4700. this._deleteTimeQuery(token._timeElapsedQuery);
  4701. token._timeElapsedQuery = null;
  4702. token._timeElapsedQueryEnded = false;
  4703. this._currentNonTimestampToken = null;
  4704. }
  4705. return result;
  4706. }
  4707. return -1;
  4708. }
  4709. private getGlAlgorithmType(algorithmType: number): number {
  4710. return algorithmType === AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  4711. }
  4712. // Transform feedback
  4713. public createTransformFeedback(): WebGLTransformFeedback {
  4714. return this._gl.createTransformFeedback();
  4715. }
  4716. public deleteTransformFeedback(value: WebGLTransformFeedback): void {
  4717. this._gl.deleteTransformFeedback(value);
  4718. }
  4719. public bindTransformFeedback(value: Nullable<WebGLTransformFeedback>): void {
  4720. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  4721. }
  4722. public beginTransformFeedback(usePoints: boolean = true): void {
  4723. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  4724. }
  4725. public endTransformFeedback(): void {
  4726. this._gl.endTransformFeedback();
  4727. }
  4728. public setTranformFeedbackVaryings(program: WebGLProgram, value: string[]): void {
  4729. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  4730. }
  4731. public bindTransformFeedbackBuffer(value: Nullable<WebGLBuffer>): void {
  4732. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  4733. }
  4734. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, database?: Database, useArrayBuffer?: boolean, onError?: (request?: XMLHttpRequest, exception?: any) => void): IFileRequest {
  4735. let request = Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  4736. this._activeRequests.push(request);
  4737. request.onCompleteObservable.add(request => {
  4738. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  4739. });
  4740. return request;
  4741. }
  4742. /** @ignore */
  4743. public _loadFileAsync(url: string, database?: Database, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  4744. return new Promise((resolve, reject) => {
  4745. this._loadFile(url, (data) => {
  4746. resolve(data);
  4747. }, undefined, database, useArrayBuffer, (request, exception) => {
  4748. reject(exception);
  4749. })
  4750. });
  4751. }
  4752. private _partialLoadFile(url: string, index: number, loadedFiles: (string | ArrayBuffer)[], scene: Nullable<Scene>, onfinish: (files: (string | ArrayBuffer)[]) => void, onErrorCallBack: Nullable<(message?: string, exception?: any) => void> = null): void {
  4753. var onload = (data: string | ArrayBuffer) => {
  4754. loadedFiles[index] = data;
  4755. (<any>loadedFiles)._internalCount++;
  4756. if ((<any>loadedFiles)._internalCount === 6) {
  4757. onfinish(loadedFiles);
  4758. }
  4759. };
  4760. const onerror = (request?: XMLHttpRequest, exception?: any) => {
  4761. if (onErrorCallBack && request) {
  4762. onErrorCallBack(request.status + " " + request.statusText, exception);
  4763. }
  4764. };
  4765. this._loadFile(url, onload, undefined, undefined, true, onerror);
  4766. }
  4767. private _cascadeLoadFiles(scene: Nullable<Scene>, onfinish: (images: (string | ArrayBuffer)[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null): void {
  4768. var loadedFiles: (string | ArrayBuffer)[] = [];
  4769. (<any>loadedFiles)._internalCount = 0;
  4770. for (let index = 0; index < 6; index++) {
  4771. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  4772. }
  4773. }
  4774. // Statics
  4775. public static isSupported(): boolean {
  4776. try {
  4777. var tempcanvas = document.createElement("canvas");
  4778. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4779. return gl != null && !!window.WebGLRenderingContext;
  4780. } catch (e) {
  4781. return false;
  4782. }
  4783. }
  4784. }
  4785. }