babylon.engine.ts 247 KB

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