babylon.engine.ts 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319
  1. module BABYLON {
  2. var compileShader = (gl: WebGLRenderingContext, source: string, type: string, defines: string): WebGLShader => {
  3. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  4. gl.shaderSource(shader, (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 getWebGLTextureType = (gl: WebGLRenderingContext, type: number): number => {
  12. var textureType = gl.UNSIGNED_BYTE;
  13. if (type === Engine.TEXTURETYPE_FLOAT)
  14. textureType = gl.FLOAT;
  15. return textureType;
  16. };
  17. var getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
  18. var magFilter = gl.NEAREST;
  19. var minFilter = gl.NEAREST;
  20. if (samplingMode === Texture.BILINEAR_SAMPLINGMODE) {
  21. magFilter = gl.LINEAR;
  22. if (generateMipMaps) {
  23. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  24. } else {
  25. minFilter = gl.LINEAR;
  26. }
  27. } else if (samplingMode === Texture.TRILINEAR_SAMPLINGMODE) {
  28. magFilter = gl.LINEAR;
  29. if (generateMipMaps) {
  30. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  31. } else {
  32. minFilter = gl.LINEAR;
  33. }
  34. } else if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  35. magFilter = gl.NEAREST;
  36. if (generateMipMaps) {
  37. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  38. } else {
  39. minFilter = gl.NEAREST;
  40. }
  41. }
  42. return {
  43. min: minFilter,
  44. mag: magFilter
  45. }
  46. }
  47. var prepareWebGLTexture = (texture: WebGLTexture, gl: WebGLRenderingContext, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  48. processFunction: (width: number, height: number) => void, onLoad: () => void, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE) => {
  49. var engine = scene.getEngine();
  50. var potWidth = Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  51. var potHeight = Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  52. gl.bindTexture(gl.TEXTURE_2D, texture);
  53. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  54. texture._baseWidth = width;
  55. texture._baseHeight = height;
  56. texture._width = potWidth;
  57. texture._height = potHeight;
  58. texture.isReady = true;
  59. processFunction(potWidth, potHeight);
  60. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  61. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  62. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  63. if (!noMipmap && !isCompressed) {
  64. gl.generateMipmap(gl.TEXTURE_2D);
  65. }
  66. gl.bindTexture(gl.TEXTURE_2D, null);
  67. engine.resetTextureCache();
  68. scene._removePendingData(texture);
  69. if (onLoad) {
  70. onLoad();
  71. }
  72. };
  73. var partialLoad = (url: string, index: number, loadedImages: any, scene,
  74. onfinish: (images: HTMLImageElement[]) => void) => {
  75. var img: HTMLImageElement;
  76. var onload = () => {
  77. loadedImages[index] = img;
  78. loadedImages._internalCount++;
  79. scene._removePendingData(img);
  80. if (loadedImages._internalCount === 6) {
  81. onfinish(loadedImages);
  82. }
  83. };
  84. var onerror = () => {
  85. scene._removePendingData(img);
  86. };
  87. img = Tools.LoadImage(url, onload, onerror, scene.database);
  88. scene._addPendingData(img);
  89. }
  90. var cascadeLoad = (rootUrl: string, scene,
  91. onfinish: (images: HTMLImageElement[]) => void, files: string[]) => {
  92. var loadedImages: any = [];
  93. loadedImages._internalCount = 0;
  94. for (var index = 0; index < 6; index++) {
  95. partialLoad(files[index], index, loadedImages, scene, onfinish);
  96. }
  97. };
  98. export class EngineCapabilities {
  99. public maxTexturesImageUnits: number;
  100. public maxTextureSize: number;
  101. public maxCubemapTextureSize: number;
  102. public maxRenderTextureSize: number;
  103. public standardDerivatives: boolean;
  104. public s3tc;
  105. public textureFloat: boolean;
  106. public textureAnisotropicFilterExtension;
  107. public maxAnisotropy: number;
  108. public instancedArrays;
  109. public uintIndices: boolean;
  110. public highPrecisionShaderSupported: boolean;
  111. public fragmentDepthSupported: boolean;
  112. public textureFloatLinearFiltering: boolean;
  113. public textureLOD: boolean;
  114. public drawBuffersExtension;
  115. }
  116. /**
  117. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  118. */
  119. export class Engine {
  120. // Const statics
  121. private static _ALPHA_DISABLE = 0;
  122. private static _ALPHA_ADD = 1;
  123. private static _ALPHA_COMBINE = 2;
  124. private static _ALPHA_SUBTRACT = 3;
  125. private static _ALPHA_MULTIPLY = 4;
  126. private static _ALPHA_MAXIMIZED = 5;
  127. private static _ALPHA_ONEONE = 6;
  128. private static _DELAYLOADSTATE_NONE = 0;
  129. private static _DELAYLOADSTATE_LOADED = 1;
  130. private static _DELAYLOADSTATE_LOADING = 2;
  131. private static _DELAYLOADSTATE_NOTLOADED = 4;
  132. private static _TEXTUREFORMAT_ALPHA = 0;
  133. private static _TEXTUREFORMAT_LUMINANCE = 1;
  134. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  135. private static _TEXTUREFORMAT_RGB = 4;
  136. private static _TEXTUREFORMAT_RGBA = 5;
  137. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  138. private static _TEXTURETYPE_FLOAT = 1;
  139. public static get ALPHA_DISABLE(): number {
  140. return Engine._ALPHA_DISABLE;
  141. }
  142. public static get ALPHA_ONEONE(): number {
  143. return Engine._ALPHA_ONEONE;
  144. }
  145. public static get ALPHA_ADD(): number {
  146. return Engine._ALPHA_ADD;
  147. }
  148. public static get ALPHA_COMBINE(): number {
  149. return Engine._ALPHA_COMBINE;
  150. }
  151. public static get ALPHA_SUBTRACT(): number {
  152. return Engine._ALPHA_SUBTRACT;
  153. }
  154. public static get ALPHA_MULTIPLY(): number {
  155. return Engine._ALPHA_MULTIPLY;
  156. }
  157. public static get ALPHA_MAXIMIZED(): number {
  158. return Engine._ALPHA_MAXIMIZED;
  159. }
  160. public static get DELAYLOADSTATE_NONE(): number {
  161. return Engine._DELAYLOADSTATE_NONE;
  162. }
  163. public static get DELAYLOADSTATE_LOADED(): number {
  164. return Engine._DELAYLOADSTATE_LOADED;
  165. }
  166. public static get DELAYLOADSTATE_LOADING(): number {
  167. return Engine._DELAYLOADSTATE_LOADING;
  168. }
  169. public static get DELAYLOADSTATE_NOTLOADED(): number {
  170. return Engine._DELAYLOADSTATE_NOTLOADED;
  171. }
  172. public static get TEXTUREFORMAT_ALPHA(): number {
  173. return Engine._TEXTUREFORMAT_ALPHA;
  174. }
  175. public static get TEXTUREFORMAT_LUMINANCE(): number {
  176. return Engine._TEXTUREFORMAT_LUMINANCE;
  177. }
  178. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  179. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  180. }
  181. public static get TEXTUREFORMAT_RGB(): number {
  182. return Engine._TEXTUREFORMAT_RGB;
  183. }
  184. public static get TEXTUREFORMAT_RGBA(): number {
  185. return Engine._TEXTUREFORMAT_RGBA;
  186. }
  187. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  188. return Engine._TEXTURETYPE_UNSIGNED_INT;
  189. }
  190. public static get TEXTURETYPE_FLOAT(): number {
  191. return Engine._TEXTURETYPE_FLOAT;
  192. }
  193. public static get Version(): string {
  194. return "2.4.0-alpha";
  195. }
  196. // Updatable statics so stick with vars here
  197. public static CollisionsEpsilon = 0.001;
  198. public static CodeRepository = "src/";
  199. public static ShadersRepository = "src/Shaders/";
  200. // Public members
  201. public isFullscreen = false;
  202. public isPointerLock = false;
  203. public cullBackFaces = true;
  204. public renderEvenInBackground = true;
  205. // To enable/disable IDB support and avoid XHR on .manifest
  206. public enableOfflineSupport = true;
  207. public scenes = new Array<Scene>();
  208. // Private Members
  209. public _gl: WebGLRenderingContext;
  210. private _renderingCanvas: HTMLCanvasElement;
  211. private _windowIsBackground = false;
  212. private _webGLVersion = "1.0";
  213. public static audioEngine: AudioEngine;
  214. private _onBlur: () => void;
  215. private _onFocus: () => void;
  216. private _onFullscreenChange: () => void;
  217. private _onPointerLockChange: () => void;
  218. private _hardwareScalingLevel: number;
  219. private _caps: EngineCapabilities;
  220. private _pointerLockRequested: boolean;
  221. private _alphaTest: boolean;
  222. private _loadingScreen: ILoadingScreen;
  223. private _drawCalls = 0;
  224. private _glVersion: string;
  225. private _glRenderer: string;
  226. private _glVendor: string;
  227. private _videoTextureSupported: boolean;
  228. private _renderingQueueLaunched = false;
  229. private _activeRenderLoops = [];
  230. // FPS
  231. private fpsRange = 60;
  232. private previousFramesDuration = [];
  233. private fps = 60;
  234. private deltaTime = 0;
  235. // States
  236. private _depthCullingState = new Internals._DepthCullingState();
  237. private _alphaState = new Internals._AlphaState();
  238. private _alphaMode = Engine.ALPHA_DISABLE;
  239. // Cache
  240. private _loadedTexturesCache = new Array<WebGLTexture>();
  241. private _maxTextureChannels = 16;
  242. private _activeTexturesCache = new Array<BaseTexture>(this._maxTextureChannels);
  243. private _currentEffect: Effect;
  244. private _compiledEffects = {};
  245. private _vertexAttribArrays: boolean[];
  246. private _cachedViewport: Viewport;
  247. private _cachedVertexBuffers: any;
  248. private _cachedIndexBuffer: WebGLBuffer;
  249. private _cachedEffectForVertexBuffers: Effect;
  250. private _currentRenderTarget: WebGLTexture;
  251. private _uintIndicesCurrentlySet = false;
  252. private _workingCanvas: HTMLCanvasElement;
  253. private _workingContext: CanvasRenderingContext2D;
  254. private _bindedRenderFunction: any;
  255. /**
  256. * @constructor
  257. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  258. * @param {boolean} [antialias] - enable antialias
  259. * @param options - further options to be sent to the getContext function
  260. */
  261. constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?: { antialias?: boolean, preserveDrawingBuffer?: boolean, limitDeviceRatio?: number }, adaptToDeviceRatio = true) {
  262. this._renderingCanvas = canvas;
  263. options = options || {};
  264. options.antialias = antialias;
  265. if (options.preserveDrawingBuffer === undefined) {
  266. options.preserveDrawingBuffer = false;
  267. }
  268. // GL
  269. //try {
  270. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  271. // if (this._gl) {
  272. // this._webGLVersion = "2.0";
  273. // }
  274. //} catch (e) {
  275. // // Do nothing
  276. //}
  277. if (!this._gl) {
  278. try {
  279. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  280. } catch (e) {
  281. throw new Error("WebGL not supported");
  282. }
  283. }
  284. if (!this._gl) {
  285. throw new Error("WebGL not supported");
  286. }
  287. this._onBlur = () => {
  288. this._windowIsBackground = true;
  289. };
  290. this._onFocus = () => {
  291. this._windowIsBackground = false;
  292. };
  293. window.addEventListener("blur", this._onBlur);
  294. window.addEventListener("focus", this._onFocus);
  295. // Viewport
  296. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  297. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  298. this.resize();
  299. // Caps
  300. this._caps = new EngineCapabilities();
  301. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  302. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  303. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  304. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  305. // Infos
  306. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  307. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  308. if (rendererInfo != null) {
  309. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  310. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  311. }
  312. if (!this._glVendor) {
  313. this._glVendor = "Unknown vendor";
  314. }
  315. if (!this._glRenderer) {
  316. this._glRenderer = "Unknown renderer";
  317. }
  318. // Extensions
  319. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  320. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  321. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  322. 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');
  323. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  324. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  325. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  326. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  327. this._caps.highPrecisionShaderSupported = true;
  328. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  329. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  330. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  331. if (this._gl.getShaderPrecisionFormat) {
  332. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  333. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  334. }
  335. // Depth buffer
  336. this.setDepthBuffer(true);
  337. this.setDepthFunctionToLessOrEqual();
  338. this.setDepthWrite(true);
  339. // Fullscreen
  340. this._onFullscreenChange = () => {
  341. if (document.fullscreen !== undefined) {
  342. this.isFullscreen = document.fullscreen;
  343. } else if (document.mozFullScreen !== undefined) {
  344. this.isFullscreen = document.mozFullScreen;
  345. } else if (document.webkitIsFullScreen !== undefined) {
  346. this.isFullscreen = document.webkitIsFullScreen;
  347. } else if (document.msIsFullScreen !== undefined) {
  348. this.isFullscreen = document.msIsFullScreen;
  349. }
  350. // Pointer lock
  351. if (this.isFullscreen && this._pointerLockRequested) {
  352. canvas.requestPointerLock = canvas.requestPointerLock ||
  353. canvas.msRequestPointerLock ||
  354. canvas.mozRequestPointerLock ||
  355. canvas.webkitRequestPointerLock;
  356. if (canvas.requestPointerLock) {
  357. canvas.requestPointerLock();
  358. }
  359. }
  360. };
  361. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  362. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  363. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  364. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  365. // Pointer lock
  366. this._onPointerLockChange = () => {
  367. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  368. document.webkitPointerLockElement === canvas ||
  369. document.msPointerLockElement === canvas ||
  370. document.pointerLockElement === canvas
  371. );
  372. };
  373. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  374. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  375. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  376. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  377. if (AudioEngine && !Engine.audioEngine) {
  378. Engine.audioEngine = new AudioEngine();
  379. }
  380. //default loading screen
  381. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas);
  382. Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  383. }
  384. public get webGLVersion(): string {
  385. return this._webGLVersion;
  386. }
  387. private _prepareWorkingCanvas(): void {
  388. if (this._workingCanvas) {
  389. return;
  390. }
  391. this._workingCanvas = document.createElement("canvas");
  392. this._workingContext = this._workingCanvas.getContext("2d");
  393. }
  394. public resetTextureCache() {
  395. for (var index = 0; index < this._maxTextureChannels; index++) {
  396. this._activeTexturesCache[index] = null;
  397. }
  398. }
  399. public getGlInfo() {
  400. return {
  401. vendor: this._glVendor,
  402. renderer: this._glRenderer,
  403. version: this._glVersion
  404. }
  405. }
  406. public getAspectRatio(camera: Camera, useScreen = false): number {
  407. var viewport = camera.viewport;
  408. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  409. }
  410. public getRenderWidth(useScreen = false): number {
  411. if (!useScreen && this._currentRenderTarget) {
  412. return this._currentRenderTarget._width;
  413. }
  414. return this._renderingCanvas.width;
  415. }
  416. public getRenderHeight(useScreen = false): number {
  417. if (!useScreen && this._currentRenderTarget) {
  418. return this._currentRenderTarget._height;
  419. }
  420. return this._renderingCanvas.height;
  421. }
  422. public getRenderingCanvas(): HTMLCanvasElement {
  423. return this._renderingCanvas;
  424. }
  425. public getRenderingCanvasClientRect(): ClientRect {
  426. return this._renderingCanvas.getBoundingClientRect();
  427. }
  428. public setHardwareScalingLevel(level: number): void {
  429. this._hardwareScalingLevel = level;
  430. this.resize();
  431. }
  432. public getHardwareScalingLevel(): number {
  433. return this._hardwareScalingLevel;
  434. }
  435. public getLoadedTexturesCache(): WebGLTexture[] {
  436. return this._loadedTexturesCache;
  437. }
  438. public getCaps(): EngineCapabilities {
  439. return this._caps;
  440. }
  441. public get drawCalls(): number {
  442. return this._drawCalls;
  443. }
  444. // Methods
  445. public resetDrawCalls(): void {
  446. this._drawCalls = 0;
  447. }
  448. public setDepthFunctionToGreater(): void {
  449. this._depthCullingState.depthFunc = this._gl.GREATER;
  450. }
  451. public setDepthFunctionToGreaterOrEqual(): void {
  452. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  453. }
  454. public setDepthFunctionToLess(): void {
  455. this._depthCullingState.depthFunc = this._gl.LESS;
  456. }
  457. public setDepthFunctionToLessOrEqual(): void {
  458. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  459. }
  460. /**
  461. * stop executing a render loop function and remove it from the execution array
  462. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  463. */
  464. public stopRenderLoop(renderFunction?: () => void): void {
  465. if (!renderFunction) {
  466. this._activeRenderLoops = [];
  467. return;
  468. }
  469. var index = this._activeRenderLoops.indexOf(renderFunction);
  470. if (index >= 0) {
  471. this._activeRenderLoops.splice(index, 1);
  472. }
  473. }
  474. public _renderLoop(): void {
  475. var shouldRender = true;
  476. if (!this.renderEvenInBackground && this._windowIsBackground) {
  477. shouldRender = false;
  478. }
  479. if (shouldRender) {
  480. // Start new frame
  481. this.beginFrame();
  482. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  483. var renderFunction = this._activeRenderLoops[index];
  484. renderFunction();
  485. }
  486. // Present
  487. this.endFrame();
  488. }
  489. if (this._activeRenderLoops.length > 0) {
  490. // Register new frame
  491. Tools.QueueNewFrame(this._bindedRenderFunction);
  492. } else {
  493. this._renderingQueueLaunched = false;
  494. }
  495. }
  496. /**
  497. * Register and execute a render loop. The engine can have more than one render function.
  498. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  499. * @example
  500. * engine.runRenderLoop(function () {
  501. * scene.render()
  502. * })
  503. */
  504. public runRenderLoop(renderFunction: () => void): void {
  505. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  506. return;
  507. }
  508. this._activeRenderLoops.push(renderFunction);
  509. if (!this._renderingQueueLaunched) {
  510. this._renderingQueueLaunched = true;
  511. this._bindedRenderFunction = this._renderLoop.bind(this);
  512. Tools.QueueNewFrame(this._bindedRenderFunction);
  513. }
  514. }
  515. /**
  516. * Toggle full screen mode.
  517. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  518. */
  519. public switchFullscreen(requestPointerLock: boolean): void {
  520. if (this.isFullscreen) {
  521. Tools.ExitFullscreen();
  522. } else {
  523. this._pointerLockRequested = requestPointerLock;
  524. Tools.RequestFullscreen(this._renderingCanvas);
  525. }
  526. }
  527. public clear(color: any, backBuffer: boolean, depthStencil: boolean): void {
  528. this.applyStates();
  529. if (backBuffer) {
  530. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  531. }
  532. if (depthStencil && this._depthCullingState.depthMask) {
  533. this._gl.clearDepth(1.0);
  534. }
  535. var mode = 0;
  536. if (backBuffer) {
  537. mode |= this._gl.COLOR_BUFFER_BIT;
  538. }
  539. if (depthStencil && this._depthCullingState.depthMask) {
  540. mode |= this._gl.DEPTH_BUFFER_BIT;
  541. }
  542. this._gl.clear(mode);
  543. }
  544. /**
  545. * Set the WebGL's viewport
  546. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  547. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  548. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  549. */
  550. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  551. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  552. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  553. var x = viewport.x || 0;
  554. var y = viewport.y || 0;
  555. this._cachedViewport = viewport;
  556. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  557. }
  558. public setDirectViewport(x: number, y: number, width: number, height: number): void {
  559. this._cachedViewport = null;
  560. this._gl.viewport(x, y, width, height);
  561. }
  562. public beginFrame(): void {
  563. this._measureFps();
  564. }
  565. public endFrame(): void {
  566. //this.flushFramebuffer();
  567. }
  568. /**
  569. * resize the view according to the canvas' size.
  570. * @example
  571. * window.addEventListener("resize", function () {
  572. * engine.resize();
  573. * });
  574. */
  575. public resize(): void {
  576. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  577. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  578. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  579. for (var index = 0; index < this.scenes.length; index++) {
  580. var scene = this.scenes[index];
  581. if (scene.debugLayer.isVisible()) {
  582. scene.debugLayer._syncPositions();
  583. }
  584. }
  585. }
  586. /**
  587. * force a specific size of the canvas
  588. * @param {number} width - the new canvas' width
  589. * @param {number} height - the new canvas' height
  590. */
  591. public setSize(width: number, height: number): void {
  592. this._renderingCanvas.width = width;
  593. this._renderingCanvas.height = height;
  594. for (var index = 0; index < this.scenes.length; index++) {
  595. var scene = this.scenes[index];
  596. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  597. var cam = scene.cameras[camIndex];
  598. cam._currentRenderId = 0;
  599. }
  600. }
  601. }
  602. public bindFramebuffer(texture: WebGLTexture, faceIndex?: number): void {
  603. this._currentRenderTarget = texture;
  604. var gl = this._gl;
  605. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  606. if (texture.isCube) {
  607. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  608. } else {
  609. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  610. }
  611. this._gl.viewport(0, 0, texture._width, texture._height);
  612. this.wipeCaches();
  613. }
  614. public unBindFramebuffer(texture: WebGLTexture, disableGenerateMipMaps = false): void {
  615. this._currentRenderTarget = null;
  616. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  617. var gl = this._gl;
  618. gl.bindTexture(gl.TEXTURE_2D, texture);
  619. gl.generateMipmap(gl.TEXTURE_2D);
  620. gl.bindTexture(gl.TEXTURE_2D, null);
  621. }
  622. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  623. }
  624. public generateMipMapsForCubemap(texture: WebGLTexture) {
  625. if (texture.generateMipMaps) {
  626. var gl = this._gl;
  627. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  628. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  629. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  630. }
  631. }
  632. public flushFramebuffer(): void {
  633. this._gl.flush();
  634. }
  635. public restoreDefaultFramebuffer(): void {
  636. this._currentRenderTarget = null;
  637. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  638. this.setViewport(this._cachedViewport);
  639. this.wipeCaches();
  640. }
  641. // VBOs
  642. private _resetVertexBufferBinding(): void {
  643. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  644. this._cachedVertexBuffers = null;
  645. }
  646. public createVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
  647. var vbo = this._gl.createBuffer();
  648. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  649. if (vertices instanceof Float32Array) {
  650. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.STATIC_DRAW);
  651. } else {
  652. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.STATIC_DRAW);
  653. }
  654. this._resetVertexBufferBinding();
  655. vbo.references = 1;
  656. return vbo;
  657. }
  658. public createDynamicVertexBuffer(capacity: number): WebGLBuffer {
  659. var vbo = this._gl.createBuffer();
  660. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  661. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  662. this._resetVertexBufferBinding();
  663. vbo.references = 1;
  664. return vbo;
  665. }
  666. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: number[] | Float32Array, offset?: number): void {
  667. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  668. if (offset === undefined) {
  669. offset = 0;
  670. }
  671. if (vertices instanceof Float32Array) {
  672. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, <Float32Array>vertices);
  673. } else {
  674. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(<number[]>vertices));
  675. }
  676. this._resetVertexBufferBinding();
  677. }
  678. private _resetIndexBufferBinding(): void {
  679. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  680. this._cachedIndexBuffer = null;
  681. }
  682. public createIndexBuffer(indices: number[] | Int32Array): WebGLBuffer {
  683. var vbo = this._gl.createBuffer();
  684. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  685. // Check for 32 bits indices
  686. var arrayBuffer;
  687. var need32Bits = false;
  688. if (this._caps.uintIndices) {
  689. for (var index = 0; index < indices.length; index++) {
  690. if (indices[index] > 65535) {
  691. need32Bits = true;
  692. break;
  693. }
  694. }
  695. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  696. } else {
  697. arrayBuffer = new Uint16Array(indices);
  698. }
  699. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  700. this._resetIndexBufferBinding();
  701. vbo.references = 1;
  702. vbo.is32Bits = need32Bits;
  703. return vbo;
  704. }
  705. public bindBuffers(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  706. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  707. this._cachedVertexBuffers = vertexBuffer;
  708. this._cachedEffectForVertexBuffers = effect;
  709. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  710. var offset = 0;
  711. for (var index = 0; index < vertexDeclaration.length; index++) {
  712. var order = effect.getAttributeLocation(index);
  713. if (order >= 0) {
  714. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  715. }
  716. offset += vertexDeclaration[index] * 4;
  717. }
  718. }
  719. if (this._cachedIndexBuffer !== indexBuffer) {
  720. this._cachedIndexBuffer = indexBuffer;
  721. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  722. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  723. }
  724. }
  725. public bindMultiBuffers(vertexBuffers: VertexBuffer[], indexBuffer: WebGLBuffer, effect: Effect): void {
  726. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  727. this._cachedVertexBuffers = vertexBuffers;
  728. this._cachedEffectForVertexBuffers = effect;
  729. var attributes = effect.getAttributesNames();
  730. for (var index = 0; index < attributes.length; index++) {
  731. var order = effect.getAttributeLocation(index);
  732. if (order >= 0) {
  733. var vertexBuffer = vertexBuffers[attributes[index]];
  734. if (!vertexBuffer) {
  735. continue;
  736. }
  737. var stride = vertexBuffer.getStrideSize();
  738. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  739. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  740. }
  741. }
  742. }
  743. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  744. this._cachedIndexBuffer = indexBuffer;
  745. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  746. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  747. }
  748. }
  749. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  750. buffer.references--;
  751. if (buffer.references === 0) {
  752. this._gl.deleteBuffer(buffer);
  753. return true;
  754. }
  755. return false;
  756. }
  757. public createInstancesBuffer(capacity: number): WebGLBuffer {
  758. var buffer = this._gl.createBuffer();
  759. buffer.capacity = capacity;
  760. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  761. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  762. return buffer;
  763. }
  764. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  765. this._gl.deleteBuffer(buffer);
  766. }
  767. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[]): void {
  768. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  769. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  770. for (var index = 0; index < 4; index++) {
  771. var offsetLocation = offsetLocations[index];
  772. this._gl.enableVertexAttribArray(offsetLocation);
  773. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  774. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  775. }
  776. }
  777. public unBindInstancesBuffer(instancesBuffer: WebGLBuffer, offsetLocations: number[]): void {
  778. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  779. for (var index = 0; index < 4; index++) {
  780. var offsetLocation = offsetLocations[index];
  781. this._gl.disableVertexAttribArray(offsetLocation);
  782. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  783. }
  784. }
  785. public applyStates() {
  786. this._depthCullingState.apply(this._gl);
  787. this._alphaState.apply(this._gl);
  788. }
  789. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  790. // Apply states
  791. this.applyStates();
  792. this._drawCalls++;
  793. // Render
  794. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  795. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  796. if (instancesCount) {
  797. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  798. return;
  799. }
  800. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  801. }
  802. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  803. // Apply states
  804. this.applyStates();
  805. this._drawCalls++;
  806. if (instancesCount) {
  807. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  808. return;
  809. }
  810. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  811. }
  812. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  813. // Apply states
  814. this.applyStates();
  815. this._drawCalls++;
  816. if (instancesCount) {
  817. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  818. return;
  819. }
  820. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  821. }
  822. // Shaders
  823. public _releaseEffect(effect: Effect): void {
  824. if (this._compiledEffects[effect._key]) {
  825. delete this._compiledEffects[effect._key];
  826. if (effect.getProgram()) {
  827. this._gl.deleteProgram(effect.getProgram());
  828. }
  829. }
  830. }
  831. public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks,
  832. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  833. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  834. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  835. var name = vertex + "+" + fragment + "@" + defines;
  836. if (this._compiledEffects[name]) {
  837. return this._compiledEffects[name];
  838. }
  839. var effect = new Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  840. effect._key = name;
  841. this._compiledEffects[name] = effect;
  842. return effect;
  843. }
  844. public createEffectForParticles(fragmentName: string, uniformsNames: string[] = [], samplers: string[] = [], defines = "", fallbacks?: EffectFallbacks,
  845. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  846. return this.createEffect(
  847. {
  848. vertex: "particles",
  849. fragmentElement: fragmentName
  850. },
  851. ["position", "color", "options"],
  852. ["view", "projection"].concat(uniformsNames),
  853. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  854. }
  855. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string): WebGLProgram {
  856. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  857. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  858. var shaderProgram = this._gl.createProgram();
  859. this._gl.attachShader(shaderProgram, vertexShader);
  860. this._gl.attachShader(shaderProgram, fragmentShader);
  861. this._gl.linkProgram(shaderProgram);
  862. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  863. if (!linked) {
  864. var error = this._gl.getProgramInfoLog(shaderProgram);
  865. if (error) {
  866. throw new Error(error);
  867. }
  868. }
  869. this._gl.deleteShader(vertexShader);
  870. this._gl.deleteShader(fragmentShader);
  871. return shaderProgram;
  872. }
  873. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  874. var results = [];
  875. for (var index = 0; index < uniformsNames.length; index++) {
  876. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  877. }
  878. return results;
  879. }
  880. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  881. var results = [];
  882. for (var index = 0; index < attributesNames.length; index++) {
  883. try {
  884. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  885. } catch (e) {
  886. results.push(-1);
  887. }
  888. }
  889. return results;
  890. }
  891. public enableEffect(effect: Effect): void {
  892. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  893. if (effect && effect.onBind) {
  894. effect.onBind(effect);
  895. }
  896. return;
  897. }
  898. this._vertexAttribArrays = this._vertexAttribArrays || [];
  899. // Use program
  900. this._gl.useProgram(effect.getProgram());
  901. for (var i in this._vertexAttribArrays) {
  902. //make sure this is a number)
  903. var iAsNumber = +i;
  904. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  905. continue;
  906. }
  907. this._vertexAttribArrays[iAsNumber] = false;
  908. this._gl.disableVertexAttribArray(iAsNumber);
  909. }
  910. var attributesCount = effect.getAttributesCount();
  911. for (var index = 0; index < attributesCount; index++) {
  912. // Attributes
  913. var order = effect.getAttributeLocation(index);
  914. if (order >= 0) {
  915. this._vertexAttribArrays[order] = true;
  916. this._gl.enableVertexAttribArray(order);
  917. }
  918. }
  919. this._currentEffect = effect;
  920. if (effect.onBind) {
  921. effect.onBind(effect);
  922. }
  923. }
  924. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  925. if (!uniform)
  926. return;
  927. this._gl.uniform1fv(uniform, <any>array);
  928. }
  929. public setArray2(uniform: WebGLUniformLocation, array: number[]): void {
  930. if (!uniform || array.length % 2 !== 0)
  931. return;
  932. this._gl.uniform2fv(uniform, <any>array);
  933. }
  934. public setArray3(uniform: WebGLUniformLocation, array: number[]): void {
  935. if (!uniform || array.length % 3 !== 0)
  936. return;
  937. this._gl.uniform3fv(uniform, <any>array);
  938. }
  939. public setArray4(uniform: WebGLUniformLocation, array: number[]): void {
  940. if (!uniform || array.length % 4 !== 0)
  941. return;
  942. this._gl.uniform4fv(uniform, <any>array);
  943. }
  944. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  945. if (!uniform)
  946. return;
  947. this._gl.uniformMatrix4fv(uniform, false, matrices);
  948. }
  949. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  950. if (!uniform)
  951. return;
  952. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  953. }
  954. public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  955. if (!uniform)
  956. return;
  957. this._gl.uniformMatrix3fv(uniform, false, matrix);
  958. }
  959. public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  960. if (!uniform)
  961. return;
  962. this._gl.uniformMatrix2fv(uniform, false, matrix);
  963. }
  964. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  965. if (!uniform)
  966. return;
  967. this._gl.uniform1f(uniform, value);
  968. }
  969. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  970. if (!uniform)
  971. return;
  972. this._gl.uniform2f(uniform, x, y);
  973. }
  974. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  975. if (!uniform)
  976. return;
  977. this._gl.uniform3f(uniform, x, y, z);
  978. }
  979. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  980. if (!uniform)
  981. return;
  982. this._gl.uniform1i(uniform, bool);
  983. }
  984. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  985. if (!uniform)
  986. return;
  987. this._gl.uniform4f(uniform, x, y, z, w);
  988. }
  989. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  990. if (!uniform)
  991. return;
  992. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  993. }
  994. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  995. if (!uniform)
  996. return;
  997. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  998. }
  999. // States
  1000. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  1001. // Culling
  1002. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  1003. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  1004. var cullFace = this.cullBackFaces ? showSide : hideSide;
  1005. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  1006. if (culling) {
  1007. this._depthCullingState.cullFace = cullFace;
  1008. this._depthCullingState.cull = true;
  1009. } else {
  1010. this._depthCullingState.cull = false;
  1011. }
  1012. }
  1013. // Z offset
  1014. this._depthCullingState.zOffset = zOffset;
  1015. }
  1016. public setDepthBuffer(enable: boolean): void {
  1017. this._depthCullingState.depthTest = enable;
  1018. }
  1019. public getDepthWrite(): boolean {
  1020. return this._depthCullingState.depthMask;
  1021. }
  1022. public setDepthWrite(enable: boolean): void {
  1023. this._depthCullingState.depthMask = enable;
  1024. }
  1025. public setColorWrite(enable: boolean): void {
  1026. this._gl.colorMask(enable, enable, enable, enable);
  1027. }
  1028. public setAlphaMode(mode: number): void {
  1029. if (this._alphaMode === mode) {
  1030. return;
  1031. }
  1032. switch (mode) {
  1033. case Engine.ALPHA_DISABLE:
  1034. this.setDepthWrite(true);
  1035. this._alphaState.alphaBlend = false;
  1036. break;
  1037. case Engine.ALPHA_COMBINE:
  1038. this.setDepthWrite(false);
  1039. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1040. this._alphaState.alphaBlend = true;
  1041. break;
  1042. case Engine.ALPHA_ONEONE:
  1043. this.setDepthWrite(false);
  1044. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1045. this._alphaState.alphaBlend = true;
  1046. break;
  1047. case Engine.ALPHA_ADD:
  1048. this.setDepthWrite(false);
  1049. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1050. this._alphaState.alphaBlend = true;
  1051. break;
  1052. case Engine.ALPHA_SUBTRACT:
  1053. this.setDepthWrite(false);
  1054. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1055. this._alphaState.alphaBlend = true;
  1056. break;
  1057. case Engine.ALPHA_MULTIPLY:
  1058. this.setDepthWrite(false);
  1059. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  1060. this._alphaState.alphaBlend = true;
  1061. break;
  1062. case Engine.ALPHA_MAXIMIZED:
  1063. this.setDepthWrite(false);
  1064. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1065. this._alphaState.alphaBlend = true;
  1066. break;
  1067. }
  1068. this._alphaMode = mode;
  1069. }
  1070. public getAlphaMode(): number {
  1071. return this._alphaMode;
  1072. }
  1073. public setAlphaTesting(enable: boolean): void {
  1074. this._alphaTest = enable;
  1075. }
  1076. public getAlphaTesting(): boolean {
  1077. return this._alphaTest;
  1078. }
  1079. // Textures
  1080. public wipeCaches(): void {
  1081. this.resetTextureCache();
  1082. this._currentEffect = null;
  1083. this._depthCullingState.reset();
  1084. this._alphaState.reset();
  1085. this._cachedVertexBuffers = null;
  1086. this._cachedIndexBuffer = null;
  1087. this._cachedEffectForVertexBuffers = null;
  1088. }
  1089. public setSamplingMode(texture: WebGLTexture, samplingMode: number): void {
  1090. var gl = this._gl;
  1091. gl.bindTexture(gl.TEXTURE_2D, texture);
  1092. var magFilter = gl.NEAREST;
  1093. var minFilter = gl.NEAREST;
  1094. if (samplingMode === Texture.BILINEAR_SAMPLINGMODE) {
  1095. magFilter = gl.LINEAR;
  1096. minFilter = gl.LINEAR;
  1097. } else if (samplingMode === Texture.TRILINEAR_SAMPLINGMODE) {
  1098. magFilter = gl.LINEAR;
  1099. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  1100. }
  1101. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  1102. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  1103. gl.bindTexture(gl.TEXTURE_2D, null);
  1104. texture.samplingMode = samplingMode;
  1105. }
  1106. public createTexture(url: string, noMipmap: boolean, invertY: boolean, scene: Scene, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE, onLoad: () => void = null, onError: () => void = null, buffer: any = null): WebGLTexture {
  1107. var texture = this._gl.createTexture();
  1108. var extension: string;
  1109. var fromData: any = false;
  1110. if (url.substr(0, 5) === "data:") {
  1111. fromData = true;
  1112. }
  1113. if (!fromData)
  1114. extension = url.substr(url.length - 4, 4).toLowerCase();
  1115. else {
  1116. var oldUrl = url;
  1117. fromData = oldUrl.split(':');
  1118. url = oldUrl;
  1119. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  1120. }
  1121. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1122. var isTGA = (extension === ".tga");
  1123. scene._addPendingData(texture);
  1124. texture.url = url;
  1125. texture.noMipmap = noMipmap;
  1126. texture.references = 1;
  1127. texture.samplingMode = samplingMode;
  1128. this._loadedTexturesCache.push(texture);
  1129. var onerror = () => {
  1130. scene._removePendingData(texture);
  1131. if (onError) {
  1132. onError();
  1133. }
  1134. };
  1135. var callback: (arrayBuffer: any) => void;
  1136. if (isTGA) {
  1137. callback = (arrayBuffer) => {
  1138. var data = new Uint8Array(arrayBuffer);
  1139. var header = Internals.TGATools.GetTGAHeader(data);
  1140. prepareWebGLTexture(texture, this._gl, scene, header.width, header.height, invertY, noMipmap, false, () => {
  1141. Internals.TGATools.UploadContent(this._gl, data);
  1142. }, onLoad, samplingMode);
  1143. };
  1144. if (!(fromData instanceof Array))
  1145. Tools.LoadFile(url, arrayBuffer => {
  1146. callback(arrayBuffer);
  1147. }, onerror, scene.database, true);
  1148. else
  1149. callback(buffer);
  1150. } else if (isDDS) {
  1151. callback = (data) => {
  1152. var info = Internals.DDSTools.GetDDSInfo(data);
  1153. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  1154. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  1155. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 1);
  1156. }, onLoad, samplingMode);
  1157. };
  1158. if (!(fromData instanceof Array))
  1159. Tools.LoadFile(url, data => {
  1160. callback(data);
  1161. }, onerror, scene.database, true);
  1162. else
  1163. callback(buffer);
  1164. } else {
  1165. var onload = (img) => {
  1166. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight) => {
  1167. var isPot = (img.width === potWidth && img.height === potHeight);
  1168. if (!isPot) {
  1169. this._prepareWorkingCanvas();
  1170. this._workingCanvas.width = potWidth;
  1171. this._workingCanvas.height = potHeight;
  1172. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1173. this._workingContext.imageSmoothingEnabled = false;
  1174. this._workingContext.mozImageSmoothingEnabled = false;
  1175. this._workingContext.oImageSmoothingEnabled = false;
  1176. this._workingContext.webkitImageSmoothingEnabled = false;
  1177. this._workingContext.msImageSmoothingEnabled = false;
  1178. }
  1179. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  1180. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1181. this._workingContext.imageSmoothingEnabled = true;
  1182. this._workingContext.mozImageSmoothingEnabled = true;
  1183. this._workingContext.oImageSmoothingEnabled = true;
  1184. this._workingContext.webkitImageSmoothingEnabled = true;
  1185. this._workingContext.msImageSmoothingEnabled = true;
  1186. }
  1187. }
  1188. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  1189. }, onLoad, samplingMode);
  1190. };
  1191. if (!(fromData instanceof Array))
  1192. Tools.LoadImage(url, onload, onerror, scene.database);
  1193. else
  1194. Tools.LoadImage(buffer, onload, onerror, scene.database);
  1195. }
  1196. return texture;
  1197. }
  1198. private _getInternalFormat(format: number): number {
  1199. var internalFormat = this._gl.RGBA;
  1200. switch (format) {
  1201. case Engine.TEXTUREFORMAT_ALPHA:
  1202. internalFormat = this._gl.ALPHA;
  1203. break;
  1204. case Engine.TEXTUREFORMAT_LUMINANCE:
  1205. internalFormat = this._gl.LUMINANCE;
  1206. break;
  1207. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  1208. internalFormat = this._gl.LUMINANCE_ALPHA;
  1209. break;
  1210. case Engine.TEXTUREFORMAT_RGB:
  1211. internalFormat = this._gl.RGB;
  1212. break;
  1213. case Engine.TEXTUREFORMAT_RGBA:
  1214. internalFormat = this._gl.RGBA;
  1215. break;
  1216. }
  1217. return internalFormat;
  1218. }
  1219. public updateRawTexture(texture: WebGLTexture, data: ArrayBufferView, format: number, invertY: boolean, compression: string = null): void {
  1220. var internalFormat = this._getInternalFormat(format);
  1221. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1222. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  1223. if (compression) {
  1224. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  1225. } else {
  1226. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  1227. }
  1228. if (texture.generateMipMaps) {
  1229. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1230. }
  1231. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1232. this.resetTextureCache();
  1233. texture.isReady = true;
  1234. }
  1235. public createRawTexture(data: ArrayBufferView, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: string = null): WebGLTexture {
  1236. var texture = this._gl.createTexture();
  1237. texture._baseWidth = width;
  1238. texture._baseHeight = height;
  1239. texture._width = width;
  1240. texture._height = height;
  1241. texture.references = 1;
  1242. this.updateRawTexture(texture, data, format, invertY, compression);
  1243. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1244. // Filters
  1245. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1246. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1247. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1248. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1249. texture.samplingMode = samplingMode;
  1250. this._loadedTexturesCache.push(texture);
  1251. return texture;
  1252. }
  1253. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number, forceExponantOfTwo = true): WebGLTexture {
  1254. var texture = this._gl.createTexture();
  1255. texture._baseWidth = width;
  1256. texture._baseHeight = height;
  1257. if (forceExponantOfTwo) {
  1258. width = Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  1259. height = Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  1260. }
  1261. this.resetTextureCache();
  1262. texture._width = width;
  1263. texture._height = height;
  1264. texture.isReady = false;
  1265. texture.generateMipMaps = generateMipMaps;
  1266. texture.references = 1;
  1267. texture.samplingMode = samplingMode;
  1268. this.updateTextureSamplingMode(samplingMode, texture);
  1269. this._loadedTexturesCache.push(texture);
  1270. return texture;
  1271. }
  1272. public updateTextureSamplingMode(samplingMode: number, texture: WebGLTexture): void {
  1273. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  1274. if (texture.isCube) {
  1275. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  1276. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1277. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1278. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1279. } else {
  1280. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1281. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1282. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1283. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1284. }
  1285. }
  1286. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean): void {
  1287. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1288. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  1289. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  1290. if (texture.generateMipMaps) {
  1291. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1292. }
  1293. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1294. this.resetTextureCache();
  1295. texture.isReady = true;
  1296. }
  1297. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  1298. if (texture._isDisabled) {
  1299. return;
  1300. }
  1301. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1302. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  1303. try {
  1304. // Testing video texture support
  1305. if (this._videoTextureSupported === undefined) {
  1306. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1307. if (this._gl.getError() !== 0) {
  1308. this._videoTextureSupported = false;
  1309. } else {
  1310. this._videoTextureSupported = true;
  1311. }
  1312. }
  1313. // Copy video through the current working canvas if video texture is not supported
  1314. if (!this._videoTextureSupported) {
  1315. if (!texture._workingCanvas) {
  1316. texture._workingCanvas = document.createElement("canvas");
  1317. texture._workingContext = texture._workingCanvas.getContext("2d");
  1318. texture._workingCanvas.width = texture._width;
  1319. texture._workingCanvas.height = texture._height;
  1320. }
  1321. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  1322. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  1323. } else {
  1324. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1325. }
  1326. if (texture.generateMipMaps) {
  1327. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1328. }
  1329. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1330. this.resetTextureCache();
  1331. texture.isReady = true;
  1332. } catch (ex) {
  1333. // Something unexpected
  1334. // Let's disable the texture
  1335. texture._isDisabled = true;
  1336. }
  1337. }
  1338. public createRenderTargetTexture(size: any, options): WebGLTexture {
  1339. // old version had a "generateMipMaps" arg instead of options.
  1340. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  1341. // in the same way, generateDepthBuffer is defaulted to true
  1342. var generateMipMaps = false;
  1343. var generateDepthBuffer = true;
  1344. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1345. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  1346. if (options !== undefined) {
  1347. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  1348. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1349. type = options.type === undefined ? type : options.type;
  1350. if (options.samplingMode !== undefined) {
  1351. samplingMode = options.samplingMode;
  1352. }
  1353. if (type === Engine.TEXTURETYPE_FLOAT) {
  1354. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  1355. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  1356. }
  1357. }
  1358. var gl = this._gl;
  1359. var texture = gl.createTexture();
  1360. gl.bindTexture(gl.TEXTURE_2D, texture);
  1361. var width = size.width || size;
  1362. var height = size.height || size;
  1363. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1364. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  1365. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1366. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  1367. }
  1368. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  1369. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  1370. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1371. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1372. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  1373. var depthBuffer: WebGLRenderbuffer;
  1374. // Create the depth buffer
  1375. if (generateDepthBuffer) {
  1376. depthBuffer = gl.createRenderbuffer();
  1377. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  1378. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  1379. }
  1380. // Create the framebuffer
  1381. var framebuffer = gl.createFramebuffer();
  1382. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  1383. if (generateDepthBuffer) {
  1384. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  1385. }
  1386. if (generateMipMaps) {
  1387. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1388. }
  1389. // Unbind
  1390. gl.bindTexture(gl.TEXTURE_2D, null);
  1391. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1392. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  1393. texture._framebuffer = framebuffer;
  1394. if (generateDepthBuffer) {
  1395. texture._depthBuffer = depthBuffer;
  1396. }
  1397. texture._width = width;
  1398. texture._height = height;
  1399. texture.isReady = true;
  1400. texture.generateMipMaps = generateMipMaps;
  1401. texture.references = 1;
  1402. texture.samplingMode = samplingMode;
  1403. this.resetTextureCache();
  1404. this._loadedTexturesCache.push(texture);
  1405. return texture;
  1406. }
  1407. public createRenderTargetCubeTexture(size: number, options?: any): WebGLTexture {
  1408. var gl = this._gl;
  1409. var texture = gl.createTexture();
  1410. var generateMipMaps = true;
  1411. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  1412. if (options !== undefined) {
  1413. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  1414. if (options.samplingMode !== undefined) {
  1415. samplingMode = options.samplingMode;
  1416. }
  1417. }
  1418. texture.isCube = true;
  1419. texture.references = 1;
  1420. texture.generateMipMaps = generateMipMaps;
  1421. texture.references = 1;
  1422. texture.samplingMode = samplingMode;
  1423. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1424. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1425. for (var face = 0; face < 6; face++) {
  1426. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  1427. }
  1428. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  1429. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  1430. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1431. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1432. // Create the depth buffer
  1433. var depthBuffer = gl.createRenderbuffer();
  1434. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  1435. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  1436. // Create the framebuffer
  1437. var framebuffer = gl.createFramebuffer();
  1438. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  1439. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  1440. // Mipmaps
  1441. if (texture.generateMipMaps) {
  1442. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1443. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1444. }
  1445. // Unbind
  1446. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1447. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1448. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  1449. texture._framebuffer = framebuffer;
  1450. texture._depthBuffer = depthBuffer;
  1451. this.resetTextureCache();
  1452. texture._width = size;
  1453. texture._height = size;
  1454. texture.isReady = true;
  1455. return texture;
  1456. }
  1457. public createCubeTexture(rootUrl: string, scene: Scene, files: string[], noMipmap?: boolean): WebGLTexture {
  1458. var gl = this._gl;
  1459. var texture = gl.createTexture();
  1460. texture.isCube = true;
  1461. texture.url = rootUrl;
  1462. texture.references = 1;
  1463. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  1464. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1465. if (isDDS) {
  1466. Tools.LoadFile(rootUrl, data => {
  1467. var info = Internals.DDSTools.GetDDSInfo(data);
  1468. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  1469. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1470. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  1471. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 6);
  1472. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  1473. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1474. }
  1475. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1476. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  1477. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1478. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1479. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1480. this.resetTextureCache();
  1481. texture._width = info.width;
  1482. texture._height = info.height;
  1483. texture.isReady = true;
  1484. }, null, null, true);
  1485. } else {
  1486. cascadeLoad(rootUrl, scene, imgs => {
  1487. var width = Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  1488. var height = width;
  1489. this._prepareWorkingCanvas();
  1490. this._workingCanvas.width = width;
  1491. this._workingCanvas.height = height;
  1492. var faces = [
  1493. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1494. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1495. ];
  1496. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1497. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1498. for (var index = 0; index < faces.length; index++) {
  1499. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  1500. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  1501. }
  1502. if (!noMipmap) {
  1503. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1504. }
  1505. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1506. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1507. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1508. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1509. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1510. this.resetTextureCache();
  1511. texture._width = width;
  1512. texture._height = height;
  1513. texture.isReady = true;
  1514. }, files);
  1515. }
  1516. return texture;
  1517. }
  1518. public createRawCubeTexture(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  1519. callback: (ArrayBuffer) => ArrayBufferView[],
  1520. mipmmapGenerator: ((faces: ArrayBufferView[]) => ArrayBufferView[][])): WebGLTexture {
  1521. var gl = this._gl;
  1522. var texture = gl.createTexture();
  1523. scene._addPendingData(texture);
  1524. texture.isCube = true;
  1525. texture.references = 1;
  1526. texture.url = url;
  1527. var internalFormat = this._getInternalFormat(format);
  1528. var textureType = gl.UNSIGNED_BYTE;
  1529. if (type === Engine.TEXTURETYPE_FLOAT) {
  1530. textureType = gl.FLOAT;
  1531. }
  1532. var width = size;
  1533. var height = width;
  1534. var isPot = (Tools.IsExponentOfTwo(width) && Tools.IsExponentOfTwo(height));
  1535. texture._width = width;
  1536. texture._height = height;
  1537. var onerror = () => {
  1538. scene._removePendingData(texture);
  1539. };
  1540. var internalCallback = (data) => {
  1541. var rgbeDataArrays = callback(data);
  1542. var facesIndex = [
  1543. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1544. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1545. ];
  1546. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1547. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1548. if (!noMipmap && isPot) {
  1549. if (mipmmapGenerator) {
  1550. var arrayTemp: ArrayBufferView[] = [];
  1551. // Data are known to be in +X +Y +Z -X -Y -Z
  1552. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  1553. arrayTemp.push(rgbeDataArrays[0]); // +X
  1554. arrayTemp.push(rgbeDataArrays[3]); // -X
  1555. arrayTemp.push(rgbeDataArrays[1]); // +Y
  1556. arrayTemp.push(rgbeDataArrays[4]); // -Y
  1557. arrayTemp.push(rgbeDataArrays[2]); // +Z
  1558. arrayTemp.push(rgbeDataArrays[5]); // -Z
  1559. var mipData = mipmmapGenerator(arrayTemp);
  1560. for (var level = 0; level < mipData.length; level++) {
  1561. var mipSize = width >> level;
  1562. // mipData is order in +X -X +Y -Y +Z -Z
  1563. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  1564. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  1565. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  1566. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  1567. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  1568. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  1569. }
  1570. }
  1571. else {
  1572. // Data are known to be in +X +Y +Z -X -Y -Z
  1573. for (var index = 0; index < facesIndex.length; index++) {
  1574. var faceData = rgbeDataArrays[index];
  1575. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  1576. }
  1577. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1578. }
  1579. }
  1580. else {
  1581. noMipmap = true;
  1582. }
  1583. if (textureType == gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  1584. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  1585. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  1586. }
  1587. else {
  1588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1589. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1590. }
  1591. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1592. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1593. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1594. texture.isReady = true;
  1595. this.resetTextureCache();
  1596. scene._removePendingData(texture);
  1597. };
  1598. Tools.LoadFile(url, data => {
  1599. internalCallback(data);
  1600. }, onerror, scene.database, true);
  1601. return texture;
  1602. };
  1603. public _releaseTexture(texture: WebGLTexture): void {
  1604. var gl = this._gl;
  1605. if (texture._framebuffer) {
  1606. gl.deleteFramebuffer(texture._framebuffer);
  1607. }
  1608. if (texture._depthBuffer) {
  1609. gl.deleteRenderbuffer(texture._depthBuffer);
  1610. }
  1611. gl.deleteTexture(texture);
  1612. // Unbind channels
  1613. this.unbindAllTextures();
  1614. var index = this._loadedTexturesCache.indexOf(texture);
  1615. if (index !== -1) {
  1616. this._loadedTexturesCache.splice(index, 1);
  1617. }
  1618. }
  1619. public bindSamplers(effect: Effect): void {
  1620. this._gl.useProgram(effect.getProgram());
  1621. var samplers = effect.getSamplers();
  1622. for (var index = 0; index < samplers.length; index++) {
  1623. var uniform = effect.getUniform(samplers[index]);
  1624. this._gl.uniform1i(uniform, index);
  1625. }
  1626. this._currentEffect = null;
  1627. }
  1628. public _bindTexture(channel: number, texture: WebGLTexture): void {
  1629. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1630. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1631. this._activeTexturesCache[channel] = null;
  1632. }
  1633. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  1634. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  1635. }
  1636. public unbindAllTextures(): void {
  1637. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  1638. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1639. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1640. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1641. this._activeTexturesCache[channel] = null;
  1642. }
  1643. }
  1644. public setTexture(channel: number, texture: BaseTexture): void {
  1645. if (channel < 0) {
  1646. return;
  1647. }
  1648. // Not ready?
  1649. if (!texture || !texture.isReady()) {
  1650. if (this._activeTexturesCache[channel] != null) {
  1651. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1652. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1653. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1654. this._activeTexturesCache[channel] = null;
  1655. }
  1656. return;
  1657. }
  1658. // Video
  1659. var alreadyActivated = false;
  1660. if (texture instanceof VideoTexture) {
  1661. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1662. alreadyActivated = true;
  1663. texture.update();
  1664. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  1665. texture.delayLoad();
  1666. return;
  1667. }
  1668. if (this._activeTexturesCache[channel] === texture) {
  1669. return;
  1670. }
  1671. this._activeTexturesCache[channel] = texture;
  1672. var internalTexture = texture.getInternalTexture();
  1673. if (!alreadyActivated) {
  1674. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1675. }
  1676. if (internalTexture.isCube) {
  1677. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  1678. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  1679. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  1680. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  1681. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  1682. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  1683. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  1684. }
  1685. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  1686. } else {
  1687. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  1688. if (internalTexture._cachedWrapU !== texture.wrapU) {
  1689. internalTexture._cachedWrapU = texture.wrapU;
  1690. switch (texture.wrapU) {
  1691. case Texture.WRAP_ADDRESSMODE:
  1692. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  1693. break;
  1694. case Texture.CLAMP_ADDRESSMODE:
  1695. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  1696. break;
  1697. case Texture.MIRROR_ADDRESSMODE:
  1698. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  1699. break;
  1700. }
  1701. }
  1702. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1703. internalTexture._cachedWrapV = texture.wrapV;
  1704. switch (texture.wrapV) {
  1705. case Texture.WRAP_ADDRESSMODE:
  1706. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1707. break;
  1708. case Texture.CLAMP_ADDRESSMODE:
  1709. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1710. break;
  1711. case Texture.MIRROR_ADDRESSMODE:
  1712. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1713. break;
  1714. }
  1715. }
  1716. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1717. }
  1718. }
  1719. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  1720. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1721. var value = texture.anisotropicFilteringLevel;
  1722. if (texture.getInternalTexture().samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1723. value = 1;
  1724. }
  1725. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  1726. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  1727. texture._cachedAnisotropicFilteringLevel = value;
  1728. }
  1729. }
  1730. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  1731. var data = new Uint8Array(height * width * 4);
  1732. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1733. return data;
  1734. }
  1735. public releaseInternalTexture(texture: WebGLTexture): void {
  1736. if (!texture) {
  1737. return;
  1738. }
  1739. texture.references--;
  1740. // Final reference ?
  1741. if (texture.references === 0) {
  1742. var texturesCache = this.getLoadedTexturesCache();
  1743. var index = texturesCache.indexOf(texture);
  1744. if (index > -1) {
  1745. texturesCache.splice(index, 1);
  1746. }
  1747. this._releaseTexture(texture);
  1748. }
  1749. }
  1750. // Dispose
  1751. public dispose(): void {
  1752. this.hideLoadingUI();
  1753. this.stopRenderLoop();
  1754. // Release scenes
  1755. while (this.scenes.length) {
  1756. this.scenes[0].dispose();
  1757. }
  1758. // Release audio engine
  1759. Engine.audioEngine.dispose();
  1760. // Release effects
  1761. for (var name in this._compiledEffects) {
  1762. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1763. }
  1764. // Unbind
  1765. for (var i in this._vertexAttribArrays) {
  1766. //making sure this is a string
  1767. var iAsNumber = +i;
  1768. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  1769. continue;
  1770. }
  1771. this._gl.disableVertexAttribArray(iAsNumber);
  1772. }
  1773. this._gl = null;
  1774. // Events
  1775. window.removeEventListener("blur", this._onBlur);
  1776. window.removeEventListener("focus", this._onFocus);
  1777. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1778. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1779. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1780. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1781. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1782. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1783. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1784. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1785. }
  1786. // Loading screen
  1787. public displayLoadingUI(): void {
  1788. this._loadingScreen.displayLoadingUI();
  1789. }
  1790. public hideLoadingUI(): void {
  1791. this._loadingScreen.hideLoadingUI();
  1792. }
  1793. public get loadingScreen(): ILoadingScreen {
  1794. return this._loadingScreen;
  1795. }
  1796. public set loadingScreen(loadingScreen: ILoadingScreen) {
  1797. this._loadingScreen = loadingScreen;
  1798. }
  1799. public set loadingUIText(text: string) {
  1800. this._loadingScreen.loadingUIText = text;
  1801. }
  1802. public set loadingUIBackgroundColor(color: string) {
  1803. this._loadingScreen.loadingUIBackgroundColor = color;
  1804. }
  1805. // FPS
  1806. public getFps(): number {
  1807. return this.fps;
  1808. }
  1809. public getDeltaTime(): number {
  1810. return this.deltaTime;
  1811. }
  1812. private _measureFps(): void {
  1813. this.previousFramesDuration.push(Tools.Now);
  1814. var length = this.previousFramesDuration.length;
  1815. if (length >= 2) {
  1816. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  1817. }
  1818. if (length >= this.fpsRange) {
  1819. if (length > this.fpsRange) {
  1820. this.previousFramesDuration.splice(0, 1);
  1821. length = this.previousFramesDuration.length;
  1822. }
  1823. var sum = 0;
  1824. for (var id = 0; id < length - 1; id++) {
  1825. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  1826. }
  1827. this.fps = 1000.0 / (sum / (length - 1));
  1828. }
  1829. }
  1830. // Statics
  1831. public static isSupported(): boolean {
  1832. try {
  1833. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  1834. if (navigator.isCocoonJS) {
  1835. return true;
  1836. }
  1837. var tempcanvas = document.createElement("canvas");
  1838. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1839. return gl != null && !!window.WebGLRenderingContext;
  1840. } catch (e) {
  1841. return false;
  1842. }
  1843. }
  1844. }
  1845. }