babylon.engine.ts 52 KB

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