babylon.engine.js 56 KB

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