babylon.engine.js 41 KB

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