babylon.engine.ts 48 KB

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