babylon.engine.ts 227 KB

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