babylon.engine.ts 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  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. this._gl.getError();
  436. }
  437. // Shaders
  438. public _releaseEffect(effect: Effect): void {
  439. if (this._compiledEffects[effect._key]) {
  440. delete this._compiledEffects[effect._key];
  441. if (effect.getProgram()) {
  442. this._gl.deleteProgram(effect.getProgram());
  443. }
  444. }
  445. }
  446. public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, optionalDefines?: string[],
  447. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  448. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  449. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  450. var name = vertex + "+" + fragment + "@" + defines;
  451. if (this._compiledEffects[name]) {
  452. return this._compiledEffects[name];
  453. }
  454. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, optionalDefines, onCompiled, onError);
  455. effect._key = name;
  456. this._compiledEffects[name] = effect;
  457. return effect;
  458. }
  459. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string): WebGLProgram {
  460. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  461. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  462. var shaderProgram = this._gl.createProgram();
  463. this._gl.attachShader(shaderProgram, vertexShader);
  464. this._gl.attachShader(shaderProgram, fragmentShader);
  465. var linked = this._gl.linkProgram(shaderProgram);
  466. if (!linked) {
  467. var error = this._gl.getProgramInfoLog(shaderProgram);
  468. if (error) {
  469. throw new Error(error);
  470. }
  471. }
  472. this._gl.deleteShader(vertexShader);
  473. this._gl.deleteShader(fragmentShader);
  474. return shaderProgram;
  475. }
  476. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  477. var results = [];
  478. for (var index = 0; index < uniformsNames.length; index++) {
  479. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  480. }
  481. return results;
  482. }
  483. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  484. var results = [];
  485. for (var index = 0; index < attributesNames.length; index++) {
  486. try {
  487. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  488. } catch (e) {
  489. results.push(-1);
  490. }
  491. }
  492. return results;
  493. }
  494. public enableEffect(effect: Effect): void {
  495. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  496. return;
  497. }
  498. // Use program
  499. this._gl.useProgram(effect.getProgram());
  500. var currentCount = effect.getAttributesCount();
  501. var maxIndex = 0;
  502. for (var index = 0; index < currentCount; index++) {
  503. // Attributes
  504. var order = effect.getAttribute(index);
  505. if (order >= 0) {
  506. this._gl.enableVertexAttribArray(effect.getAttribute(index));
  507. maxIndex = Math.max(maxIndex, order);
  508. }
  509. }
  510. for (index = maxIndex + 1; index <= this._lastVertexAttribIndex; index++) {
  511. this._gl.disableVertexAttribArray(index);
  512. }
  513. this._lastVertexAttribIndex = maxIndex;
  514. this._currentEffect = effect;
  515. }
  516. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  517. if (!uniform)
  518. return;
  519. this._gl.uniform1fv(uniform, array);
  520. }
  521. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  522. if (!uniform)
  523. return;
  524. this._gl.uniformMatrix4fv(uniform, false, matrices);
  525. }
  526. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  527. if (!uniform)
  528. return;
  529. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  530. }
  531. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  532. if (!uniform)
  533. return;
  534. this._gl.uniform1f(uniform, value);
  535. }
  536. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  537. if (!uniform)
  538. return;
  539. this._gl.uniform2f(uniform, x, y);
  540. }
  541. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  542. if (!uniform)
  543. return;
  544. this._gl.uniform3f(uniform, x, y, z);
  545. }
  546. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  547. if (!uniform)
  548. return;
  549. this._gl.uniform1i(uniform, bool);
  550. }
  551. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  552. if (!uniform)
  553. return;
  554. this._gl.uniform4f(uniform, x, y, z, w);
  555. }
  556. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  557. if (!uniform)
  558. return;
  559. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  560. }
  561. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  562. if (!uniform)
  563. return;
  564. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  565. }
  566. // States
  567. public setState(culling: boolean): void {
  568. // Culling
  569. if (this._cullingState !== culling) {
  570. if (culling) {
  571. this._gl.cullFace(this.cullBackFaces ? this._gl.BACK : this._gl.FRONT);
  572. this._gl.enable(this._gl.CULL_FACE);
  573. } else {
  574. this._gl.disable(this._gl.CULL_FACE);
  575. }
  576. this._cullingState = culling;
  577. }
  578. }
  579. public setDepthBuffer(enable: boolean): void {
  580. if (enable) {
  581. this._gl.enable(this._gl.DEPTH_TEST);
  582. } else {
  583. this._gl.disable(this._gl.DEPTH_TEST);
  584. }
  585. }
  586. public setDepthWrite(enable: boolean): void {
  587. this._gl.depthMask(enable);
  588. this._depthMask = enable;
  589. }
  590. public setColorWrite(enable: boolean): void {
  591. this._gl.colorMask(enable, enable, enable, enable);
  592. }
  593. public setAlphaMode(mode: number): void {
  594. switch (mode) {
  595. case BABYLON.Engine.ALPHA_DISABLE:
  596. this.setDepthWrite(true);
  597. this._gl.disable(this._gl.BLEND);
  598. break;
  599. case BABYLON.Engine.ALPHA_COMBINE:
  600. this.setDepthWrite(false);
  601. this._gl.blendFuncSeparate(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  602. this._gl.enable(this._gl.BLEND);
  603. break;
  604. case BABYLON.Engine.ALPHA_ADD:
  605. this.setDepthWrite(false);
  606. this._gl.blendFuncSeparate(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  607. this._gl.enable(this._gl.BLEND);
  608. break;
  609. }
  610. }
  611. public setAlphaTesting(enable: boolean): void {
  612. this._alphaTest = enable;
  613. }
  614. public getAlphaTesting(): boolean {
  615. return this._alphaTest;
  616. }
  617. // Textures
  618. public wipeCaches(): void {
  619. this._activeTexturesCache = [];
  620. this._currentEffect = null;
  621. this._cullingState = null;
  622. this._cachedVertexBuffers = null;
  623. this._cachedIndexBuffer = null;
  624. this._cachedEffectForVertexBuffers = null;
  625. }
  626. public createTexture(url: string, noMipmap: boolean, invertY: boolean, scene: Scene): WebGLTexture {
  627. var texture = this._gl.createTexture();
  628. var isDDS = this.getCaps().s3tc && (url.substr(url.length - 4, 4).toLowerCase() === ".dds");
  629. scene._addPendingData(texture);
  630. texture.url = url;
  631. texture.noMipmap = noMipmap;
  632. texture.references = 1;
  633. this._loadedTexturesCache.push(texture);
  634. if (isDDS) {
  635. BABYLON.Tools.LoadFile(url, data => {
  636. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  637. var loadMipmap = info.mipmapCount > 1 && !noMipmap;
  638. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, true, () => {
  639. BABYLON.Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, loadMipmap);
  640. });
  641. }, null, scene.database, true);
  642. } else {
  643. var onload = (img) => {
  644. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight) => {
  645. var isPot = (img.width == potWidth && img.height == potHeight);
  646. if (!isPot) {
  647. this._workingCanvas.width = potWidth;
  648. this._workingCanvas.height = potHeight;
  649. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  650. }
  651. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  652. });
  653. };
  654. var onerror = () => {
  655. scene._removePendingData(texture);
  656. };
  657. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  658. }
  659. return texture;
  660. }
  661. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean): WebGLTexture {
  662. var texture = this._gl.createTexture();
  663. width = getExponantOfTwo(width, this._caps.maxTextureSize);
  664. height = getExponantOfTwo(height, this._caps.maxTextureSize);
  665. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  666. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, this._gl.LINEAR);
  667. if (!generateMipMaps) {
  668. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR);
  669. } else {
  670. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR_MIPMAP_LINEAR);
  671. }
  672. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  673. this._activeTexturesCache = [];
  674. texture._baseWidth = width;
  675. texture._baseHeight = height;
  676. texture._width = width;
  677. texture._height = height;
  678. texture.isReady = false;
  679. texture.generateMipMaps = generateMipMaps;
  680. texture.references = 1;
  681. this._loadedTexturesCache.push(texture);
  682. return texture;
  683. }
  684. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean): void {
  685. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  686. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  687. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  688. if (texture.generateMipMaps) {
  689. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  690. }
  691. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  692. this._activeTexturesCache = [];
  693. texture.isReady = true;
  694. }
  695. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  696. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  697. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  698. // Scale the video if it is a NPOT using the current working canvas
  699. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  700. if (!texture._workingCanvas) {
  701. texture._workingCanvas = document.createElement("canvas");
  702. texture._workingContext = texture._workingCanvas.getContext("2d");
  703. texture._workingCanvas.width = texture._width;
  704. texture._workingCanvas.height = texture._height;
  705. }
  706. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  707. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  708. } else {
  709. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  710. }
  711. if (texture.generateMipMaps) {
  712. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  713. }
  714. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  715. this._activeTexturesCache = [];
  716. texture.isReady = true;
  717. }
  718. public createRenderTargetTexture(size: any, options): WebGLTexture {
  719. // old version had a "generateMipMaps" arg instead of options.
  720. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  721. // in the same way, generateDepthBuffer is defaulted to true
  722. var generateMipMaps = false;
  723. var generateDepthBuffer = true;
  724. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  725. if (options !== undefined) {
  726. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  727. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  728. if (options.samplingMode !== undefined) {
  729. samplingMode = options.samplingMode;
  730. }
  731. }
  732. var gl = this._gl;
  733. var texture = gl.createTexture();
  734. gl.bindTexture(gl.TEXTURE_2D, texture);
  735. var width = size.width || size;
  736. var height = size.height || size;
  737. var magFilter = gl.NEAREST;
  738. var minFilter = gl.NEAREST;
  739. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  740. magFilter = gl.LINEAR;
  741. if (generateMipMaps) {
  742. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  743. } else {
  744. minFilter = gl.LINEAR;
  745. }
  746. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  747. magFilter = gl.LINEAR;
  748. if (generateMipMaps) {
  749. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  750. } else {
  751. minFilter = gl.LINEAR;
  752. }
  753. }
  754. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  755. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  756. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  757. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  758. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  759. var depthBuffer: WebGLRenderbuffer;
  760. // Create the depth buffer
  761. if (generateDepthBuffer) {
  762. depthBuffer = gl.createRenderbuffer();
  763. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  764. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  765. }
  766. // Create the framebuffer
  767. var framebuffer = gl.createFramebuffer();
  768. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  769. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  770. if (generateDepthBuffer) {
  771. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  772. }
  773. // Unbind
  774. gl.bindTexture(gl.TEXTURE_2D, null);
  775. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  776. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  777. texture._framebuffer = framebuffer;
  778. if (generateDepthBuffer) {
  779. texture._depthBuffer = depthBuffer;
  780. }
  781. texture._width = width;
  782. texture._height = height;
  783. texture.isReady = true;
  784. texture.generateMipMaps = generateMipMaps;
  785. texture.references = 1;
  786. this._activeTexturesCache = [];
  787. this._loadedTexturesCache.push(texture);
  788. return texture;
  789. }
  790. public createCubeTexture(rootUrl: string, scene: Scene, extensions: string[], noMipmap?: boolean): WebGLTexture {
  791. var gl = this._gl;
  792. var texture = gl.createTexture();
  793. texture.isCube = true;
  794. texture.url = rootUrl;
  795. texture.references = 1;
  796. this._loadedTexturesCache.push(texture);
  797. cascadeLoad(rootUrl, 0, [], scene, imgs => {
  798. var width = getExponantOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  799. var height = width;
  800. this._workingCanvas.width = width;
  801. this._workingCanvas.height = height;
  802. var faces = [
  803. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  804. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  805. ];
  806. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  807. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  808. for (var index = 0; index < faces.length; index++) {
  809. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  810. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  811. }
  812. if (!noMipmap) {
  813. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  814. }
  815. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  816. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  817. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  819. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  820. this._activeTexturesCache = [];
  821. texture._width = width;
  822. texture._height = height;
  823. texture.isReady = true;
  824. }, extensions);
  825. return texture;
  826. }
  827. public _releaseTexture(texture: WebGLTexture): void {
  828. var gl = this._gl;
  829. if (texture._framebuffer) {
  830. gl.deleteFramebuffer(texture._framebuffer);
  831. }
  832. if (texture._depthBuffer) {
  833. gl.deleteRenderbuffer(texture._depthBuffer);
  834. }
  835. gl.deleteTexture(texture);
  836. // Unbind channels
  837. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  838. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  839. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  840. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  841. this._activeTexturesCache[channel] = null;
  842. }
  843. var index = this._loadedTexturesCache.indexOf(texture);
  844. if (index !== -1) {
  845. this._loadedTexturesCache.splice(index, 1);
  846. }
  847. }
  848. public bindSamplers(effect: Effect): void {
  849. this._gl.useProgram(effect.getProgram());
  850. var samplers = effect.getSamplers();
  851. for (var index = 0; index < samplers.length; index++) {
  852. var uniform = effect.getUniform(samplers[index]);
  853. this._gl.uniform1i(uniform, index);
  854. }
  855. this._currentEffect = null;
  856. }
  857. public _bindTexture(channel: number, texture: WebGLTexture): void {
  858. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  859. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  860. this._activeTexturesCache[channel] = null;
  861. }
  862. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  863. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  864. }
  865. public setTexture(channel: number, texture: Texture): void {
  866. if (channel < 0) {
  867. return;
  868. }
  869. // Not ready?
  870. if (!texture || !texture.isReady()) {
  871. if (this._activeTexturesCache[channel] != null) {
  872. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  873. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  874. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  875. this._activeTexturesCache[channel] = null;
  876. }
  877. return;
  878. }
  879. // Video
  880. if (texture instanceof BABYLON.VideoTexture) {
  881. if ((<VideoTexture>texture).update()) {
  882. this._activeTexturesCache[channel] = null;
  883. }
  884. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  885. texture.delayLoad();
  886. return;
  887. }
  888. if (this._activeTexturesCache[channel] == texture) {
  889. return;
  890. }
  891. this._activeTexturesCache[channel] = texture;
  892. var internalTexture = texture.getInternalTexture();
  893. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  894. if (internalTexture.isCube) {
  895. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  896. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  897. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  898. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  899. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  900. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  901. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  902. }
  903. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  904. } else {
  905. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  906. if (internalTexture._cachedWrapU !== texture.wrapU) {
  907. internalTexture._cachedWrapU = texture.wrapU;
  908. switch (texture.wrapU) {
  909. case BABYLON.Texture.WRAP_ADDRESSMODE:
  910. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  911. break;
  912. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  913. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  914. break;
  915. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  916. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  917. break;
  918. }
  919. }
  920. if (internalTexture._cachedWrapV !== texture.wrapV) {
  921. internalTexture._cachedWrapV = texture.wrapV;
  922. switch (texture.wrapV) {
  923. case BABYLON.Texture.WRAP_ADDRESSMODE:
  924. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  925. break;
  926. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  927. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  928. break;
  929. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  930. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  931. break;
  932. }
  933. }
  934. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  935. }
  936. }
  937. public _setAnisotropicLevel(key: number, texture: Texture) {
  938. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  939. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  940. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  941. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  942. }
  943. }
  944. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  945. var data = new Uint8Array(height * width * 4);
  946. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  947. return data;
  948. }
  949. // Dispose
  950. public dispose(): void {
  951. this.stopRenderLoop();
  952. // Release scenes
  953. while (this.scenes.length) {
  954. this.scenes[0].dispose();
  955. }
  956. // Release effects
  957. for (var name in this._compiledEffects) {
  958. this._gl.deleteProgram(this._compiledEffects[name]._program);
  959. }
  960. // Events
  961. window.removeEventListener("blur", this._onBlur);
  962. window.removeEventListener("focus", this._onFocus);
  963. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  964. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  965. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  966. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  967. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  968. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  969. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  970. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  971. }
  972. // Statics
  973. public static isSupported(): boolean {
  974. try {
  975. var tempcanvas = document.createElement("canvas");
  976. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  977. return gl != null && !!window.WebGLRenderingContext;
  978. } catch (e) {
  979. return false;
  980. }
  981. }
  982. }
  983. }