babylon.engine.ts 48 KB

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