babylon.engine.ts 185 KB

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