babylon.engine.js 34 KB

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