babylon.engine.ts 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287
  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 getExponantOfTwo = (value: number, max: number): number => {
  12. var count = 1;
  13. do {
  14. count *= 2;
  15. } while (count < value);
  16. if (count > max)
  17. count = max;
  18. return count;
  19. };
  20. var prepareWebGLTexture = (texture: WebGLTexture, gl: WebGLRenderingContext, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  21. processFunction: (width: number, height: number) => void) => {
  22. var engine = scene.getEngine();
  23. var potWidth = getExponantOfTwo(width, engine.getCaps().maxTextureSize);
  24. var potHeight = getExponantOfTwo(height, engine.getCaps().maxTextureSize);
  25. gl.bindTexture(gl.TEXTURE_2D, texture);
  26. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  27. processFunction(potWidth, potHeight);
  28. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  29. if (noMipmap) {
  30. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  31. } else {
  32. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
  33. if (!isCompressed) {
  34. gl.generateMipmap(gl.TEXTURE_2D);
  35. }
  36. }
  37. gl.bindTexture(gl.TEXTURE_2D, null);
  38. engine._activeTexturesCache = [];
  39. texture._baseWidth = width;
  40. texture._baseHeight = height;
  41. texture._width = potWidth;
  42. texture._height = potHeight;
  43. texture.isReady = true;
  44. scene._removePendingData(texture);
  45. };
  46. // ANY
  47. var cascadeLoad = (rootUrl: string, index: number, loadedImages: HTMLImageElement[], scene,
  48. onfinish: (images: HTMLImageElement[]) => void, extensions: string[]) => {
  49. var img: HTMLImageElement;
  50. var onload = () => {
  51. loadedImages.push(img);
  52. scene._removePendingData(img);
  53. if (index != extensions.length - 1) {
  54. cascadeLoad(rootUrl, index + 1, loadedImages, scene, onfinish, extensions);
  55. } else {
  56. onfinish(loadedImages);
  57. }
  58. };
  59. var onerror = () => {
  60. scene._removePendingData(img);
  61. };
  62. img = BABYLON.Tools.LoadImage(rootUrl + extensions[index], onload, onerror, scene.database);
  63. scene._addPendingData(img);
  64. };
  65. export class EngineCapabilities {
  66. public maxTexturesImageUnits: number;
  67. public maxTextureSize: number;
  68. public maxCubemapTextureSize: number;
  69. public maxRenderTextureSize: number;
  70. public standardDerivatives: boolean;
  71. public s3tc;
  72. public textureFloat: boolean;
  73. public textureAnisotropicFilterExtension;
  74. public maxAnisotropy: number;
  75. }
  76. export class Engine {
  77. // Const statics
  78. private static _ALPHA_DISABLE = 0;
  79. private static _ALPHA_ADD = 1;
  80. private static _ALPHA_COMBINE = 2;
  81. private static _DELAYLOADSTATE_NONE = 0;
  82. private static _DELAYLOADSTATE_LOADED = 1;
  83. private static _DELAYLOADSTATE_LOADING = 2;
  84. private static _DELAYLOADSTATE_NOTLOADED = 4;
  85. public static get ALPHA_DISABLE(): number {
  86. return Engine._ALPHA_DISABLE;
  87. }
  88. public static get ALPHA_ADD(): number {
  89. return Engine._ALPHA_ADD;
  90. }
  91. public static get ALPHA_COMBINE(): number {
  92. return Engine._ALPHA_COMBINE;
  93. }
  94. public static get DELAYLOADSTATE_NONE(): number {
  95. return Engine._DELAYLOADSTATE_NONE;
  96. }
  97. public static get DELAYLOADSTATE_LOADED(): number {
  98. return Engine._DELAYLOADSTATE_LOADED;
  99. }
  100. public static get DELAYLOADSTATE_LOADING(): number {
  101. return Engine._DELAYLOADSTATE_LOADING;
  102. }
  103. public static get DELAYLOADSTATE_NOTLOADED(): number {
  104. return Engine._DELAYLOADSTATE_NOTLOADED;
  105. }
  106. // Updatable statics so stick with vars here
  107. public static Epsilon = 0.001;
  108. public static CollisionsEpsilon = 0.001;
  109. public static ShadersRepository = "Babylon/Shaders/";
  110. // Public members
  111. public isFullscreen = false;
  112. public isPointerLock = false;
  113. public forceWireframe = false;
  114. public cullBackFaces = true;
  115. public renderEvenInBackground = true;
  116. public scenes = new Array<Scene>();
  117. // Private Members
  118. private _gl: WebGLRenderingContext;
  119. private _renderingCanvas: HTMLCanvasElement;
  120. private _windowIsBackground = false;
  121. private _onBlur: () => void;
  122. private _onFocus: () => void;
  123. private _onFullscreenChange: () => void;
  124. private _onPointerLockChange: () => void;
  125. private _hardwareScalingLevel: number;
  126. private _caps: EngineCapabilities;
  127. private _pointerLockRequested: boolean;
  128. private _alphaTest: boolean;
  129. private _runningLoop = false;
  130. private _renderFunction: () => void;
  131. // Cache
  132. private _loadedTexturesCache = new Array<WebGLTexture>();
  133. public _activeTexturesCache = new Array<BaseTexture>();
  134. private _currentEffect: Effect;
  135. private _cullingState: boolean;
  136. private _compiledEffects = {};
  137. private _vertexAttribArrays: boolean[];
  138. private _depthMask = false;
  139. private _cachedViewport: Viewport;
  140. private _cachedVertexBuffers: any;
  141. private _cachedIndexBuffer: WebGLBuffer;
  142. private _cachedEffectForVertexBuffers: Effect;
  143. private _currentRenderTarget: WebGLTexture;
  144. private _workingCanvas: HTMLCanvasElement;
  145. private _workingContext: CanvasRenderingContext2D;
  146. constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?) {
  147. this._renderingCanvas = canvas;
  148. options = options || {};
  149. options.antialias = antialias;
  150. // GL
  151. try {
  152. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  153. } catch (e) {
  154. throw new Error("WebGL not supported");
  155. }
  156. if (!this._gl) {
  157. throw new Error("WebGL not supported");
  158. }
  159. this._onBlur = () => {
  160. this._windowIsBackground = true;
  161. };
  162. this._onFocus = () => {
  163. this._windowIsBackground = false;
  164. };
  165. window.addEventListener("blur", this._onBlur);
  166. window.addEventListener("focus", this._onFocus);
  167. // Textures
  168. this._workingCanvas = document.createElement("canvas");
  169. this._workingContext = this._workingCanvas.getContext("2d");
  170. // Viewport
  171. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  172. this.resize();
  173. // Caps
  174. this._caps = new EngineCapabilities();
  175. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  176. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  177. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  178. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  179. // Extensions
  180. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  181. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  182. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  183. 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');
  184. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  185. // Depth buffer
  186. this.setDepthBuffer(true);
  187. this.setDepthFunctionToLessOrEqual();
  188. this.setDepthWrite(true);
  189. // Fullscreen
  190. this._onFullscreenChange = () => {
  191. if (document.fullscreen !== undefined) {
  192. this.isFullscreen = document.fullscreen;
  193. } else if (document.mozFullScreen !== undefined) {
  194. this.isFullscreen = document.mozFullScreen;
  195. } else if (document.webkitIsFullScreen !== undefined) {
  196. this.isFullscreen = document.webkitIsFullScreen;
  197. } else if (document.msIsFullScreen !== undefined) {
  198. this.isFullscreen = document.msIsFullScreen;
  199. }
  200. // Pointer lock
  201. if (this.isFullscreen && this._pointerLockRequested) {
  202. canvas.requestPointerLock = canvas.requestPointerLock ||
  203. canvas.msRequestPointerLock ||
  204. canvas.mozRequestPointerLock ||
  205. canvas.webkitRequestPointerLock;
  206. if (canvas.requestPointerLock) {
  207. canvas.requestPointerLock();
  208. }
  209. }
  210. };
  211. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  212. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  213. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  214. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  215. // Pointer lock
  216. this._onPointerLockChange = () => {
  217. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  218. document.webkitPointerLockElement === canvas ||
  219. document.msPointerLockElement === canvas ||
  220. document.pointerLockElement === canvas
  221. );
  222. };
  223. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  224. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  225. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  226. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  227. }
  228. public getAspectRatio(camera: Camera): number {
  229. var viewport = camera.viewport;
  230. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  231. }
  232. public getRenderWidth(): number {
  233. if (this._currentRenderTarget) {
  234. return this._currentRenderTarget._width;
  235. }
  236. return this._renderingCanvas.width;
  237. }
  238. public getRenderHeight(): number {
  239. if (this._currentRenderTarget) {
  240. return this._currentRenderTarget._height;
  241. }
  242. return this._renderingCanvas.height;
  243. }
  244. public getRenderingCanvas(): HTMLCanvasElement {
  245. return this._renderingCanvas;
  246. }
  247. public setHardwareScalingLevel(level: number): void {
  248. this._hardwareScalingLevel = level;
  249. this.resize();
  250. }
  251. public getHardwareScalingLevel(): number {
  252. return this._hardwareScalingLevel;
  253. }
  254. public getLoadedTexturesCache(): WebGLTexture[] {
  255. return this._loadedTexturesCache;
  256. }
  257. public getCaps(): EngineCapabilities {
  258. return this._caps;
  259. }
  260. // Methods
  261. public setDepthFunctionToGreater(): void {
  262. this._gl.depthFunc(this._gl.GREATER);
  263. }
  264. public setDepthFunctionToGreaterOrEqual(): void {
  265. this._gl.depthFunc(this._gl.GEQUAL);
  266. }
  267. public setDepthFunctionToLess(): void {
  268. this._gl.depthFunc(this._gl.LESS);
  269. }
  270. public setDepthFunctionToLessOrEqual(): void {
  271. this._gl.depthFunc(this._gl.LEQUAL);
  272. }
  273. public stopRenderLoop(): void {
  274. this._renderFunction = null;
  275. this._runningLoop = false;
  276. }
  277. public _renderLoop(): void {
  278. var shouldRender = true;
  279. if (!this.renderEvenInBackground && this._windowIsBackground) {
  280. shouldRender = false;
  281. }
  282. if (shouldRender) {
  283. // Start new frame
  284. this.beginFrame();
  285. if (this._renderFunction) {
  286. this._renderFunction();
  287. }
  288. // Present
  289. this.endFrame();
  290. }
  291. if (this._runningLoop) {
  292. // Register new frame
  293. BABYLON.Tools.QueueNewFrame(() => {
  294. this._renderLoop();
  295. });
  296. }
  297. }
  298. public runRenderLoop(renderFunction: () => void): void {
  299. this._runningLoop = true;
  300. this._renderFunction = renderFunction;
  301. BABYLON.Tools.QueueNewFrame(() => {
  302. this._renderLoop();
  303. });
  304. }
  305. public switchFullscreen(requestPointerLock: boolean): void {
  306. if (this.isFullscreen) {
  307. BABYLON.Tools.ExitFullscreen();
  308. } else {
  309. this._pointerLockRequested = requestPointerLock;
  310. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  311. }
  312. }
  313. public clear(color: any, backBuffer: boolean, depthStencil: boolean): void {
  314. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  315. if (this._depthMask) {
  316. this._gl.clearDepth(1.0);
  317. }
  318. var mode = 0;
  319. if (backBuffer)
  320. mode |= this._gl.COLOR_BUFFER_BIT;
  321. if (depthStencil && this._depthMask)
  322. mode |= this._gl.DEPTH_BUFFER_BIT;
  323. this._gl.clear(mode);
  324. }
  325. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  326. var width = requiredWidth || this._renderingCanvas.width;
  327. var height = requiredHeight || this._renderingCanvas.height;
  328. var x = viewport.x || 0;
  329. var y = viewport.y || 0;
  330. this._cachedViewport = viewport;
  331. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  332. }
  333. public setDirectViewport(x: number, y: number, width: number, height: number): void {
  334. this._cachedViewport = null;
  335. this._gl.viewport(x, y, width, height);
  336. }
  337. public beginFrame(): void {
  338. BABYLON.Tools._MeasureFps();
  339. }
  340. public endFrame(): void {
  341. this.flushFramebuffer();
  342. }
  343. public resize(): void {
  344. this._renderingCanvas.width = this._renderingCanvas.clientWidth / this._hardwareScalingLevel;
  345. this._renderingCanvas.height = this._renderingCanvas.clientHeight / this._hardwareScalingLevel;
  346. }
  347. public bindFramebuffer(texture: WebGLTexture): void {
  348. this._currentRenderTarget = texture;
  349. var gl = this._gl;
  350. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  351. this._gl.viewport(0, 0, texture._width, texture._height);
  352. this.wipeCaches();
  353. }
  354. public unBindFramebuffer(texture: WebGLTexture): void {
  355. this._currentRenderTarget = null;
  356. if (texture.generateMipMaps) {
  357. var gl = this._gl;
  358. gl.bindTexture(gl.TEXTURE_2D, texture);
  359. gl.generateMipmap(gl.TEXTURE_2D);
  360. gl.bindTexture(gl.TEXTURE_2D, null);
  361. }
  362. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  363. }
  364. public flushFramebuffer(): void {
  365. this._gl.flush();
  366. }
  367. public restoreDefaultFramebuffer(): void {
  368. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  369. this.setViewport(this._cachedViewport);
  370. this.wipeCaches();
  371. }
  372. // VBOs
  373. private _resetVertexBufferBinding(): void {
  374. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  375. this._cachedVertexBuffers = null;
  376. }
  377. public createVertexBuffer(vertices: number[]): WebGLBuffer {
  378. var vbo = this._gl.createBuffer();
  379. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  380. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  381. this._resetVertexBufferBinding();
  382. vbo.references = 1;
  383. return vbo;
  384. }
  385. public createDynamicVertexBuffer(capacity: number): WebGLBuffer {
  386. var vbo = this._gl.createBuffer();
  387. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  388. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  389. this._resetVertexBufferBinding();
  390. vbo.references = 1;
  391. return vbo;
  392. }
  393. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: any, length?: number): void {
  394. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  395. //if (length && length != vertices.length) {
  396. // this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices, 0, length));
  397. //} else {
  398. if (vertices instanceof Float32Array) {
  399. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  400. } else {
  401. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  402. }
  403. // }
  404. this._resetVertexBufferBinding();
  405. }
  406. private _resetIndexBufferBinding(): void {
  407. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  408. this._cachedIndexBuffer = null;
  409. }
  410. public createIndexBuffer(indices: number[]): WebGLBuffer {
  411. var vbo = this._gl.createBuffer();
  412. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  413. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  414. this._resetIndexBufferBinding();
  415. vbo.references = 1;
  416. return vbo;
  417. }
  418. public bindBuffers(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  419. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  420. this._cachedVertexBuffers = vertexBuffer;
  421. this._cachedEffectForVertexBuffers = effect;
  422. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  423. var offset = 0;
  424. for (var index = 0; index < vertexDeclaration.length; index++) {
  425. var order = effect.getAttribute(index);
  426. if (order >= 0) {
  427. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  428. }
  429. offset += vertexDeclaration[index] * 4;
  430. }
  431. }
  432. if (this._cachedIndexBuffer !== indexBuffer) {
  433. this._cachedIndexBuffer = indexBuffer;
  434. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  435. }
  436. }
  437. public bindMultiBuffers(vertexBuffers: VertexBuffer[], indexBuffer: WebGLBuffer, effect: Effect): void {
  438. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  439. this._cachedVertexBuffers = vertexBuffers;
  440. this._cachedEffectForVertexBuffers = effect;
  441. var attributes = effect.getAttributesNames();
  442. for (var index = 0; index < attributes.length; index++) {
  443. var order = effect.getAttribute(index);
  444. if (order >= 0) {
  445. var vertexBuffer = vertexBuffers[attributes[index]];
  446. var stride = vertexBuffer.getStrideSize();
  447. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  448. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  449. }
  450. }
  451. }
  452. if (this._cachedIndexBuffer !== indexBuffer) {
  453. this._cachedIndexBuffer = indexBuffer;
  454. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  455. }
  456. }
  457. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  458. buffer.references--;
  459. if (buffer.references === 0) {
  460. this._gl.deleteBuffer(buffer);
  461. return true;
  462. }
  463. return false;
  464. }
  465. public draw(useTriangles: boolean, indexStart: number, indexCount: number): void {
  466. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  467. }
  468. // Shaders
  469. public _releaseEffect(effect: Effect): void {
  470. if (this._compiledEffects[effect._key]) {
  471. delete this._compiledEffects[effect._key];
  472. if (effect.getProgram()) {
  473. this._gl.deleteProgram(effect.getProgram());
  474. }
  475. }
  476. }
  477. public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, optionalDefines?: string[],
  478. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  479. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  480. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  481. var name = vertex + "+" + fragment + "@" + defines;
  482. if (this._compiledEffects[name]) {
  483. return this._compiledEffects[name];
  484. }
  485. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, optionalDefines, onCompiled, onError);
  486. effect._key = name;
  487. this._compiledEffects[name] = effect;
  488. return effect;
  489. }
  490. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string): WebGLProgram {
  491. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  492. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  493. var shaderProgram = this._gl.createProgram();
  494. this._gl.attachShader(shaderProgram, vertexShader);
  495. this._gl.attachShader(shaderProgram, fragmentShader);
  496. this._gl.linkProgram(shaderProgram);
  497. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  498. if (!linked) {
  499. var error = this._gl.getProgramInfoLog(shaderProgram);
  500. if (error) {
  501. throw new Error(error);
  502. }
  503. }
  504. this._gl.deleteShader(vertexShader);
  505. this._gl.deleteShader(fragmentShader);
  506. return shaderProgram;
  507. }
  508. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  509. var results = [];
  510. for (var index = 0; index < uniformsNames.length; index++) {
  511. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  512. }
  513. return results;
  514. }
  515. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  516. var results = [];
  517. for (var index = 0; index < attributesNames.length; index++) {
  518. try {
  519. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  520. } catch (e) {
  521. results.push(-1);
  522. }
  523. }
  524. return results;
  525. }
  526. public enableEffect(effect: Effect): void {
  527. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  528. return;
  529. }
  530. this._vertexAttribArrays = this._vertexAttribArrays || [];
  531. // Use program
  532. this._gl.useProgram(effect.getProgram());
  533. for (var i in this._vertexAttribArrays) {
  534. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  535. continue;
  536. }
  537. this._vertexAttribArrays[i] = false;
  538. this._gl.disableVertexAttribArray(i);
  539. }
  540. var attributesCount = effect.getAttributesCount();
  541. for (var index = 0; index < attributesCount; index++) {
  542. // Attributes
  543. var order = effect.getAttribute(index);
  544. if (order >= 0) {
  545. this._vertexAttribArrays[order] = true;
  546. this._gl.enableVertexAttribArray(order);
  547. }
  548. }
  549. this._currentEffect = effect;
  550. }
  551. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  552. if (!uniform)
  553. return;
  554. this._gl.uniform1fv(uniform, array);
  555. }
  556. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  557. if (!uniform)
  558. return;
  559. this._gl.uniformMatrix4fv(uniform, false, matrices);
  560. }
  561. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  562. if (!uniform)
  563. return;
  564. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  565. }
  566. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  567. if (!uniform)
  568. return;
  569. this._gl.uniform1f(uniform, value);
  570. }
  571. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  572. if (!uniform)
  573. return;
  574. this._gl.uniform2f(uniform, x, y);
  575. }
  576. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  577. if (!uniform)
  578. return;
  579. this._gl.uniform3f(uniform, x, y, z);
  580. }
  581. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  582. if (!uniform)
  583. return;
  584. this._gl.uniform1i(uniform, bool);
  585. }
  586. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  587. if (!uniform)
  588. return;
  589. this._gl.uniform4f(uniform, x, y, z, w);
  590. }
  591. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  592. if (!uniform)
  593. return;
  594. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  595. }
  596. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  597. if (!uniform)
  598. return;
  599. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  600. }
  601. // States
  602. public setState(culling: boolean): void {
  603. // Culling
  604. if (this._cullingState !== culling) {
  605. if (culling) {
  606. this._gl.cullFace(this.cullBackFaces ? this._gl.BACK : this._gl.FRONT);
  607. this._gl.enable(this._gl.CULL_FACE);
  608. } else {
  609. this._gl.disable(this._gl.CULL_FACE);
  610. }
  611. this._cullingState = culling;
  612. }
  613. }
  614. public setDepthBuffer(enable: boolean): void {
  615. if (enable) {
  616. this._gl.enable(this._gl.DEPTH_TEST);
  617. } else {
  618. this._gl.disable(this._gl.DEPTH_TEST);
  619. }
  620. }
  621. public setDepthWrite(enable: boolean): void {
  622. this._gl.depthMask(enable);
  623. this._depthMask = enable;
  624. }
  625. public setColorWrite(enable: boolean): void {
  626. this._gl.colorMask(enable, enable, enable, enable);
  627. }
  628. public setAlphaMode(mode: number): void {
  629. switch (mode) {
  630. case BABYLON.Engine.ALPHA_DISABLE:
  631. this.setDepthWrite(true);
  632. this._gl.disable(this._gl.BLEND);
  633. break;
  634. case BABYLON.Engine.ALPHA_COMBINE:
  635. this.setDepthWrite(false);
  636. this._gl.blendFuncSeparate(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  637. this._gl.enable(this._gl.BLEND);
  638. break;
  639. case BABYLON.Engine.ALPHA_ADD:
  640. this.setDepthWrite(false);
  641. this._gl.blendFuncSeparate(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  642. this._gl.enable(this._gl.BLEND);
  643. break;
  644. }
  645. }
  646. public setAlphaTesting(enable: boolean): void {
  647. this._alphaTest = enable;
  648. }
  649. public getAlphaTesting(): boolean {
  650. return this._alphaTest;
  651. }
  652. // Textures
  653. public wipeCaches(): void {
  654. this._activeTexturesCache = [];
  655. this._currentEffect = null;
  656. this._cullingState = null;
  657. this._cachedVertexBuffers = null;
  658. this._cachedIndexBuffer = null;
  659. this._cachedEffectForVertexBuffers = null;
  660. }
  661. public createTexture(url: string, noMipmap: boolean, invertY: boolean, scene: Scene): WebGLTexture {
  662. var texture = this._gl.createTexture();
  663. var extension = url.substr(url.length - 4, 4).toLowerCase();
  664. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  665. var isTGA = (extension === ".tga");
  666. scene._addPendingData(texture);
  667. texture.url = url;
  668. texture.noMipmap = noMipmap;
  669. texture.references = 1;
  670. this._loadedTexturesCache.push(texture);
  671. if (isTGA) {
  672. BABYLON.Tools.LoadFile(url, arrayBuffer => {
  673. var data = new Uint8Array(arrayBuffer);
  674. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  675. prepareWebGLTexture(texture, this._gl, scene, header.width, header.height, invertY, noMipmap, false, () => {
  676. Internals.TGATools.UploadContent(this._gl, data);
  677. });
  678. }, null, scene.database, true);
  679. } else if (isDDS) {
  680. BABYLON.Tools.LoadFile(url, data => {
  681. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  682. var loadMipmap = info.mipmapCount > 1 && !noMipmap;
  683. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, true, () => {
  684. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, loadMipmap);
  685. });
  686. }, null, scene.database, true);
  687. } else {
  688. var onload = (img) => {
  689. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight) => {
  690. var isPot = (img.width == potWidth && img.height == potHeight);
  691. if (!isPot) {
  692. this._workingCanvas.width = potWidth;
  693. this._workingCanvas.height = potHeight;
  694. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  695. }
  696. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  697. });
  698. };
  699. var onerror = () => {
  700. scene._removePendingData(texture);
  701. };
  702. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  703. }
  704. return texture;
  705. }
  706. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean): WebGLTexture {
  707. var texture = this._gl.createTexture();
  708. width = getExponantOfTwo(width, this._caps.maxTextureSize);
  709. height = getExponantOfTwo(height, this._caps.maxTextureSize);
  710. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  711. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, this._gl.LINEAR);
  712. if (!generateMipMaps) {
  713. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR);
  714. } else {
  715. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR_MIPMAP_LINEAR);
  716. }
  717. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  718. this._activeTexturesCache = [];
  719. texture._baseWidth = width;
  720. texture._baseHeight = height;
  721. texture._width = width;
  722. texture._height = height;
  723. texture.isReady = false;
  724. texture.generateMipMaps = generateMipMaps;
  725. texture.references = 1;
  726. this._loadedTexturesCache.push(texture);
  727. return texture;
  728. }
  729. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean): void {
  730. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  731. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  732. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  733. if (texture.generateMipMaps) {
  734. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  735. }
  736. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  737. this._activeTexturesCache = [];
  738. texture.isReady = true;
  739. }
  740. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  741. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  742. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  743. // Scale the video if it is a NPOT using the current working canvas
  744. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  745. if (!texture._workingCanvas) {
  746. texture._workingCanvas = document.createElement("canvas");
  747. texture._workingContext = texture._workingCanvas.getContext("2d");
  748. texture._workingCanvas.width = texture._width;
  749. texture._workingCanvas.height = texture._height;
  750. }
  751. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  752. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  753. } else {
  754. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  755. }
  756. if (texture.generateMipMaps) {
  757. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  758. }
  759. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  760. this._activeTexturesCache = [];
  761. texture.isReady = true;
  762. }
  763. public createRenderTargetTexture(size: any, options): WebGLTexture {
  764. // old version had a "generateMipMaps" arg instead of options.
  765. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  766. // in the same way, generateDepthBuffer is defaulted to true
  767. var generateMipMaps = false;
  768. var generateDepthBuffer = true;
  769. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  770. if (options !== undefined) {
  771. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  772. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  773. if (options.samplingMode !== undefined) {
  774. samplingMode = options.samplingMode;
  775. }
  776. }
  777. var gl = this._gl;
  778. var texture = gl.createTexture();
  779. gl.bindTexture(gl.TEXTURE_2D, texture);
  780. var width = size.width || size;
  781. var height = size.height || size;
  782. var magFilter = gl.NEAREST;
  783. var minFilter = gl.NEAREST;
  784. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  785. magFilter = gl.LINEAR;
  786. if (generateMipMaps) {
  787. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  788. } else {
  789. minFilter = gl.LINEAR;
  790. }
  791. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  792. magFilter = gl.LINEAR;
  793. if (generateMipMaps) {
  794. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  795. } else {
  796. minFilter = gl.LINEAR;
  797. }
  798. }
  799. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  800. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  801. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  802. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  803. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  804. var depthBuffer: WebGLRenderbuffer;
  805. // Create the depth buffer
  806. if (generateDepthBuffer) {
  807. depthBuffer = gl.createRenderbuffer();
  808. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  809. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  810. }
  811. // Create the framebuffer
  812. var framebuffer = gl.createFramebuffer();
  813. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  814. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  815. if (generateDepthBuffer) {
  816. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  817. }
  818. // Unbind
  819. gl.bindTexture(gl.TEXTURE_2D, null);
  820. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  821. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  822. texture._framebuffer = framebuffer;
  823. if (generateDepthBuffer) {
  824. texture._depthBuffer = depthBuffer;
  825. }
  826. texture._width = width;
  827. texture._height = height;
  828. texture.isReady = true;
  829. texture.generateMipMaps = generateMipMaps;
  830. texture.references = 1;
  831. this._activeTexturesCache = [];
  832. this._loadedTexturesCache.push(texture);
  833. return texture;
  834. }
  835. public createCubeTexture(rootUrl: string, scene: Scene, extensions: string[], noMipmap?: boolean): WebGLTexture {
  836. var gl = this._gl;
  837. var texture = gl.createTexture();
  838. texture.isCube = true;
  839. texture.url = rootUrl;
  840. texture.references = 1;
  841. this._loadedTexturesCache.push(texture);
  842. cascadeLoad(rootUrl, 0, [], scene, imgs => {
  843. var width = getExponantOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  844. var height = width;
  845. this._workingCanvas.width = width;
  846. this._workingCanvas.height = height;
  847. var faces = [
  848. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  849. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  850. ];
  851. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  852. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  853. for (var index = 0; index < faces.length; index++) {
  854. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  855. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  856. }
  857. if (!noMipmap) {
  858. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  859. }
  860. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  861. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  862. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  863. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  864. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  865. this._activeTexturesCache = [];
  866. texture._width = width;
  867. texture._height = height;
  868. texture.isReady = true;
  869. }, extensions);
  870. return texture;
  871. }
  872. public _releaseTexture(texture: WebGLTexture): void {
  873. var gl = this._gl;
  874. if (texture._framebuffer) {
  875. gl.deleteFramebuffer(texture._framebuffer);
  876. }
  877. if (texture._depthBuffer) {
  878. gl.deleteRenderbuffer(texture._depthBuffer);
  879. }
  880. gl.deleteTexture(texture);
  881. // Unbind channels
  882. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  883. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  884. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  885. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  886. this._activeTexturesCache[channel] = null;
  887. }
  888. var index = this._loadedTexturesCache.indexOf(texture);
  889. if (index !== -1) {
  890. this._loadedTexturesCache.splice(index, 1);
  891. }
  892. }
  893. public bindSamplers(effect: Effect): void {
  894. this._gl.useProgram(effect.getProgram());
  895. var samplers = effect.getSamplers();
  896. for (var index = 0; index < samplers.length; index++) {
  897. var uniform = effect.getUniform(samplers[index]);
  898. this._gl.uniform1i(uniform, index);
  899. }
  900. this._currentEffect = null;
  901. }
  902. public _bindTexture(channel: number, texture: WebGLTexture): void {
  903. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  904. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  905. this._activeTexturesCache[channel] = null;
  906. }
  907. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  908. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  909. }
  910. public setTexture(channel: number, texture: BaseTexture): void {
  911. if (channel < 0) {
  912. return;
  913. }
  914. // Not ready?
  915. if (!texture || !texture.isReady()) {
  916. if (this._activeTexturesCache[channel] != null) {
  917. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  918. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  919. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  920. this._activeTexturesCache[channel] = null;
  921. }
  922. return;
  923. }
  924. // Video
  925. if (texture instanceof BABYLON.VideoTexture) {
  926. if ((<VideoTexture>texture).update()) {
  927. this._activeTexturesCache[channel] = null;
  928. }
  929. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  930. texture.delayLoad();
  931. return;
  932. }
  933. if (this._activeTexturesCache[channel] == texture) {
  934. return;
  935. }
  936. this._activeTexturesCache[channel] = texture;
  937. var internalTexture = texture.getInternalTexture();
  938. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  939. if (internalTexture.isCube) {
  940. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  941. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  942. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  943. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  944. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  945. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  946. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  947. }
  948. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  949. } else {
  950. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  951. if (internalTexture._cachedWrapU !== texture.wrapU) {
  952. internalTexture._cachedWrapU = texture.wrapU;
  953. switch (texture.wrapU) {
  954. case BABYLON.Texture.WRAP_ADDRESSMODE:
  955. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  956. break;
  957. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  958. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  959. break;
  960. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  961. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  962. break;
  963. }
  964. }
  965. if (internalTexture._cachedWrapV !== texture.wrapV) {
  966. internalTexture._cachedWrapV = texture.wrapV;
  967. switch (texture.wrapV) {
  968. case BABYLON.Texture.WRAP_ADDRESSMODE:
  969. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  970. break;
  971. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  972. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  973. break;
  974. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  975. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  976. break;
  977. }
  978. }
  979. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  980. }
  981. }
  982. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  983. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  984. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  985. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  986. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  987. }
  988. }
  989. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  990. var data = new Uint8Array(height * width * 4);
  991. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  992. return data;
  993. }
  994. // Dispose
  995. public dispose(): void {
  996. this.stopRenderLoop();
  997. // Release scenes
  998. while (this.scenes.length) {
  999. this.scenes[0].dispose();
  1000. }
  1001. // Release effects
  1002. for (var name in this._compiledEffects) {
  1003. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1004. }
  1005. // Events
  1006. window.removeEventListener("blur", this._onBlur);
  1007. window.removeEventListener("focus", this._onFocus);
  1008. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1009. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1010. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1011. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1012. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1013. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1014. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1015. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1016. }
  1017. // Statics
  1018. public static isSupported(): boolean {
  1019. try {
  1020. var tempcanvas = document.createElement("canvas");
  1021. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1022. return gl != null && !!window.WebGLRenderingContext;
  1023. } catch (e) {
  1024. return false;
  1025. }
  1026. }
  1027. }
  1028. }