babylon.engine.ts 147 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549
  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. if (samplingMode === Texture.BILINEAR_SAMPLINGMODE) {
  15. magFilter = gl.LINEAR;
  16. if (generateMipMaps) {
  17. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  18. } else {
  19. minFilter = gl.LINEAR;
  20. }
  21. } else if (samplingMode === Texture.TRILINEAR_SAMPLINGMODE) {
  22. magFilter = gl.LINEAR;
  23. if (generateMipMaps) {
  24. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  25. } else {
  26. minFilter = gl.LINEAR;
  27. }
  28. } else if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  29. magFilter = gl.NEAREST;
  30. if (generateMipMaps) {
  31. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  32. } else {
  33. minFilter = gl.NEAREST;
  34. }
  35. }
  36. return {
  37. min: minFilter,
  38. mag: magFilter
  39. }
  40. }
  41. var prepareWebGLTexture = (texture: WebGLTexture, gl: WebGLRenderingContext, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  42. processFunction: (width: number, height: number) => void, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE) => {
  43. var engine = scene.getEngine();
  44. if (!engine) {
  45. return;
  46. }
  47. var potWidth = Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  48. var potHeight = Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  49. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  50. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  51. texture._baseWidth = width;
  52. texture._baseHeight = height;
  53. texture._width = potWidth;
  54. texture._height = potHeight;
  55. texture.isReady = true;
  56. processFunction(potWidth, potHeight);
  57. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  58. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  59. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  60. if (!noMipmap && !isCompressed) {
  61. gl.generateMipmap(gl.TEXTURE_2D);
  62. }
  63. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  64. engine.resetTextureCache();
  65. scene._removePendingData(texture);
  66. texture.onLoadedCallbacks.forEach(callback => {
  67. callback();
  68. });
  69. texture.onLoadedCallbacks = [];
  70. };
  71. var partialLoad = (url: string, index: number, loadedImages: any, scene,
  72. onfinish: (images: HTMLImageElement[]) => void, onErrorCallBack: () => void = null) => {
  73. var img: HTMLImageElement;
  74. var onload = () => {
  75. loadedImages[index] = img;
  76. loadedImages._internalCount++;
  77. scene._removePendingData(img);
  78. if (loadedImages._internalCount === 6) {
  79. onfinish(loadedImages);
  80. }
  81. };
  82. var onerror = () => {
  83. scene._removePendingData(img);
  84. if (onErrorCallBack) {
  85. onErrorCallBack();
  86. }
  87. };
  88. img = Tools.LoadImage(url, onload, onerror, scene.database);
  89. scene._addPendingData(img);
  90. }
  91. var cascadeLoad = (rootUrl: string, scene,
  92. onfinish: (images: HTMLImageElement[]) => void, files: string[], onError: () => void = null) => {
  93. var loadedImages: any = [];
  94. loadedImages._internalCount = 0;
  95. for (var index = 0; index < 6; index++) {
  96. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  97. }
  98. };
  99. export class InstancingAttributeInfo {
  100. /**
  101. * Index/offset of the attribute in the vertex shader
  102. */
  103. index: number;
  104. /**
  105. * size of the attribute, 1, 2, 3 or 4
  106. */
  107. attributeSize: number;
  108. /**
  109. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  110. * default is FLOAT
  111. */
  112. attribyteType: number;
  113. /**
  114. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  115. */
  116. normalized: boolean;
  117. /**
  118. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  119. */
  120. offset: number;
  121. /**
  122. * Name of the GLSL attribute, for debugging purpose only
  123. */
  124. attributeName: string;
  125. }
  126. export class EngineCapabilities {
  127. public maxTexturesImageUnits: number;
  128. public maxVertexTextureImageUnits: number;
  129. public maxTextureSize: number;
  130. public maxCubemapTextureSize: number;
  131. public maxRenderTextureSize: number;
  132. public maxVertexAttribs: number;
  133. public maxVaryingVectors: number;
  134. public maxVertexUniformVectors: number;
  135. public maxFragmentUniformVectors: number;
  136. public standardDerivatives: boolean;
  137. public s3tc: WEBGL_compressed_texture_s3tc;
  138. public pvrtc: any; //WEBGL_compressed_texture_pvrtc;
  139. public etc1: any; //WEBGL_compressed_texture_etc1;
  140. public etc2: any; //WEBGL_compressed_texture_etc;
  141. public astc: any; //WEBGL_compressed_texture_astc;
  142. public textureFloat: boolean;
  143. public vertexArrayObject: boolean;
  144. public textureAnisotropicFilterExtension: EXT_texture_filter_anisotropic;
  145. public maxAnisotropy: number;
  146. public instancedArrays: boolean;
  147. public uintIndices: boolean;
  148. public highPrecisionShaderSupported: boolean;
  149. public fragmentDepthSupported: boolean;
  150. public textureFloatLinearFiltering: boolean;
  151. public textureFloatRender: boolean;
  152. public textureHalfFloat: boolean;
  153. public textureHalfFloatLinearFiltering: boolean;
  154. public textureHalfFloatRender: boolean;
  155. public textureLOD: boolean;
  156. public drawBuffersExtension;
  157. public colorBufferFloat: boolean;
  158. }
  159. export interface EngineOptions extends WebGLContextAttributes {
  160. limitDeviceRatio?: number;
  161. autoEnableWebVR?: boolean;
  162. disableWebGL2Support?: boolean;
  163. audioEngine?: boolean;
  164. }
  165. /**
  166. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  167. */
  168. export class Engine {
  169. public static Instances = new Array<Engine>();
  170. public static get LastCreatedEngine(): Engine {
  171. if (Engine.Instances.length === 0) {
  172. return null;
  173. }
  174. return Engine.Instances[Engine.Instances.length - 1];
  175. }
  176. public static get LastCreatedScene(): Scene {
  177. var lastCreatedEngine = Engine.LastCreatedEngine;
  178. if (!lastCreatedEngine) {
  179. return null;
  180. }
  181. if (lastCreatedEngine.scenes.length === 0) {
  182. return null;
  183. }
  184. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  185. }
  186. /**
  187. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  188. */
  189. public static MarkAllMaterialsAsDirty(flag:number, predicate?: (mat: Material) => boolean): void {
  190. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  191. var engine = Engine.Instances[engineIndex];
  192. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  193. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  194. }
  195. }
  196. }
  197. // Const statics
  198. private static _ALPHA_DISABLE = 0;
  199. private static _ALPHA_ADD = 1;
  200. private static _ALPHA_COMBINE = 2;
  201. private static _ALPHA_SUBTRACT = 3;
  202. private static _ALPHA_MULTIPLY = 4;
  203. private static _ALPHA_MAXIMIZED = 5;
  204. private static _ALPHA_ONEONE = 6;
  205. private static _ALPHA_PREMULTIPLIED = 7;
  206. private static _DELAYLOADSTATE_NONE = 0;
  207. private static _DELAYLOADSTATE_LOADED = 1;
  208. private static _DELAYLOADSTATE_LOADING = 2;
  209. private static _DELAYLOADSTATE_NOTLOADED = 4;
  210. private static _TEXTUREFORMAT_ALPHA = 0;
  211. private static _TEXTUREFORMAT_LUMINANCE = 1;
  212. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  213. private static _TEXTUREFORMAT_RGB = 4;
  214. private static _TEXTUREFORMAT_RGBA = 5;
  215. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  216. private static _TEXTURETYPE_FLOAT = 1;
  217. private static _TEXTURETYPE_HALF_FLOAT = 2;
  218. // Depht or Stencil test Constants.
  219. private static _NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  220. 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.
  221. 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.
  222. 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.
  223. 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.
  224. 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.
  225. 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.
  226. 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.
  227. private static HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  228. private static RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  229. private static RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  230. public static get NEVER(): number {
  231. return Engine._NEVER;
  232. }
  233. public static get ALWAYS(): number {
  234. return Engine._ALWAYS;
  235. }
  236. public static get LESS(): number {
  237. return Engine._LESS;
  238. }
  239. public static get EQUAL(): number {
  240. return Engine._EQUAL;
  241. }
  242. public static get LEQUAL(): number {
  243. return Engine._LEQUAL;
  244. }
  245. public static get GREATER(): number {
  246. return Engine._GREATER;
  247. }
  248. public static get GEQUAL(): number {
  249. return Engine._GEQUAL;
  250. }
  251. public static get NOTEQUAL(): number {
  252. return Engine._NOTEQUAL;
  253. }
  254. // Stencil Actions Constants.
  255. private static _KEEP = 0x1E00;
  256. private static _REPLACE = 0x1E01;
  257. private static _INCR = 0x1E02;
  258. private static _DECR = 0x1E03;
  259. private static _INVERT = 0x150A;
  260. private static _INCR_WRAP = 0x8507;
  261. private static _DECR_WRAP = 0x8508;
  262. public static get KEEP(): number {
  263. return Engine._KEEP;
  264. }
  265. public static get REPLACE(): number {
  266. return Engine._REPLACE;
  267. }
  268. public static get INCR(): number {
  269. return Engine._INCR;
  270. }
  271. public static get DECR(): number {
  272. return Engine._DECR;
  273. }
  274. public static get INVERT(): number {
  275. return Engine._INVERT;
  276. }
  277. public static get INCR_WRAP(): number {
  278. return Engine._INCR_WRAP;
  279. }
  280. public static get DECR_WRAP(): number {
  281. return Engine._DECR_WRAP;
  282. }
  283. public static get ALPHA_DISABLE(): number {
  284. return Engine._ALPHA_DISABLE;
  285. }
  286. public static get ALPHA_ONEONE(): number {
  287. return Engine._ALPHA_ONEONE;
  288. }
  289. public static get ALPHA_ADD(): number {
  290. return Engine._ALPHA_ADD;
  291. }
  292. public static get ALPHA_COMBINE(): number {
  293. return Engine._ALPHA_COMBINE;
  294. }
  295. public static get ALPHA_SUBTRACT(): number {
  296. return Engine._ALPHA_SUBTRACT;
  297. }
  298. public static get ALPHA_MULTIPLY(): number {
  299. return Engine._ALPHA_MULTIPLY;
  300. }
  301. public static get ALPHA_MAXIMIZED(): number {
  302. return Engine._ALPHA_MAXIMIZED;
  303. }
  304. public static get ALPHA_PREMULTIPLIED(): number {
  305. return Engine._ALPHA_PREMULTIPLIED;
  306. }
  307. public static get DELAYLOADSTATE_NONE(): number {
  308. return Engine._DELAYLOADSTATE_NONE;
  309. }
  310. public static get DELAYLOADSTATE_LOADED(): number {
  311. return Engine._DELAYLOADSTATE_LOADED;
  312. }
  313. public static get DELAYLOADSTATE_LOADING(): number {
  314. return Engine._DELAYLOADSTATE_LOADING;
  315. }
  316. public static get DELAYLOADSTATE_NOTLOADED(): number {
  317. return Engine._DELAYLOADSTATE_NOTLOADED;
  318. }
  319. public static get TEXTUREFORMAT_ALPHA(): number {
  320. return Engine._TEXTUREFORMAT_ALPHA;
  321. }
  322. public static get TEXTUREFORMAT_LUMINANCE(): number {
  323. return Engine._TEXTUREFORMAT_LUMINANCE;
  324. }
  325. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  326. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  327. }
  328. public static get TEXTUREFORMAT_RGB(): number {
  329. return Engine._TEXTUREFORMAT_RGB;
  330. }
  331. public static get TEXTUREFORMAT_RGBA(): number {
  332. return Engine._TEXTUREFORMAT_RGBA;
  333. }
  334. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  335. return Engine._TEXTURETYPE_UNSIGNED_INT;
  336. }
  337. public static get TEXTURETYPE_FLOAT(): number {
  338. return Engine._TEXTURETYPE_FLOAT;
  339. }
  340. public static get TEXTURETYPE_HALF_FLOAT(): number {
  341. return Engine._TEXTURETYPE_HALF_FLOAT;
  342. }
  343. public static get Version(): string {
  344. return "3.0-alpha";
  345. }
  346. // Updatable statics so stick with vars here
  347. public static CollisionsEpsilon = 0.001;
  348. public static CodeRepository = "src/";
  349. public static ShadersRepository = "src/Shaders/";
  350. // Public members
  351. public isFullscreen = false;
  352. public isPointerLock = false;
  353. public cullBackFaces = true;
  354. public renderEvenInBackground = true;
  355. public preventCacheWipeBetweenFrames = false;
  356. // To enable/disable IDB support and avoid XHR on .manifest
  357. public enableOfflineSupport = true;
  358. public scenes = new Array<Scene>();
  359. //WebVR
  360. //The new WebVR uses promises.
  361. //this promise resolves with the current devices available.
  362. public vrDisplaysPromise;
  363. private _vrDisplays;
  364. private _vrDisplayEnabled;
  365. private _oldSize: BABYLON.Size;
  366. private _oldHardwareScaleFactor: number;
  367. private _vrAnimationFrameHandler: number;
  368. // Private Members
  369. public _gl: WebGLRenderingContext;
  370. private _renderingCanvas: HTMLCanvasElement;
  371. private _windowIsBackground = false;
  372. private _webGLVersion = 1.0;
  373. private _badOS = false;
  374. public static audioEngine: AudioEngine;
  375. private _onBlur: () => void;
  376. private _onFocus: () => void;
  377. private _onFullscreenChange: () => void;
  378. private _onPointerLockChange: () => void;
  379. private _hardwareScalingLevel: number;
  380. private _caps: EngineCapabilities;
  381. private _pointerLockRequested: boolean;
  382. private _alphaTest: boolean;
  383. private _isStencilEnable: boolean;
  384. private _loadingScreen: ILoadingScreen;
  385. public _drawCalls = new PerfCounter();
  386. private _glVersion: string;
  387. private _glRenderer: string;
  388. private _glVendor: string;
  389. private _videoTextureSupported: boolean;
  390. private _renderingQueueLaunched = false;
  391. private _activeRenderLoops = [];
  392. // FPS
  393. private fpsRange = 60;
  394. private previousFramesDuration = [];
  395. private fps = 60;
  396. private deltaTime = 0;
  397. // States
  398. private _depthCullingState = new Internals._DepthCullingState();
  399. private _stencilState = new Internals._StencilState();
  400. private _alphaState = new Internals._AlphaState();
  401. private _alphaMode = Engine.ALPHA_DISABLE;
  402. // Cache
  403. private _loadedTexturesCache = new Array<WebGLTexture>();
  404. private _maxTextureChannels = 16;
  405. private _activeTexture: number;
  406. private _activeTexturesCache = new Array<WebGLTexture>(this._maxTextureChannels);
  407. private _currentEffect: Effect;
  408. private _currentProgram: WebGLProgram;
  409. private _compiledEffects = {};
  410. private _vertexAttribArraysEnabled: boolean[] = [];
  411. private _cachedViewport: Viewport;
  412. private _cachedVertexArrayObject: WebGLVertexArrayObject;
  413. private _cachedVertexBuffers: any;
  414. private _cachedIndexBuffer: WebGLBuffer;
  415. private _cachedEffectForVertexBuffers: Effect;
  416. private _currentRenderTarget: WebGLTexture;
  417. private _uintIndicesCurrentlySet = false;
  418. private _currentBoundBuffer = new Array<WebGLBuffer>();
  419. private _currentFramebuffer: WebGLFramebuffer;
  420. private _currentBufferPointers: Array<{ indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number, buffer: WebGLBuffer }> = [];
  421. private _currentInstanceLocations = new Array<number>();
  422. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  423. private _textureUnits: Int32Array;
  424. private _workingCanvas: HTMLCanvasElement;
  425. private _workingContext: CanvasRenderingContext2D;
  426. private _externalData: StringDictionary<Object>;
  427. private _bindedRenderFunction: any;
  428. private _vaoRecordInProgress = false;
  429. private _mustWipeVertexAttributes = false;
  430. // Hardware supported Compressed Textures
  431. private _texturesSupported = new Array<string>();
  432. private _textureFormatInUse: string;
  433. public get texturesSupported(): Array<string> {
  434. return this._texturesSupported;
  435. }
  436. public get textureFormatInUse(): string {
  437. return this._textureFormatInUse;
  438. }
  439. /**
  440. * @constructor
  441. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  442. * @param {boolean} [antialias] - enable antialias
  443. * @param options - further options to be sent to the getContext function
  444. */
  445. constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio = false) {
  446. this._renderingCanvas = canvas;
  447. Engine.Instances.push(this);
  448. this._externalData = new StringDictionary<Object>();
  449. options = options || {};
  450. if (antialias != null) {
  451. options.antialias = antialias;
  452. }
  453. if (options.preserveDrawingBuffer === undefined) {
  454. options.preserveDrawingBuffer = false;
  455. }
  456. if (options.audioEngine === undefined) {
  457. options.audioEngine = true;
  458. }
  459. if (options.stencil === undefined) {
  460. options.stencil = true;
  461. }
  462. // GL
  463. if (!options.disableWebGL2Support) {
  464. try {
  465. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  466. if (this._gl) {
  467. this._webGLVersion = 2.0;
  468. }
  469. } catch (e) {
  470. // Do nothing
  471. }
  472. }
  473. if (!this._gl) {
  474. if (!canvas) {
  475. throw new Error("The provided canvas is null or undefined.");
  476. }
  477. try {
  478. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  479. } catch (e) {
  480. throw new Error("WebGL not supported");
  481. }
  482. }
  483. if (!this._gl) {
  484. throw new Error("WebGL not supported");
  485. }
  486. this._onBlur = () => {
  487. this._windowIsBackground = true;
  488. };
  489. this._onFocus = () => {
  490. this._windowIsBackground = false;
  491. };
  492. window.addEventListener("blur", this._onBlur);
  493. window.addEventListener("focus", this._onFocus);
  494. // Viewport
  495. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  496. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  497. this.resize();
  498. // Caps
  499. this._isStencilEnable = options.stencil;
  500. this._caps = new EngineCapabilities();
  501. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  502. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  503. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  504. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  505. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  506. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  507. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  508. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  509. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  510. // Infos
  511. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  512. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  513. if (rendererInfo != null) {
  514. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  515. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  516. }
  517. if (!this._glVendor) {
  518. this._glVendor = "Unknown vendor";
  519. }
  520. if (!this._glRenderer) {
  521. this._glRenderer = "Unknown renderer";
  522. }
  523. // Extensions
  524. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  525. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  526. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  527. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  528. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1' ) || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1' );
  529. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc' ) || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc' ) ||
  530. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  531. 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');
  532. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  533. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  534. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  535. this._caps.highPrecisionShaderSupported = true;
  536. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  537. // Checks if some of the format renders first to allow the use of webgl inspector.
  538. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float')
  539. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  540. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  541. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  542. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  543. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  544. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  545. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  546. // Vertex array object
  547. if (this._webGLVersion > 1) {
  548. this._caps.vertexArrayObject = true;
  549. } else {
  550. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  551. if (vertexArrayObjectExtension != null) {
  552. this._caps.vertexArrayObject = true;
  553. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  554. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  555. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  556. } else {
  557. this._caps.vertexArrayObject = false;
  558. }
  559. }
  560. // Instances count
  561. if (this._webGLVersion > 1) {
  562. this._caps.instancedArrays = true;
  563. } else {
  564. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  565. if (instanceExtension != null) {
  566. this._caps.instancedArrays = true;
  567. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  568. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  569. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  570. } else {
  571. this._caps.instancedArrays = false;
  572. }
  573. }
  574. // Intelligently add supported compressed formats in order to check for.
  575. // Check for ASTC support first as it is most powerful and to be very cross platform.
  576. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  577. // Likely no hardware which supports both PVR & DXT, so order matters little.
  578. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  579. if (this._caps.astc ) this.texturesSupported.push('-astc.ktx');
  580. if (this._caps.s3tc ) this.texturesSupported.push('-dxt.ktx');
  581. if (this._caps.pvrtc) this.texturesSupported.push('-pvrtc.ktx');
  582. if (this._caps.etc2 ) this.texturesSupported.push('-etc2.ktx');
  583. if (this._caps.etc1 ) this.texturesSupported.push('-etc1.ktx');
  584. if (this._gl.getShaderPrecisionFormat) {
  585. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  586. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  587. }
  588. // Depth buffer
  589. this.setDepthBuffer(true);
  590. this.setDepthFunctionToLessOrEqual();
  591. this.setDepthWrite(true);
  592. // Fullscreen
  593. this._onFullscreenChange = () => {
  594. if (document.fullscreen !== undefined) {
  595. this.isFullscreen = document.fullscreen;
  596. } else if (document.mozFullScreen !== undefined) {
  597. this.isFullscreen = document.mozFullScreen;
  598. } else if (document.webkitIsFullScreen !== undefined) {
  599. this.isFullscreen = document.webkitIsFullScreen;
  600. } else if (document.msIsFullScreen !== undefined) {
  601. this.isFullscreen = document.msIsFullScreen;
  602. }
  603. // Pointer lock
  604. if (this.isFullscreen && this._pointerLockRequested) {
  605. canvas.requestPointerLock = canvas.requestPointerLock ||
  606. canvas.msRequestPointerLock ||
  607. canvas.mozRequestPointerLock ||
  608. canvas.webkitRequestPointerLock;
  609. if (canvas.requestPointerLock) {
  610. canvas.requestPointerLock();
  611. }
  612. }
  613. };
  614. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  615. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  616. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  617. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  618. // Pointer lock
  619. this._onPointerLockChange = () => {
  620. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  621. document.webkitPointerLockElement === canvas ||
  622. document.msPointerLockElement === canvas ||
  623. document.pointerLockElement === canvas
  624. );
  625. };
  626. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  627. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  628. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  629. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  630. if (options.audioEngine && AudioEngine && !Engine.audioEngine) {
  631. Engine.audioEngine = new AudioEngine();
  632. }
  633. //default loading screen
  634. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas);
  635. //Load WebVR Devices
  636. if (options.autoEnableWebVR) {
  637. this.initWebVR();
  638. }
  639. //Detect if we are running on a faulty buggy OS.
  640. var regexp = /AppleWebKit.*10.[\d] Mobile/
  641. //ua sniffing is the tool of the devil.
  642. this._badOS = regexp.test(navigator.userAgent);
  643. Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  644. }
  645. public get webGLVersion(): number {
  646. return this._webGLVersion;
  647. }
  648. /**
  649. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  650. */
  651. public get isStencilEnable(): boolean {
  652. return this._isStencilEnable;
  653. }
  654. private _prepareWorkingCanvas(): void {
  655. if (this._workingCanvas) {
  656. return;
  657. }
  658. this._workingCanvas = document.createElement("canvas");
  659. this._workingContext = this._workingCanvas.getContext("2d");
  660. }
  661. public resetTextureCache() {
  662. for (var index = 0; index < this._maxTextureChannels; index++) {
  663. this._activeTexturesCache[index] = null;
  664. }
  665. }
  666. public getGlInfo() {
  667. return {
  668. vendor: this._glVendor,
  669. renderer: this._glRenderer,
  670. version: this._glVersion
  671. }
  672. }
  673. public getAspectRatio(camera: Camera, useScreen = false): number {
  674. var viewport = camera.viewport;
  675. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  676. }
  677. public getRenderWidth(useScreen = false): number {
  678. if (!useScreen && this._currentRenderTarget) {
  679. return this._currentRenderTarget._width;
  680. }
  681. return this._renderingCanvas.width;
  682. }
  683. public getRenderHeight(useScreen = false): number {
  684. if (!useScreen && this._currentRenderTarget) {
  685. return this._currentRenderTarget._height;
  686. }
  687. return this._renderingCanvas.height;
  688. }
  689. public getRenderingCanvas(): HTMLCanvasElement {
  690. return this._renderingCanvas;
  691. }
  692. public getRenderingCanvasClientRect(): ClientRect {
  693. return this._renderingCanvas.getBoundingClientRect();
  694. }
  695. public setHardwareScalingLevel(level: number): void {
  696. this._hardwareScalingLevel = level;
  697. this.resize();
  698. }
  699. public getHardwareScalingLevel(): number {
  700. return this._hardwareScalingLevel;
  701. }
  702. public getLoadedTexturesCache(): WebGLTexture[] {
  703. return this._loadedTexturesCache;
  704. }
  705. public getCaps(): EngineCapabilities {
  706. return this._caps;
  707. }
  708. public get drawCalls(): number {
  709. return this._drawCalls.current;
  710. }
  711. public get drawCallsPerfCounter(): PerfCounter {
  712. return this._drawCalls;
  713. }
  714. public getDepthFunction(): number {
  715. return this._depthCullingState.depthFunc;
  716. }
  717. public setDepthFunction(depthFunc: number) {
  718. this._depthCullingState.depthFunc = depthFunc;
  719. }
  720. public setDepthFunctionToGreater(): void {
  721. this._depthCullingState.depthFunc = this._gl.GREATER;
  722. }
  723. public setDepthFunctionToGreaterOrEqual(): void {
  724. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  725. }
  726. public setDepthFunctionToLess(): void {
  727. this._depthCullingState.depthFunc = this._gl.LESS;
  728. }
  729. public setDepthFunctionToLessOrEqual(): void {
  730. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  731. }
  732. public getStencilBuffer(): boolean {
  733. return this._stencilState.stencilTest;
  734. }
  735. public setStencilBuffer(enable: boolean): void {
  736. this._stencilState.stencilTest = enable;
  737. }
  738. public getStencilMask(): number {
  739. return this._stencilState.stencilMask;
  740. }
  741. public setStencilMask(mask: number): void {
  742. this._stencilState.stencilMask = mask;
  743. }
  744. public getStencilFunction(): number {
  745. return this._stencilState.stencilFunc;
  746. }
  747. public getStencilFunctionReference(): number {
  748. return this._stencilState.stencilFuncRef;
  749. }
  750. public getStencilFunctionMask(): number {
  751. return this._stencilState.stencilFuncMask;
  752. }
  753. public setStencilFunction(stencilFunc: number) {
  754. this._stencilState.stencilFunc = stencilFunc;
  755. }
  756. public setStencilFunctionReference(reference: number) {
  757. this._stencilState.stencilFuncRef = reference;
  758. }
  759. public setStencilFunctionMask(mask: number) {
  760. this._stencilState.stencilFuncMask = mask;
  761. }
  762. public getStencilOperationFail(): number {
  763. return this._stencilState.stencilOpStencilFail;
  764. }
  765. public getStencilOperationDepthFail(): number {
  766. return this._stencilState.stencilOpDepthFail;
  767. }
  768. public getStencilOperationPass(): number {
  769. return this._stencilState.stencilOpStencilDepthPass;
  770. }
  771. public setStencilOperationFail(operation: number): void {
  772. this._stencilState.stencilOpStencilFail = operation;
  773. }
  774. public setStencilOperationDepthFail(operation: number): void {
  775. this._stencilState.stencilOpDepthFail = operation;
  776. }
  777. public setStencilOperationPass(operation: number): void {
  778. this._stencilState.stencilOpStencilDepthPass = operation;
  779. }
  780. /**
  781. * stop executing a render loop function and remove it from the execution array
  782. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  783. */
  784. public stopRenderLoop(renderFunction?: () => void): void {
  785. if (!renderFunction) {
  786. this._activeRenderLoops = [];
  787. return;
  788. }
  789. var index = this._activeRenderLoops.indexOf(renderFunction);
  790. if (index >= 0) {
  791. this._activeRenderLoops.splice(index, 1);
  792. }
  793. }
  794. public _renderLoop(): void {
  795. var shouldRender = true;
  796. if (!this.renderEvenInBackground && this._windowIsBackground) {
  797. shouldRender = false;
  798. }
  799. if (shouldRender) {
  800. // Start new frame
  801. this.beginFrame();
  802. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  803. var renderFunction = this._activeRenderLoops[index];
  804. renderFunction();
  805. }
  806. // Present
  807. this.endFrame();
  808. }
  809. if (this._activeRenderLoops.length > 0) {
  810. // Register new frame
  811. Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  812. } else {
  813. this._renderingQueueLaunched = false;
  814. }
  815. }
  816. /**
  817. * Register and execute a render loop. The engine can have more than one render function.
  818. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  819. * @example
  820. * engine.runRenderLoop(function () {
  821. * scene.render()
  822. * })
  823. */
  824. public runRenderLoop(renderFunction: () => void): void {
  825. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  826. return;
  827. }
  828. this._activeRenderLoops.push(renderFunction);
  829. if (!this._renderingQueueLaunched) {
  830. this._renderingQueueLaunched = true;
  831. this._bindedRenderFunction = this._renderLoop.bind(this);
  832. Tools.QueueNewFrame(this._bindedRenderFunction);
  833. }
  834. }
  835. /**
  836. * Toggle full screen mode.
  837. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  838. * @param {any} options - an options object to be sent to the requestFullscreen function
  839. */
  840. public switchFullscreen(requestPointerLock: boolean): void {
  841. if (this.isFullscreen) {
  842. Tools.ExitFullscreen();
  843. } else {
  844. this._pointerLockRequested = requestPointerLock;
  845. Tools.RequestFullscreen(this._renderingCanvas);
  846. }
  847. }
  848. public clear(color: Color4, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  849. this.applyStates();
  850. var mode = 0;
  851. if (backBuffer && color) {
  852. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  853. mode |= this._gl.COLOR_BUFFER_BIT;
  854. }
  855. if (depth) {
  856. this._gl.clearDepth(1.0);
  857. mode |= this._gl.DEPTH_BUFFER_BIT;
  858. }
  859. if (stencil) {
  860. this._gl.clearStencil(0);
  861. mode |= this._gl.STENCIL_BUFFER_BIT;
  862. }
  863. this._gl.clear(mode);
  864. }
  865. public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
  866. let gl = this._gl;
  867. // Save state
  868. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  869. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  870. // Change state
  871. gl.enable(gl.SCISSOR_TEST);
  872. gl.scissor(x, y, width, height);
  873. // Clear
  874. this.clear(clearColor, true, true, true);
  875. // Restore state
  876. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  877. if (curScissor === true) {
  878. gl.enable(gl.SCISSOR_TEST);
  879. } else {
  880. gl.disable(gl.SCISSOR_TEST);
  881. }
  882. }
  883. /**
  884. * Set the WebGL's viewport
  885. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  886. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  887. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  888. */
  889. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  890. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  891. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  892. var x = viewport.x || 0;
  893. var y = viewport.y || 0;
  894. this._cachedViewport = viewport;
  895. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  896. }
  897. /**
  898. * Directly set the WebGL Viewport
  899. * The x, y, width & height are directly passed to the WebGL call
  900. * @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.
  901. */
  902. public setDirectViewport(x: number, y: number, width: number, height: number): Viewport {
  903. let currentViewport = this._cachedViewport;
  904. this._cachedViewport = null;
  905. this._gl.viewport(x, y, width, height);
  906. return currentViewport;
  907. }
  908. public beginFrame(): void {
  909. this._measureFps();
  910. }
  911. public endFrame(): void {
  912. //force a flush in case we are using a bad OS.
  913. if (this._badOS) {
  914. this.flushFramebuffer();
  915. }
  916. //submit frame to the vr device, if enabled
  917. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  918. this._vrDisplayEnabled.submitFrame()
  919. }
  920. }
  921. /**
  922. * resize the view according to the canvas' size.
  923. * @example
  924. * window.addEventListener("resize", function () {
  925. * engine.resize();
  926. * });
  927. */
  928. public resize(): void {
  929. // We're not resizing the size of the canvas while in VR mode & presenting
  930. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  931. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  932. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  933. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  934. }
  935. }
  936. /**
  937. * force a specific size of the canvas
  938. * @param {number} width - the new canvas' width
  939. * @param {number} height - the new canvas' height
  940. */
  941. public setSize(width: number, height: number): void {
  942. this._renderingCanvas.width = width;
  943. this._renderingCanvas.height = height;
  944. for (var index = 0; index < this.scenes.length; index++) {
  945. var scene = this.scenes[index];
  946. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  947. var cam = scene.cameras[camIndex];
  948. cam._currentRenderId = 0;
  949. }
  950. }
  951. }
  952. //WebVR functions
  953. public initWebVR() {
  954. if (!this.vrDisplaysPromise) {
  955. this._getVRDisplays();
  956. }
  957. }
  958. public enableVR(vrDevice) {
  959. this._vrDisplayEnabled = vrDevice;
  960. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  961. }
  962. public disableVR() {
  963. if (this._vrDisplayEnabled) {
  964. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  965. }
  966. }
  967. private _onVRFullScreenTriggered = () => {
  968. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  969. //get the old size before we change
  970. this._oldSize = new BABYLON.Size(this.getRenderWidth(), this.getRenderHeight());
  971. this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
  972. //get the width and height, change the render size
  973. var leftEye = this._vrDisplayEnabled.getEyeParameters('left');
  974. var width, height;
  975. this.setHardwareScalingLevel(1);
  976. this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  977. } else {
  978. //When the specs are implemented, need to uncomment this.
  979. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  980. this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
  981. this.setSize(this._oldSize.width, this._oldSize.height);
  982. this._vrDisplayEnabled = undefined;
  983. }
  984. }
  985. private _getVRDisplays() {
  986. var getWebVRDevices = (devices: Array<any>) => {
  987. var size = devices.length;
  988. var i = 0;
  989. this._vrDisplays = devices.filter(function (device) {
  990. return devices[i] instanceof VRDisplay;
  991. });
  992. return this._vrDisplays;
  993. }
  994. //using a key due to typescript
  995. if (navigator.getVRDisplays) {
  996. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  997. }
  998. }
  999. public bindFramebuffer(texture: WebGLTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number): void {
  1000. this._currentRenderTarget = texture;
  1001. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  1002. var gl = this._gl;
  1003. if (texture.isCube) {
  1004. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  1005. }
  1006. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  1007. this.wipeCaches();
  1008. }
  1009. private bindUnboundFramebuffer(framebuffer: WebGLFramebuffer) {
  1010. if (this._currentFramebuffer !== framebuffer) {
  1011. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  1012. this._currentFramebuffer = framebuffer;
  1013. }
  1014. }
  1015. public unBindFramebuffer(texture: WebGLTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1016. this._currentRenderTarget = null;
  1017. // If MSAA, we need to bitblt back to main texture
  1018. var gl = this._gl;
  1019. if (texture._MSAAFramebuffer) {
  1020. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  1021. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  1022. gl.blitFramebuffer(0, 0, texture._width, texture._height,
  1023. 0, 0, texture._width, texture._height,
  1024. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1025. }
  1026. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  1027. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  1028. gl.generateMipmap(gl.TEXTURE_2D);
  1029. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1030. }
  1031. if (onBeforeUnbind) {
  1032. if (texture._MSAAFramebuffer) {
  1033. // Bind the correct framebuffer
  1034. this.bindUnboundFramebuffer(texture._framebuffer);
  1035. }
  1036. onBeforeUnbind();
  1037. }
  1038. this.bindUnboundFramebuffer(null);
  1039. }
  1040. public generateMipMapsForCubemap(texture: WebGLTexture) {
  1041. if (texture.generateMipMaps) {
  1042. var gl = this._gl;
  1043. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1044. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1045. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1046. }
  1047. }
  1048. public flushFramebuffer(): void {
  1049. this._gl.flush();
  1050. }
  1051. public restoreDefaultFramebuffer(): void {
  1052. this._currentRenderTarget = null;
  1053. this.bindUnboundFramebuffer(null);
  1054. this.setViewport(this._cachedViewport);
  1055. this.wipeCaches();
  1056. }
  1057. // VBOs
  1058. private _resetVertexBufferBinding(): void {
  1059. this.bindArrayBuffer(null);
  1060. this._cachedVertexBuffers = null;
  1061. }
  1062. public createVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
  1063. var vbo = this._gl.createBuffer();
  1064. this.bindArrayBuffer(vbo);
  1065. if (vertices instanceof Float32Array) {
  1066. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.STATIC_DRAW);
  1067. } else {
  1068. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.STATIC_DRAW);
  1069. }
  1070. this._resetVertexBufferBinding();
  1071. vbo.references = 1;
  1072. return vbo;
  1073. }
  1074. public createDynamicVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
  1075. var vbo = this._gl.createBuffer();
  1076. this.bindArrayBuffer(vbo);
  1077. if (vertices instanceof Float32Array) {
  1078. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.DYNAMIC_DRAW);
  1079. } else {
  1080. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.DYNAMIC_DRAW);
  1081. }
  1082. this._resetVertexBufferBinding();
  1083. vbo.references = 1;
  1084. return vbo;
  1085. }
  1086. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: number[] | Float32Array, offset?: number, count?: number): void {
  1087. this.bindArrayBuffer(vertexBuffer);
  1088. if (offset === undefined) {
  1089. offset = 0;
  1090. }
  1091. if (count === undefined) {
  1092. if (vertices instanceof Float32Array) {
  1093. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, <Float32Array>vertices);
  1094. } else {
  1095. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(<number[]>vertices));
  1096. }
  1097. } else {
  1098. if (vertices instanceof Float32Array) {
  1099. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <Float32Array>vertices.subarray(offset, offset + count));
  1100. } else {
  1101. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(<number[]>vertices).subarray(offset, offset + count));
  1102. }
  1103. }
  1104. this._resetVertexBufferBinding();
  1105. }
  1106. private _resetIndexBufferBinding(): void {
  1107. this.bindIndexBuffer(null);
  1108. this._cachedIndexBuffer = null;
  1109. }
  1110. public createIndexBuffer(indices: IndicesArray): WebGLBuffer {
  1111. var vbo = this._gl.createBuffer();
  1112. this.bindIndexBuffer(vbo);
  1113. // Check for 32 bits indices
  1114. var arrayBuffer;
  1115. var need32Bits = false;
  1116. if (indices instanceof Uint16Array) {
  1117. arrayBuffer = indices;
  1118. } else {
  1119. //check 32 bit support
  1120. if (this._caps.uintIndices) {
  1121. if (indices instanceof Uint32Array) {
  1122. arrayBuffer = indices;
  1123. need32Bits = true;
  1124. } else {
  1125. //number[] or Int32Array, check if 32 bit is necessary
  1126. for (var index = 0; index < indices.length; index++) {
  1127. if (indices[index] > 65535) {
  1128. need32Bits = true;
  1129. break;
  1130. }
  1131. }
  1132. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  1133. }
  1134. } else {
  1135. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  1136. arrayBuffer = new Uint16Array(indices);
  1137. }
  1138. }
  1139. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  1140. this._resetIndexBufferBinding();
  1141. vbo.references = 1;
  1142. vbo.is32Bits = need32Bits;
  1143. return vbo;
  1144. }
  1145. public bindArrayBuffer(buffer: WebGLBuffer): void {
  1146. if (!this._vaoRecordInProgress) {
  1147. this._unBindVertexArrayObject();
  1148. }
  1149. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  1150. }
  1151. private bindIndexBuffer(buffer: WebGLBuffer): void {
  1152. if (!this._vaoRecordInProgress) {
  1153. this._unBindVertexArrayObject();
  1154. }
  1155. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  1156. }
  1157. private bindBuffer(buffer: WebGLBuffer, target: number): void {
  1158. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  1159. this._gl.bindBuffer(target, buffer);
  1160. this._currentBoundBuffer[target] = buffer;
  1161. }
  1162. }
  1163. public updateArrayBuffer(data: Float32Array): void {
  1164. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1165. }
  1166. private vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  1167. var pointer = this._currentBufferPointers[indx];
  1168. var changed = false;
  1169. if (!pointer) {
  1170. changed = true;
  1171. this._currentBufferPointers[indx] = { indx, size, type, normalized, stride, offset, buffer: buffer };
  1172. } else {
  1173. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  1174. if (pointer.size !== size) { pointer.size = size; changed = true; }
  1175. if (pointer.type !== type) { pointer.type = type; changed = true; }
  1176. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  1177. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  1178. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  1179. }
  1180. if (changed || this._vaoRecordInProgress) {
  1181. this.bindArrayBuffer(buffer);
  1182. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  1183. }
  1184. }
  1185. private _bindIndexBufferWithCache(indexBuffer: WebGLBuffer): void {
  1186. if (indexBuffer == null) {
  1187. return;
  1188. }
  1189. if (this._cachedIndexBuffer !== indexBuffer) {
  1190. this._cachedIndexBuffer = indexBuffer;
  1191. this.bindIndexBuffer(indexBuffer);
  1192. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  1193. }
  1194. }
  1195. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: VertexBuffer; }, effect: Effect) {
  1196. var attributes = effect.getAttributesNames();
  1197. if (!this._vaoRecordInProgress) {
  1198. this._unBindVertexArrayObject();
  1199. }
  1200. this.unbindAllAttributes();
  1201. for (var index = 0; index < attributes.length; index++) {
  1202. var order = effect.getAttributeLocation(index);
  1203. if (order >= 0) {
  1204. var vertexBuffer = vertexBuffers[attributes[index]];
  1205. if (!vertexBuffer) {
  1206. continue;
  1207. }
  1208. this._gl.enableVertexAttribArray(order);
  1209. if (!this._vaoRecordInProgress) {
  1210. this._vertexAttribArraysEnabled[order] = true;
  1211. }
  1212. var buffer = vertexBuffer.getBuffer();
  1213. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  1214. if (vertexBuffer.getIsInstanced()) {
  1215. this._gl.vertexAttribDivisor(order, 1);
  1216. if (!this._vaoRecordInProgress) {
  1217. this._currentInstanceLocations.push(order);
  1218. this._currentInstanceBuffers.push(buffer);
  1219. }
  1220. }
  1221. }
  1222. }
  1223. }
  1224. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: WebGLBuffer, effect: Effect): WebGLVertexArrayObject {
  1225. var vao = this._gl.createVertexArray();
  1226. this._vaoRecordInProgress = true;
  1227. this._gl.bindVertexArray(vao);
  1228. this._mustWipeVertexAttributes = true;
  1229. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1230. this.bindIndexBuffer(indexBuffer);
  1231. this._vaoRecordInProgress = false;
  1232. this._gl.bindVertexArray(null);
  1233. return vao;
  1234. }
  1235. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: WebGLBuffer): void {
  1236. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  1237. this._cachedVertexArrayObject = vertexArrayObject;
  1238. this._gl.bindVertexArray(vertexArrayObject);
  1239. this._cachedVertexBuffers = null;
  1240. this._cachedIndexBuffer = null;
  1241. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  1242. this._mustWipeVertexAttributes = true;
  1243. }
  1244. }
  1245. public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  1246. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  1247. this._cachedVertexBuffers = vertexBuffer;
  1248. this._cachedEffectForVertexBuffers = effect;
  1249. let attributesCount = effect.getAttributesCount();
  1250. this._unBindVertexArrayObject();
  1251. this.unbindAllAttributes();
  1252. var offset = 0;
  1253. for (var index = 0; index < attributesCount; index++) {
  1254. if (index < vertexDeclaration.length) {
  1255. var order = effect.getAttributeLocation(index);
  1256. if (order >= 0) {
  1257. this._gl.enableVertexAttribArray(order);
  1258. this._vertexAttribArraysEnabled[order] = true;
  1259. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  1260. }
  1261. offset += vertexDeclaration[index] * 4;
  1262. }
  1263. }
  1264. }
  1265. this._bindIndexBufferWithCache(indexBuffer);
  1266. }
  1267. private _unBindVertexArrayObject(): void {
  1268. if (!this._cachedVertexArrayObject) {
  1269. return;
  1270. }
  1271. this._cachedVertexArrayObject = null;
  1272. this._gl.bindVertexArray(null);
  1273. }
  1274. public bindBuffers(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: WebGLBuffer, effect: Effect): void {
  1275. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  1276. this._cachedVertexBuffers = vertexBuffers;
  1277. this._cachedEffectForVertexBuffers = effect;
  1278. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1279. }
  1280. this._bindIndexBufferWithCache(indexBuffer);
  1281. }
  1282. public unbindInstanceAttributes() {
  1283. var boundBuffer;
  1284. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  1285. var instancesBuffer = this._currentInstanceBuffers[i];
  1286. if (boundBuffer != instancesBuffer) {
  1287. boundBuffer = instancesBuffer;
  1288. this.bindArrayBuffer(instancesBuffer);
  1289. }
  1290. var offsetLocation = this._currentInstanceLocations[i];
  1291. this._gl.vertexAttribDivisor(offsetLocation, 0);
  1292. }
  1293. this._currentInstanceBuffers.length = 0;
  1294. this._currentInstanceLocations.length = 0;
  1295. }
  1296. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  1297. this._gl.deleteVertexArray(vao);
  1298. }
  1299. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  1300. buffer.references--;
  1301. if (buffer.references === 0) {
  1302. this._gl.deleteBuffer(buffer);
  1303. return true;
  1304. }
  1305. return false;
  1306. }
  1307. public createInstancesBuffer(capacity: number): WebGLBuffer {
  1308. var buffer = this._gl.createBuffer();
  1309. buffer.capacity = capacity;
  1310. this.bindArrayBuffer(buffer);
  1311. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  1312. return buffer;
  1313. }
  1314. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  1315. this._gl.deleteBuffer(buffer);
  1316. }
  1317. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  1318. this.bindArrayBuffer(instancesBuffer);
  1319. if (data) {
  1320. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1321. }
  1322. if ((<any>offsetLocations[0]).index !== undefined) {
  1323. let stride = 0;
  1324. for (let i = 0; i < offsetLocations.length; i++) {
  1325. let ai = <InstancingAttributeInfo>offsetLocations[i];
  1326. stride += ai.attributeSize * 4;
  1327. }
  1328. for (let i = 0; i < offsetLocations.length; i++) {
  1329. let ai = <InstancingAttributeInfo>offsetLocations[i];
  1330. if (!this._vertexAttribArraysEnabled[ai.index]) {
  1331. this._gl.enableVertexAttribArray(ai.index);
  1332. this._vertexAttribArraysEnabled[ai.index] = true;
  1333. }
  1334. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  1335. this._gl.vertexAttribDivisor(ai.index, 1);
  1336. this._currentInstanceLocations.push(ai.index);
  1337. this._currentInstanceBuffers.push(instancesBuffer);
  1338. }
  1339. } else {
  1340. for (let index = 0; index < 4; index++) {
  1341. let offsetLocation = <number>offsetLocations[index];
  1342. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  1343. this._gl.enableVertexAttribArray(offsetLocation);
  1344. this._vertexAttribArraysEnabled[offsetLocation] = true;
  1345. }
  1346. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  1347. this._gl.vertexAttribDivisor(offsetLocation, 1);
  1348. this._currentInstanceLocations.push(offsetLocation);
  1349. this._currentInstanceBuffers.push(instancesBuffer);
  1350. }
  1351. }
  1352. }
  1353. public applyStates() {
  1354. this._depthCullingState.apply(this._gl);
  1355. this._stencilState.apply(this._gl);
  1356. this._alphaState.apply(this._gl);
  1357. }
  1358. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  1359. // Apply states
  1360. this.applyStates();
  1361. this._drawCalls.addCount(1, false);
  1362. // Render
  1363. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  1364. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  1365. if (instancesCount) {
  1366. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  1367. return;
  1368. }
  1369. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  1370. }
  1371. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1372. // Apply states
  1373. this.applyStates();
  1374. this._drawCalls.addCount(1, false);
  1375. if (instancesCount) {
  1376. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  1377. return;
  1378. }
  1379. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  1380. }
  1381. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1382. // Apply states
  1383. this.applyStates();
  1384. this._drawCalls.addCount(1, false);
  1385. if (instancesCount) {
  1386. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  1387. return;
  1388. }
  1389. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  1390. }
  1391. // Shaders
  1392. public _releaseEffect(effect: Effect): void {
  1393. if (this._compiledEffects[effect._key]) {
  1394. delete this._compiledEffects[effect._key];
  1395. if (effect.getProgram()) {
  1396. this._gl.deleteProgram(effect.getProgram());
  1397. }
  1398. }
  1399. }
  1400. public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks,
  1401. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  1402. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  1403. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  1404. var name = vertex + "+" + fragment + "@" + defines;
  1405. if (this._compiledEffects[name]) {
  1406. return this._compiledEffects[name];
  1407. }
  1408. var effect = new Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  1409. effect._key = name;
  1410. this._compiledEffects[name] = effect;
  1411. return effect;
  1412. }
  1413. public createEffectForParticles(fragmentName: string, uniformsNames: string[] = [], samplers: string[] = [], defines = "", fallbacks?: EffectFallbacks,
  1414. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  1415. return this.createEffect(
  1416. {
  1417. vertex: "particles",
  1418. fragmentElement: fragmentName
  1419. },
  1420. ["position", "color", "options"],
  1421. ["view", "projection"].concat(uniformsNames),
  1422. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  1423. }
  1424. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string, context?: WebGLRenderingContext): WebGLProgram {
  1425. context = context || this._gl;
  1426. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  1427. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  1428. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  1429. var shaderProgram = context.createProgram();
  1430. context.attachShader(shaderProgram, vertexShader);
  1431. context.attachShader(shaderProgram, fragmentShader);
  1432. context.linkProgram(shaderProgram);
  1433. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  1434. if (!linked) {
  1435. var error = context.getProgramInfoLog(shaderProgram);
  1436. if (error) {
  1437. throw new Error(error);
  1438. }
  1439. }
  1440. context.deleteShader(vertexShader);
  1441. context.deleteShader(fragmentShader);
  1442. return shaderProgram;
  1443. }
  1444. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  1445. var results = [];
  1446. for (var index = 0; index < uniformsNames.length; index++) {
  1447. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  1448. }
  1449. return results;
  1450. }
  1451. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  1452. var results = [];
  1453. for (var index = 0; index < attributesNames.length; index++) {
  1454. try {
  1455. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  1456. } catch (e) {
  1457. results.push(-1);
  1458. }
  1459. }
  1460. return results;
  1461. }
  1462. public enableEffect(effect: Effect): void {
  1463. // Use program
  1464. this.setProgram(effect.getProgram());
  1465. this._currentEffect = effect;
  1466. if (effect.onBind) {
  1467. effect.onBind(effect);
  1468. }
  1469. }
  1470. public setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void {
  1471. if (!uniform)
  1472. return;
  1473. this._gl.uniform1iv(uniform, array);
  1474. }
  1475. public setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void {
  1476. if (!uniform || array.length % 2 !== 0)
  1477. return;
  1478. this._gl.uniform2iv(uniform, array);
  1479. }
  1480. public setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void {
  1481. if (!uniform || array.length % 3 !== 0)
  1482. return;
  1483. this._gl.uniform3iv(uniform, array);
  1484. }
  1485. public setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void {
  1486. if (!uniform || array.length % 4 !== 0)
  1487. return;
  1488. this._gl.uniform4iv(uniform, array);
  1489. }
  1490. public setFloatArray(uniform: WebGLUniformLocation, array: Float32Array): void {
  1491. if (!uniform)
  1492. return;
  1493. this._gl.uniform1fv(uniform, array);
  1494. }
  1495. public setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array): void {
  1496. if (!uniform || array.length % 2 !== 0)
  1497. return;
  1498. this._gl.uniform2fv(uniform, array);
  1499. }
  1500. public setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array): void {
  1501. if (!uniform || array.length % 3 !== 0)
  1502. return;
  1503. this._gl.uniform3fv(uniform, array);
  1504. }
  1505. public setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array): void {
  1506. if (!uniform || array.length % 4 !== 0)
  1507. return;
  1508. this._gl.uniform4fv(uniform, array);
  1509. }
  1510. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  1511. if (!uniform)
  1512. return;
  1513. this._gl.uniform1fv(uniform, <any>array);
  1514. }
  1515. public setArray2(uniform: WebGLUniformLocation, array: number[]): void {
  1516. if (!uniform || array.length % 2 !== 0)
  1517. return;
  1518. this._gl.uniform2fv(uniform, <any>array);
  1519. }
  1520. public setArray3(uniform: WebGLUniformLocation, array: number[]): void {
  1521. if (!uniform || array.length % 3 !== 0)
  1522. return;
  1523. this._gl.uniform3fv(uniform, <any>array);
  1524. }
  1525. public setArray4(uniform: WebGLUniformLocation, array: number[]): void {
  1526. if (!uniform || array.length % 4 !== 0)
  1527. return;
  1528. this._gl.uniform4fv(uniform, <any>array);
  1529. }
  1530. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  1531. if (!uniform)
  1532. return;
  1533. this._gl.uniformMatrix4fv(uniform, false, matrices);
  1534. }
  1535. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  1536. if (!uniform)
  1537. return;
  1538. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  1539. }
  1540. public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  1541. if (!uniform)
  1542. return;
  1543. this._gl.uniformMatrix3fv(uniform, false, matrix);
  1544. }
  1545. public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  1546. if (!uniform)
  1547. return;
  1548. this._gl.uniformMatrix2fv(uniform, false, matrix);
  1549. }
  1550. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  1551. if (!uniform)
  1552. return;
  1553. this._gl.uniform1f(uniform, value);
  1554. }
  1555. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  1556. if (!uniform)
  1557. return;
  1558. this._gl.uniform2f(uniform, x, y);
  1559. }
  1560. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  1561. if (!uniform)
  1562. return;
  1563. this._gl.uniform3f(uniform, x, y, z);
  1564. }
  1565. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  1566. if (!uniform)
  1567. return;
  1568. this._gl.uniform1i(uniform, bool);
  1569. }
  1570. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  1571. if (!uniform)
  1572. return;
  1573. this._gl.uniform4f(uniform, x, y, z, w);
  1574. }
  1575. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  1576. if (!uniform)
  1577. return;
  1578. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  1579. }
  1580. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  1581. if (!uniform)
  1582. return;
  1583. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  1584. }
  1585. // States
  1586. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  1587. // Culling
  1588. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  1589. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  1590. var cullFace = this.cullBackFaces ? showSide : hideSide;
  1591. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  1592. if (culling) {
  1593. this._depthCullingState.cullFace = cullFace;
  1594. this._depthCullingState.cull = true;
  1595. } else {
  1596. this._depthCullingState.cull = false;
  1597. }
  1598. }
  1599. // Z offset
  1600. this._depthCullingState.zOffset = zOffset;
  1601. }
  1602. public setDepthBuffer(enable: boolean): void {
  1603. this._depthCullingState.depthTest = enable;
  1604. }
  1605. public getDepthWrite(): boolean {
  1606. return this._depthCullingState.depthMask;
  1607. }
  1608. public setDepthWrite(enable: boolean): void {
  1609. this._depthCullingState.depthMask = enable;
  1610. }
  1611. public setColorWrite(enable: boolean): void {
  1612. this._gl.colorMask(enable, enable, enable, enable);
  1613. }
  1614. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  1615. if (this._alphaMode === mode) {
  1616. return;
  1617. }
  1618. switch (mode) {
  1619. case Engine.ALPHA_DISABLE:
  1620. this._alphaState.alphaBlend = false;
  1621. break;
  1622. case Engine.ALPHA_PREMULTIPLIED:
  1623. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1624. this._alphaState.alphaBlend = true;
  1625. break;
  1626. case Engine.ALPHA_COMBINE:
  1627. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1628. this._alphaState.alphaBlend = true;
  1629. break;
  1630. case Engine.ALPHA_ONEONE:
  1631. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1632. this._alphaState.alphaBlend = true;
  1633. break;
  1634. case Engine.ALPHA_ADD:
  1635. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1636. this._alphaState.alphaBlend = true;
  1637. break;
  1638. case Engine.ALPHA_SUBTRACT:
  1639. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1640. this._alphaState.alphaBlend = true;
  1641. break;
  1642. case Engine.ALPHA_MULTIPLY:
  1643. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  1644. this._alphaState.alphaBlend = true;
  1645. break;
  1646. case Engine.ALPHA_MAXIMIZED:
  1647. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1648. this._alphaState.alphaBlend = true;
  1649. break;
  1650. }
  1651. if (!noDepthWriteChange) {
  1652. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  1653. }
  1654. this._alphaMode = mode;
  1655. }
  1656. public getAlphaMode(): number {
  1657. return this._alphaMode;
  1658. }
  1659. public setAlphaTesting(enable: boolean): void {
  1660. this._alphaTest = enable;
  1661. }
  1662. public getAlphaTesting(): boolean {
  1663. return !!this._alphaTest;
  1664. }
  1665. // Textures
  1666. public wipeCaches(): void {
  1667. if (this.preventCacheWipeBetweenFrames) {
  1668. return;
  1669. }
  1670. this.resetTextureCache();
  1671. this._currentEffect = null;
  1672. this._stencilState.reset();
  1673. this._depthCullingState.reset();
  1674. this.setDepthFunctionToLessOrEqual();
  1675. this._alphaState.reset();
  1676. this._cachedVertexBuffers = null;
  1677. this._cachedIndexBuffer = null;
  1678. this._cachedEffectForVertexBuffers = null;
  1679. this._unBindVertexArrayObject();
  1680. this.bindIndexBuffer(null);
  1681. this.bindArrayBuffer(null);
  1682. }
  1683. /**
  1684. * Set the compressed texture format to use, based on the formats you have, and the formats
  1685. * supported by the hardware / browser.
  1686. *
  1687. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  1688. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  1689. * to API arguments needed to compressed textures. This puts the burden on the container
  1690. * generator to house the arcane code for determining these for current & future formats.
  1691. *
  1692. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  1693. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  1694. *
  1695. * Note: The result of this call is not taken into account when a texture is base64.
  1696. *
  1697. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  1698. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  1699. *
  1700. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  1701. * @returns The extension selected.
  1702. */
  1703. public setTextureFormatToUse(formatsAvailable: Array<string>): string {
  1704. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  1705. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  1706. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  1707. return this._textureFormatInUse = this._texturesSupported[i];
  1708. }
  1709. }
  1710. }
  1711. // actively set format to nothing, to allow this to be called more than once
  1712. // and possibly fail the 2nd time
  1713. return this._textureFormatInUse = null;
  1714. }
  1715. /**
  1716. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  1717. * @param {string} urlArg- This contains one of the following:
  1718. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  1719. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  1720. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  1721. *
  1722. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  1723. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  1724. * @param {Scene} scene- Needed for loading to the correct scene.
  1725. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  1726. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  1727. * @param {callback} onError- Optional callback to be called upon failure.
  1728. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  1729. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  1730. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  1731. *
  1732. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  1733. */
  1734. 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?: WebGLTexture, format?: number): WebGLTexture {
  1735. var texture = fallBack ? fallBack : this._gl.createTexture();
  1736. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  1737. var fromData = url.substr(0, 5) === "data:";
  1738. var isBase64 = fromData && url.indexOf("base64") !== -1;
  1739. // establish the file extension, if possible
  1740. var lastDot = url.lastIndexOf('.');
  1741. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  1742. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1743. if (isDDS) {
  1744. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  1745. }
  1746. var isTGA = (extension === ".tga");
  1747. // determine if a ktx file should be substituted
  1748. var isKTX = false;
  1749. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  1750. url = url.substring(0, lastDot) + this._textureFormatInUse;
  1751. isKTX = true;
  1752. }
  1753. scene._addPendingData(texture);
  1754. texture.url = url;
  1755. texture.noMipmap = noMipmap;
  1756. texture.references = 1;
  1757. texture.samplingMode = samplingMode;
  1758. texture.onLoadedCallbacks = [];
  1759. if (onLoad) {
  1760. texture.onLoadedCallbacks.push(onLoad);
  1761. }
  1762. if (!fallBack) this._loadedTexturesCache.push(texture);
  1763. var onerror = () => {
  1764. scene._removePendingData(texture);
  1765. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  1766. if (isKTX) {
  1767. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  1768. } else if (onError) {
  1769. onError();
  1770. }
  1771. };
  1772. var callback: (arrayBuffer: any) => void;
  1773. // processing for non-image formats
  1774. if (isKTX || isTGA || isDDS) {
  1775. if (isKTX) {
  1776. callback = (data) => {
  1777. var ktx = new Internals.KhronosTextureContainer(data, 1);
  1778. prepareWebGLTexture(texture, this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, () => {
  1779. ktx.uploadLevels(this._gl, !noMipmap);
  1780. }, samplingMode);
  1781. };
  1782. } else if (isTGA) {
  1783. callback = (arrayBuffer) => {
  1784. var data = new Uint8Array(arrayBuffer);
  1785. var header = Internals.TGATools.GetTGAHeader(data);
  1786. prepareWebGLTexture(texture, this._gl, scene, header.width, header.height, invertY, noMipmap, false, () => {
  1787. Internals.TGATools.UploadContent(this._gl, data);
  1788. }, samplingMode);
  1789. };
  1790. } else if (isDDS) {
  1791. callback = (data) => {
  1792. var info = Internals.DDSTools.GetDDSInfo(data);
  1793. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  1794. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  1795. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 1);
  1796. }, samplingMode);
  1797. };
  1798. }
  1799. if (!buffer) {
  1800. Tools.LoadFile(url, data => {
  1801. callback(data);
  1802. }, null, scene.database, true, onerror);
  1803. } else {
  1804. callback(buffer);
  1805. }
  1806. // image format processing
  1807. } else {
  1808. var onload = (img) => {
  1809. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight) => {
  1810. var isPot = (img.width === potWidth && img.height === potHeight);
  1811. if (!isPot) {
  1812. this._prepareWorkingCanvas();
  1813. this._workingCanvas.width = potWidth;
  1814. this._workingCanvas.height = potHeight;
  1815. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1816. this._workingContext.imageSmoothingEnabled = false;
  1817. this._workingContext.mozImageSmoothingEnabled = false;
  1818. this._workingContext.oImageSmoothingEnabled = false;
  1819. this._workingContext.webkitImageSmoothingEnabled = false;
  1820. this._workingContext.msImageSmoothingEnabled = false;
  1821. }
  1822. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  1823. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1824. this._workingContext.imageSmoothingEnabled = true;
  1825. this._workingContext.mozImageSmoothingEnabled = true;
  1826. this._workingContext.oImageSmoothingEnabled = true;
  1827. this._workingContext.webkitImageSmoothingEnabled = true;
  1828. this._workingContext.msImageSmoothingEnabled = true;
  1829. }
  1830. }
  1831. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? this._gl.RGB :this._gl.RGBA);
  1832. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  1833. }, samplingMode);
  1834. };
  1835. if (!fromData || isBase64)
  1836. Tools.LoadImage(url, onload, onerror, scene.database);
  1837. else if (buffer instanceof Array || typeof buffer === "string")
  1838. Tools.LoadImage(buffer, onload, onerror, scene.database);
  1839. else
  1840. onload(buffer);
  1841. }
  1842. return texture;
  1843. }
  1844. private _getInternalFormat(format: number): number {
  1845. var internalFormat = this._gl.RGBA;
  1846. switch (format) {
  1847. case Engine.TEXTUREFORMAT_ALPHA:
  1848. internalFormat = this._gl.ALPHA;
  1849. break;
  1850. case Engine.TEXTUREFORMAT_LUMINANCE:
  1851. internalFormat = this._gl.LUMINANCE;
  1852. break;
  1853. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  1854. internalFormat = this._gl.LUMINANCE_ALPHA;
  1855. break;
  1856. case Engine.TEXTUREFORMAT_RGB:
  1857. internalFormat = this._gl.RGB;
  1858. break;
  1859. case Engine.TEXTUREFORMAT_RGBA:
  1860. internalFormat = this._gl.RGBA;
  1861. break;
  1862. }
  1863. return internalFormat;
  1864. }
  1865. public updateRawTexture(texture: WebGLTexture, data: ArrayBufferView, format: number, invertY: boolean, compression: string = null): void {
  1866. var internalFormat = this._getInternalFormat(format);
  1867. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1868. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  1869. if (texture._width % 4 !== 0) {
  1870. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  1871. }
  1872. if (compression) {
  1873. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  1874. } else {
  1875. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  1876. }
  1877. if (texture.generateMipMaps) {
  1878. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1879. }
  1880. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1881. this.resetTextureCache();
  1882. texture.isReady = true;
  1883. }
  1884. public createRawTexture(data: ArrayBufferView, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: string = null): WebGLTexture {
  1885. var texture = this._gl.createTexture();
  1886. texture._baseWidth = width;
  1887. texture._baseHeight = height;
  1888. texture._width = width;
  1889. texture._height = height;
  1890. texture.references = 1;
  1891. this.updateRawTexture(texture, data, format, invertY, compression);
  1892. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1893. // Filters
  1894. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1895. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1896. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1897. if (generateMipMaps) {
  1898. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1899. }
  1900. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1901. texture.samplingMode = samplingMode;
  1902. this._loadedTexturesCache.push(texture);
  1903. return texture;
  1904. }
  1905. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): WebGLTexture {
  1906. var texture = this._gl.createTexture();
  1907. texture._baseWidth = width;
  1908. texture._baseHeight = height;
  1909. if (generateMipMaps) {
  1910. width = Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  1911. height = Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  1912. }
  1913. this.resetTextureCache();
  1914. texture._width = width;
  1915. texture._height = height;
  1916. texture.isReady = false;
  1917. texture.generateMipMaps = generateMipMaps;
  1918. texture.references = 1;
  1919. texture.samplingMode = samplingMode;
  1920. this.updateTextureSamplingMode(samplingMode, texture);
  1921. this._loadedTexturesCache.push(texture);
  1922. return texture;
  1923. }
  1924. public updateTextureSamplingMode(samplingMode: number, texture: WebGLTexture): void {
  1925. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  1926. if (texture.isCube) {
  1927. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  1928. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1929. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1930. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  1931. } else {
  1932. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1933. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1934. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1935. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1936. }
  1937. texture.samplingMode = samplingMode;
  1938. }
  1939. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  1940. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1941. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  1942. if (premulAlpha) {
  1943. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  1944. }
  1945. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  1946. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  1947. if (texture.generateMipMaps) {
  1948. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1949. }
  1950. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1951. if (premulAlpha) {
  1952. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  1953. }
  1954. this.resetTextureCache();
  1955. texture.isReady = true;
  1956. }
  1957. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  1958. if (texture._isDisabled) {
  1959. return;
  1960. }
  1961. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1962. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  1963. try {
  1964. // Testing video texture support
  1965. if (this._videoTextureSupported === undefined) {
  1966. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1967. if (this._gl.getError() !== 0) {
  1968. this._videoTextureSupported = false;
  1969. } else {
  1970. this._videoTextureSupported = true;
  1971. }
  1972. }
  1973. // Copy video through the current working canvas if video texture is not supported
  1974. if (!this._videoTextureSupported) {
  1975. if (!texture._workingCanvas) {
  1976. texture._workingCanvas = document.createElement("canvas");
  1977. texture._workingContext = texture._workingCanvas.getContext("2d");
  1978. texture._workingCanvas.width = texture._width;
  1979. texture._workingCanvas.height = texture._height;
  1980. }
  1981. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  1982. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  1983. } else {
  1984. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1985. }
  1986. if (texture.generateMipMaps) {
  1987. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1988. }
  1989. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1990. this.resetTextureCache();
  1991. texture.isReady = true;
  1992. } catch (ex) {
  1993. // Something unexpected
  1994. // Let's disable the texture
  1995. texture._isDisabled = true;
  1996. }
  1997. }
  1998. public createRenderTargetTexture(size: any, options): WebGLTexture {
  1999. // old version had a "generateMipMaps" arg instead of options.
  2000. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  2001. // in the same way, generateDepthBuffer is defaulted to true
  2002. var generateMipMaps = false;
  2003. var generateDepthBuffer = true;
  2004. var generateStencilBuffer = false;
  2005. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2006. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2007. if (options !== undefined) {
  2008. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  2009. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2010. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  2011. type = options.type === undefined ? type : options.type;
  2012. if (options.samplingMode !== undefined) {
  2013. samplingMode = options.samplingMode;
  2014. }
  2015. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  2016. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  2017. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2018. }
  2019. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  2020. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  2021. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2022. }
  2023. }
  2024. var gl = this._gl;
  2025. var texture = gl.createTexture();
  2026. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  2027. var width = size.width || size;
  2028. var height = size.height || size;
  2029. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  2030. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  2031. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2032. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  2033. }
  2034. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2035. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2036. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2037. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2038. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  2039. // Create the framebuffer
  2040. var framebuffer = gl.createFramebuffer();
  2041. this.bindUnboundFramebuffer(framebuffer);
  2042. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  2043. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  2044. if (generateMipMaps) {
  2045. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2046. }
  2047. // Unbind
  2048. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2049. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2050. this.bindUnboundFramebuffer(null);
  2051. texture._framebuffer = framebuffer;
  2052. texture._baseWidth = width;
  2053. texture._baseHeight = height;
  2054. texture._width = width;
  2055. texture._height = height;
  2056. texture.isReady = true;
  2057. texture.samples = 1;
  2058. texture.generateMipMaps = generateMipMaps;
  2059. texture.references = 1;
  2060. texture.samplingMode = samplingMode;
  2061. texture.type = type;
  2062. texture._generateDepthBuffer = generateDepthBuffer;
  2063. texture._generateStencilBuffer = generateStencilBuffer;
  2064. this.resetTextureCache();
  2065. this._loadedTexturesCache.push(texture);
  2066. return texture;
  2067. }
  2068. private _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): WebGLRenderbuffer {
  2069. var depthStencilBuffer: WebGLRenderbuffer = null;
  2070. var gl = this._gl;
  2071. // Create the depth/stencil buffer
  2072. if (generateStencilBuffer) {
  2073. depthStencilBuffer = gl.createRenderbuffer();
  2074. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  2075. if (samples > 1) {
  2076. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  2077. } else {
  2078. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  2079. }
  2080. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  2081. }
  2082. else if (generateDepthBuffer) {
  2083. depthStencilBuffer = gl.createRenderbuffer();
  2084. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  2085. if (samples > 1) {
  2086. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  2087. } else {
  2088. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  2089. }
  2090. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  2091. }
  2092. return depthStencilBuffer;
  2093. }
  2094. public updateRenderTargetTextureSampleCount(texture: WebGLTexture, samples: number): number {
  2095. if (this.webGLVersion < 2) {
  2096. return 1;
  2097. }
  2098. if (texture.samples === samples) {
  2099. return samples;
  2100. }
  2101. var gl = this._gl;
  2102. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  2103. // Dispose previous render buffers
  2104. if (texture._depthStencilBuffer) {
  2105. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  2106. }
  2107. if (texture._MSAAFramebuffer) {
  2108. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  2109. }
  2110. if (texture._MSAARenderBuffer) {
  2111. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  2112. }
  2113. if (samples > 1) {
  2114. texture._MSAAFramebuffer = gl.createFramebuffer();
  2115. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  2116. var colorRenderbuffer = gl.createRenderbuffer();
  2117. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  2118. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  2119. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  2120. texture._MSAARenderBuffer = colorRenderbuffer;
  2121. } else {
  2122. this.bindUnboundFramebuffer(texture._framebuffer);
  2123. }
  2124. texture.samples = samples;
  2125. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  2126. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2127. this.bindUnboundFramebuffer(null);
  2128. return samples;
  2129. }
  2130. public createRenderTargetCubeTexture(size: number, options?: any): WebGLTexture {
  2131. var gl = this._gl;
  2132. var texture = gl.createTexture();
  2133. var generateMipMaps = true;
  2134. var generateDepthBuffer = true;
  2135. var generateStencilBuffer = false;
  2136. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2137. if (options !== undefined) {
  2138. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  2139. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2140. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  2141. if (options.samplingMode !== undefined) {
  2142. samplingMode = options.samplingMode;
  2143. }
  2144. }
  2145. texture.isCube = true;
  2146. texture.references = 1;
  2147. texture.generateMipMaps = generateMipMaps;
  2148. texture.references = 1;
  2149. texture.samples = 1;
  2150. texture.samplingMode = samplingMode;
  2151. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  2152. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2153. for (var face = 0; face < 6; face++) {
  2154. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  2155. }
  2156. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  2157. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  2158. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2159. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2160. // Create the framebuffer
  2161. var framebuffer = gl.createFramebuffer();
  2162. this.bindUnboundFramebuffer(framebuffer);
  2163. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  2164. // Mipmaps
  2165. if (texture.generateMipMaps) {
  2166. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2167. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2168. }
  2169. // Unbind
  2170. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2171. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2172. this.bindUnboundFramebuffer(null);
  2173. texture._framebuffer = framebuffer;
  2174. texture._width = size;
  2175. texture._height = size;
  2176. texture.isReady = true;
  2177. this.resetTextureCache();
  2178. this._loadedTexturesCache.push(texture);
  2179. return texture;
  2180. }
  2181. public createCubeTexture(rootUrl: string, scene: Scene, files: string[], noMipmap?: boolean, onLoad: () => void = null, onError: () => void = null, format?: number): WebGLTexture {
  2182. var gl = this._gl;
  2183. var texture = gl.createTexture();
  2184. texture.isCube = true;
  2185. texture.url = rootUrl;
  2186. texture.references = 1;
  2187. texture.onLoadedCallbacks = [];
  2188. var isKTX = false;
  2189. var lastDot = rootUrl.lastIndexOf('.');
  2190. var extension = rootUrl.substring(lastDot).toLowerCase();
  2191. if (this._textureFormatInUse) {
  2192. extension = this._textureFormatInUse;
  2193. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  2194. isKTX = true;
  2195. }
  2196. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  2197. if (isDDS) {
  2198. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  2199. }
  2200. if (isKTX) {
  2201. Tools.LoadFile(rootUrl, data => {
  2202. var ktx = new Internals.KhronosTextureContainer(data, 6);
  2203. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  2204. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2205. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  2206. ktx.uploadLevels(this._gl, !noMipmap);
  2207. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2208. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  2209. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2210. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2211. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2212. this.resetTextureCache();
  2213. texture._width = ktx.pixelWidth;
  2214. texture._height = ktx.pixelHeight;
  2215. texture.isReady = true;
  2216. }, null, null, true, onError);
  2217. } else if (isDDS) {
  2218. Tools.LoadFile(rootUrl, data => {
  2219. var info = Internals.DDSTools.GetDDSInfo(data);
  2220. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  2221. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2222. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  2223. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 6);
  2224. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  2225. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2226. }
  2227. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2228. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  2229. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2230. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2231. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2232. this.resetTextureCache();
  2233. texture._width = info.width;
  2234. texture._height = info.height;
  2235. texture.isReady = true;
  2236. }, null, null, true, onError);
  2237. } else {
  2238. cascadeLoad(rootUrl, scene, imgs => {
  2239. var width = Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  2240. var height = width;
  2241. this._prepareWorkingCanvas();
  2242. this._workingCanvas.width = width;
  2243. this._workingCanvas.height = height;
  2244. var faces = [
  2245. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  2246. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  2247. ];
  2248. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2249. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  2250. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  2251. for (var index = 0; index < faces.length; index++) {
  2252. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  2253. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  2254. }
  2255. if (!noMipmap) {
  2256. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2257. }
  2258. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2259. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  2260. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2261. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2262. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2263. this.resetTextureCache();
  2264. texture._width = width;
  2265. texture._height = height;
  2266. texture.isReady = true;
  2267. texture.onLoadedCallbacks.forEach(callback => {
  2268. callback();
  2269. });
  2270. if (onLoad) {
  2271. onLoad();
  2272. }
  2273. }, files, onError);
  2274. }
  2275. this._loadedTexturesCache.push(texture);
  2276. return texture;
  2277. }
  2278. public updateTextureSize(texture: WebGLTexture, width: number, height: number) {
  2279. texture._width = width;
  2280. texture._height = height;
  2281. texture._size = width * height;
  2282. texture._baseWidth = width;
  2283. texture._baseHeight = height;
  2284. }
  2285. public createRawCubeTexture(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  2286. callback: (ArrayBuffer: ArrayBuffer) => ArrayBufferView[],
  2287. mipmmapGenerator: ((faces: ArrayBufferView[]) => ArrayBufferView[][]), onLoad: () => void = null, onError: () => void = null): WebGLTexture {
  2288. var gl = this._gl;
  2289. var texture = gl.createTexture();
  2290. scene._addPendingData(texture);
  2291. texture.isCube = true;
  2292. texture.references = 1;
  2293. texture.url = url;
  2294. var textureType = gl.UNSIGNED_BYTE;
  2295. if (type === Engine.TEXTURETYPE_FLOAT) {
  2296. textureType = gl.FLOAT;
  2297. }
  2298. var internalFormat = this._getInternalFormat(format);
  2299. var needConversion = false;
  2300. if (internalFormat === gl.RGB) {
  2301. internalFormat = gl.RGBA;
  2302. needConversion = true;
  2303. }
  2304. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  2305. var width = size;
  2306. var height = width;
  2307. var isPot = (Tools.IsExponentOfTwo(width) && Tools.IsExponentOfTwo(height));
  2308. texture._width = width;
  2309. texture._height = height;
  2310. var onerror = () => {
  2311. scene._removePendingData(texture);
  2312. if (onError) {
  2313. onError();
  2314. }
  2315. };
  2316. var internalCallback = (data) => {
  2317. var rgbeDataArrays = callback(data);
  2318. var facesIndex = [
  2319. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  2320. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  2321. ];
  2322. width = texture._width;
  2323. height = texture._height;
  2324. isPot = (Tools.IsExponentOfTwo(width) && Tools.IsExponentOfTwo(height));
  2325. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2326. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  2327. if (mipmmapGenerator) {
  2328. var arrayTemp: ArrayBufferView[] = [];
  2329. // Data are known to be in +X +Y +Z -X -Y -Z
  2330. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  2331. arrayTemp.push(rgbeDataArrays[0]); // +X
  2332. arrayTemp.push(rgbeDataArrays[3]); // -X
  2333. arrayTemp.push(rgbeDataArrays[1]); // +Y
  2334. arrayTemp.push(rgbeDataArrays[4]); // -Y
  2335. arrayTemp.push(rgbeDataArrays[2]); // +Z
  2336. arrayTemp.push(rgbeDataArrays[5]); // -Z
  2337. var mipData = mipmmapGenerator(arrayTemp);
  2338. // mipData is order in +X -X +Y -Y +Z -Z
  2339. var mipFaces = [0, 2, 4, 1, 3, 5];
  2340. for (var level = 0; level < mipData.length; level++) {
  2341. var mipSize = width >> level;
  2342. for (let mipIndex in mipFaces) {
  2343. let mipFaceData = mipData[level][mipFaces[mipIndex]];
  2344. if (needConversion) {
  2345. mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  2346. }
  2347. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  2348. }
  2349. }
  2350. }
  2351. else {
  2352. // Data are known to be in +X +Y +Z -X -Y -Z
  2353. for (let index = 0; index < facesIndex.length; index++) {
  2354. let faceData = rgbeDataArrays[index];
  2355. if (needConversion) {
  2356. faceData = this._convertRGBtoRGBATextureData(faceData, width, height, type);
  2357. }
  2358. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  2359. }
  2360. if (!noMipmap && isPot) {
  2361. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2362. }
  2363. else {
  2364. noMipmap = true;
  2365. }
  2366. }
  2367. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  2368. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2369. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2370. }
  2371. else if (textureType === Engine.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  2372. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2373. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2374. }
  2375. else {
  2376. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2377. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  2378. }
  2379. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2380. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2381. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2382. texture.isReady = true;
  2383. this.resetTextureCache();
  2384. scene._removePendingData(texture);
  2385. if (onLoad) {
  2386. onLoad();
  2387. }
  2388. };
  2389. Tools.LoadFile(url, data => {
  2390. internalCallback(data);
  2391. }, onerror, scene.database, true);
  2392. return texture;
  2393. };
  2394. private _convertRGBtoRGBATextureData(rgbData: ArrayBufferView, width: number, height: number, textureType: number): ArrayBufferView {
  2395. // Create new RGBA data container.
  2396. var rgbaData: ArrayBufferView;
  2397. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  2398. rgbaData = new Float32Array(width * height * 4);
  2399. }
  2400. else {
  2401. rgbaData = new Uint32Array(width * height * 4);
  2402. }
  2403. // Convert each pixel.
  2404. for (let x = 0; x < width; x++) {
  2405. for (let y = 0; y < height; y++) {
  2406. let index = (y * width + x) * 3;
  2407. let newIndex = (y * width + x) * 4;
  2408. // Map Old Value to new value.
  2409. rgbaData[newIndex + 0] = rgbData[index + 0];
  2410. rgbaData[newIndex + 1] = rgbData[index + 1];
  2411. rgbaData[newIndex + 2] = rgbData[index + 2];
  2412. // Add fully opaque alpha channel.
  2413. rgbaData[newIndex + 3] = 1;
  2414. }
  2415. }
  2416. return rgbaData;
  2417. }
  2418. public _releaseTexture(texture: WebGLTexture): void {
  2419. var gl = this._gl;
  2420. if (texture._framebuffer) {
  2421. gl.deleteFramebuffer(texture._framebuffer);
  2422. }
  2423. if (texture._depthStencilBuffer) {
  2424. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  2425. }
  2426. if (texture._MSAAFramebuffer) {
  2427. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  2428. }
  2429. if (texture._MSAARenderBuffer) {
  2430. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  2431. }
  2432. gl.deleteTexture(texture);
  2433. // Unbind channels
  2434. this.unbindAllTextures();
  2435. var index = this._loadedTexturesCache.indexOf(texture);
  2436. if (index !== -1) {
  2437. this._loadedTexturesCache.splice(index, 1);
  2438. }
  2439. }
  2440. private setProgram(program: WebGLProgram): void {
  2441. if (this._currentProgram !== program) {
  2442. this._gl.useProgram(program);
  2443. this._currentProgram = program;
  2444. }
  2445. }
  2446. public bindSamplers(effect: Effect): void {
  2447. this.setProgram(effect.getProgram());
  2448. var samplers = effect.getSamplers();
  2449. for (var index = 0; index < samplers.length; index++) {
  2450. var uniform = effect.getUniform(samplers[index]);
  2451. this._gl.uniform1i(uniform, index);
  2452. }
  2453. this._currentEffect = null;
  2454. }
  2455. private activateTexture(texture: number): void {
  2456. if (this._activeTexture !== texture) {
  2457. this._gl.activeTexture(texture);
  2458. this._activeTexture = texture;
  2459. }
  2460. }
  2461. public _bindTextureDirectly(target: number, texture: WebGLTexture): void {
  2462. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  2463. this._gl.bindTexture(target, texture);
  2464. this._activeTexturesCache[this._activeTexture] = texture;
  2465. }
  2466. }
  2467. public _bindTexture(channel: number, texture: WebGLTexture): void {
  2468. if (channel < 0) {
  2469. return;
  2470. }
  2471. this.activateTexture(this._gl.TEXTURE0 + channel);
  2472. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2473. }
  2474. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  2475. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  2476. }
  2477. public unbindAllTextures(): void {
  2478. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  2479. this.activateTexture(this._gl["TEXTURE" + channel]);
  2480. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2481. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2482. }
  2483. }
  2484. public setTexture(channel: number, uniform: WebGLUniformLocation, texture: BaseTexture): void {
  2485. if (channel < 0) {
  2486. return;
  2487. }
  2488. this._gl.uniform1i(uniform, channel);
  2489. this._setTexture(channel, texture);
  2490. }
  2491. private _setTexture(channel: number, texture: BaseTexture): void {
  2492. // Not ready?
  2493. if (!texture || !texture.isReady()) {
  2494. if (this._activeTexturesCache[channel] != null) {
  2495. this.activateTexture(this._gl["TEXTURE" + channel]);
  2496. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2497. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2498. }
  2499. return;
  2500. }
  2501. // Video
  2502. var alreadyActivated = false;
  2503. if (texture instanceof VideoTexture) {
  2504. this.activateTexture(this._gl["TEXTURE" + channel]);
  2505. alreadyActivated = true;
  2506. texture.update();
  2507. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  2508. texture.delayLoad();
  2509. return;
  2510. }
  2511. var internalTexture = texture.getInternalTexture();
  2512. if (this._activeTexturesCache[channel] === internalTexture) {
  2513. return;
  2514. }
  2515. if (!alreadyActivated) {
  2516. this.activateTexture(this._gl["TEXTURE" + channel]);
  2517. }
  2518. if (internalTexture.isCube) {
  2519. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  2520. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  2521. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  2522. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  2523. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  2524. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  2525. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  2526. }
  2527. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  2528. } else {
  2529. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  2530. if (internalTexture._cachedWrapU !== texture.wrapU) {
  2531. internalTexture._cachedWrapU = texture.wrapU;
  2532. switch (texture.wrapU) {
  2533. case Texture.WRAP_ADDRESSMODE:
  2534. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  2535. break;
  2536. case Texture.CLAMP_ADDRESSMODE:
  2537. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  2538. break;
  2539. case Texture.MIRROR_ADDRESSMODE:
  2540. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  2541. break;
  2542. }
  2543. }
  2544. if (internalTexture._cachedWrapV !== texture.wrapV) {
  2545. internalTexture._cachedWrapV = texture.wrapV;
  2546. switch (texture.wrapV) {
  2547. case Texture.WRAP_ADDRESSMODE:
  2548. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  2549. break;
  2550. case Texture.CLAMP_ADDRESSMODE:
  2551. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  2552. break;
  2553. case Texture.MIRROR_ADDRESSMODE:
  2554. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  2555. break;
  2556. }
  2557. }
  2558. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  2559. }
  2560. }
  2561. public setTextureArray(channel: number, uniform: WebGLUniformLocation, textures: BaseTexture[]): void {
  2562. if (channel < 0) {
  2563. return;
  2564. }
  2565. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  2566. this._textureUnits = new Int32Array(textures.length);
  2567. }
  2568. for (let i = 0; i < textures.length; i++) {
  2569. this._textureUnits[i] = channel + i;
  2570. }
  2571. this._gl.uniform1iv(uniform, this._textureUnits);
  2572. for (var index = 0; index < textures.length; index++) {
  2573. this._setTexture(channel + index, textures[index]);
  2574. }
  2575. }
  2576. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  2577. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  2578. var value = texture.anisotropicFilteringLevel;
  2579. if (texture.getInternalTexture().samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  2580. value = 1;
  2581. }
  2582. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  2583. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  2584. texture._cachedAnisotropicFilteringLevel = value;
  2585. }
  2586. }
  2587. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  2588. var data = new Uint8Array(height * width * 4);
  2589. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  2590. return data;
  2591. }
  2592. /**
  2593. * Add an externaly attached data from its key.
  2594. * This method call will fail and return false, if such key already exists.
  2595. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  2596. * @param key the unique key that identifies the data
  2597. * @param data the data object to associate to the key for this Engine instance
  2598. * @return true if no such key were already present and the data was added successfully, false otherwise
  2599. */
  2600. public addExternalData<T>(key: string, data: T): boolean {
  2601. return this._externalData.add(key, data);
  2602. }
  2603. /**
  2604. * Get an externaly attached data from its key
  2605. * @param key the unique key that identifies the data
  2606. * @return the associated data, if present (can be null), or undefined if not present
  2607. */
  2608. public getExternalData<T>(key: string): T {
  2609. return <T>this._externalData.get(key);
  2610. }
  2611. /**
  2612. * Get an externaly attached data from its key, create it using a factory if it's not already present
  2613. * @param key the unique key that identifies the data
  2614. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  2615. * @return the associated data, can be null if the factory returned null.
  2616. */
  2617. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  2618. return <T>this._externalData.getOrAddWithFactory(key, factory);
  2619. }
  2620. /**
  2621. * Remove an externaly attached data from the Engine instance
  2622. * @param key the unique key that identifies the data
  2623. * @return true if the data was successfully removed, false if it doesn't exist
  2624. */
  2625. public removeExternalData(key): boolean {
  2626. return this._externalData.remove(key);
  2627. }
  2628. public releaseInternalTexture(texture: WebGLTexture): void {
  2629. if (!texture) {
  2630. return;
  2631. }
  2632. texture.references--;
  2633. // Final reference ?
  2634. if (texture.references === 0) {
  2635. var texturesCache = this.getLoadedTexturesCache();
  2636. var index = texturesCache.indexOf(texture);
  2637. if (index > -1) {
  2638. texturesCache.splice(index, 1);
  2639. }
  2640. this._releaseTexture(texture);
  2641. }
  2642. }
  2643. public unbindAllAttributes() {
  2644. if (this._mustWipeVertexAttributes) {
  2645. this._mustWipeVertexAttributes = false;
  2646. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  2647. this._gl.disableVertexAttribArray(i);
  2648. this._vertexAttribArraysEnabled[i] = false;
  2649. this._currentBufferPointers[i] = null;
  2650. }
  2651. return;
  2652. }
  2653. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  2654. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  2655. continue;
  2656. }
  2657. this._gl.disableVertexAttribArray(i);
  2658. this._vertexAttribArraysEnabled[i] = false;
  2659. this._currentBufferPointers[i] = null;
  2660. }
  2661. }
  2662. // Dispose
  2663. public dispose(): void {
  2664. this.hideLoadingUI();
  2665. this.stopRenderLoop();
  2666. // Release scenes
  2667. while (this.scenes.length) {
  2668. this.scenes[0].dispose();
  2669. }
  2670. // Release audio engine
  2671. Engine.audioEngine.dispose();
  2672. // Release effects
  2673. for (var name in this._compiledEffects) {
  2674. this._gl.deleteProgram(this._compiledEffects[name]._program);
  2675. }
  2676. // Unbind
  2677. this.unbindAllAttributes();
  2678. this._gl = null;
  2679. //WebVR
  2680. this.disableVR();
  2681. // Events
  2682. window.removeEventListener("blur", this._onBlur);
  2683. window.removeEventListener("focus", this._onFocus);
  2684. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  2685. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  2686. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  2687. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  2688. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  2689. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  2690. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  2691. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  2692. // Remove from Instances
  2693. var index = Engine.Instances.indexOf(this);
  2694. if (index >= 0) {
  2695. Engine.Instances.splice(index, 1);
  2696. }
  2697. }
  2698. // Loading screen
  2699. public displayLoadingUI(): void {
  2700. this._loadingScreen.displayLoadingUI();
  2701. }
  2702. public hideLoadingUI(): void {
  2703. this._loadingScreen.hideLoadingUI();
  2704. }
  2705. public get loadingScreen(): ILoadingScreen {
  2706. return this._loadingScreen;
  2707. }
  2708. public set loadingScreen(loadingScreen: ILoadingScreen) {
  2709. this._loadingScreen = loadingScreen;
  2710. }
  2711. public set loadingUIText(text: string) {
  2712. this._loadingScreen.loadingUIText = text;
  2713. }
  2714. public set loadingUIBackgroundColor(color: string) {
  2715. this._loadingScreen.loadingUIBackgroundColor = color;
  2716. }
  2717. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  2718. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  2719. }
  2720. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  2721. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  2722. }
  2723. public getVertexShaderSource(program: WebGLProgram): string {
  2724. var shaders = this._gl.getAttachedShaders(program);
  2725. return this._gl.getShaderSource(shaders[0]);
  2726. }
  2727. public getFragmentShaderSource(program: WebGLProgram): string {
  2728. var shaders = this._gl.getAttachedShaders(program);
  2729. return this._gl.getShaderSource(shaders[1]);
  2730. }
  2731. // FPS
  2732. public getFps(): number {
  2733. return this.fps;
  2734. }
  2735. public getDeltaTime(): number {
  2736. return this.deltaTime;
  2737. }
  2738. private _measureFps(): void {
  2739. this.previousFramesDuration.push(Tools.Now);
  2740. var length = this.previousFramesDuration.length;
  2741. if (length >= 2) {
  2742. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  2743. }
  2744. if (length >= this.fpsRange) {
  2745. if (length > this.fpsRange) {
  2746. this.previousFramesDuration.splice(0, 1);
  2747. length = this.previousFramesDuration.length;
  2748. }
  2749. var sum = 0;
  2750. for (var id = 0; id < length - 1; id++) {
  2751. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  2752. }
  2753. this.fps = 1000.0 / (sum / (length - 1));
  2754. }
  2755. }
  2756. private _canRenderToFloatFramebuffer(): boolean {
  2757. if (this._webGLVersion > 1) {
  2758. return this._caps.colorBufferFloat;
  2759. }
  2760. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  2761. }
  2762. private _canRenderToHalfFloatFramebuffer(): boolean {
  2763. if (this._webGLVersion > 1) {
  2764. return this._caps.colorBufferFloat;
  2765. }
  2766. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  2767. }
  2768. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  2769. private _canRenderToFramebuffer(type: number): boolean {
  2770. let gl = this._gl;
  2771. //clear existing errors
  2772. while (gl.getError() !== gl.NO_ERROR) { }
  2773. let successful = true;
  2774. let texture = gl.createTexture();
  2775. gl.bindTexture(gl.TEXTURE_2D, texture);
  2776. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  2777. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2778. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2779. let fb = gl.createFramebuffer();
  2780. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  2781. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  2782. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  2783. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  2784. successful = successful && (gl.getError() === gl.NO_ERROR);
  2785. //try render by clearing frame buffer's color buffer
  2786. if (successful) {
  2787. gl.clear(gl.COLOR_BUFFER_BIT);
  2788. successful = successful && (gl.getError() === gl.NO_ERROR);
  2789. }
  2790. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  2791. if (successful) {
  2792. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  2793. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  2794. let readFormat = gl.RGBA;
  2795. let readType = gl.UNSIGNED_BYTE;
  2796. let buffer = new Uint8Array(4);
  2797. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  2798. successful = successful && (gl.getError() === gl.NO_ERROR);
  2799. }
  2800. //clean up
  2801. gl.deleteTexture(texture);
  2802. gl.deleteFramebuffer(fb);
  2803. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  2804. //clear accumulated errors
  2805. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  2806. return successful;
  2807. }
  2808. private _getWebGLTextureType(type: number): number {
  2809. if (type === Engine.TEXTURETYPE_FLOAT) {
  2810. return this._gl.FLOAT;
  2811. }
  2812. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  2813. // Add Half Float Constant.
  2814. return Engine.HALF_FLOAT_OES;
  2815. }
  2816. return this._gl.UNSIGNED_BYTE;
  2817. };
  2818. private _getRGBABufferInternalSizedFormat(type: number): number {
  2819. if (this._webGLVersion === 1) {
  2820. return this._gl.RGBA;
  2821. }
  2822. if (type === Engine.TEXTURETYPE_FLOAT) {
  2823. return Engine.RGBA32F;
  2824. }
  2825. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  2826. return Engine.RGBA16F;
  2827. }
  2828. return this._gl.RGBA;
  2829. };
  2830. // Statics
  2831. public static isSupported(): boolean {
  2832. try {
  2833. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  2834. if (navigator.isCocoonJS) {
  2835. return true;
  2836. }
  2837. var tempcanvas = document.createElement("canvas");
  2838. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  2839. return gl != null && !!window.WebGLRenderingContext;
  2840. } catch (e) {
  2841. return false;
  2842. }
  2843. }
  2844. }
  2845. }