babylon.engine.ts 203 KB

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