babylon.engine.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  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) {
  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, color.a || 1.0);
  151. this._gl.clearDepth(1.0);
  152. var mode = 0;
  153. if (backBuffer)
  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._width, texture._height);
  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, length) {
  211. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  212. // Should be (vertices instanceof Float32Array ? vertices : new Float32Array(vertices)) but Chrome raises an Exception in this case :(
  213. if (length) {
  214. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices, 0, length));
  215. } else {
  216. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  217. }
  218. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  219. };
  220. BABYLON.Engine.prototype.createIndexBuffer = function (indices) {
  221. var vbo = this._gl.createBuffer();
  222. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  223. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  224. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  225. vbo.references = 1;
  226. return vbo;
  227. };
  228. BABYLON.Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  229. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  230. this._cachedVertexBuffers = vertexBuffer;
  231. this._cachedEffectForVertexBuffers = effect;
  232. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  233. var offset = 0;
  234. for (var index = 0; index < vertexDeclaration.length; index++) {
  235. var order = effect.getAttribute(index);
  236. if (order >= 0) {
  237. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  238. }
  239. offset += vertexDeclaration[index] * 4;
  240. }
  241. }
  242. if (this._cachedIndexBuffer !== indexBuffer) {
  243. this._cachedIndexBuffer = indexBuffer;
  244. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  245. }
  246. };
  247. BABYLON.Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  248. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  249. this._cachedVertexBuffers = vertexBuffers;
  250. this._cachedEffectForVertexBuffers = effect;
  251. var attributes = effect.getAttributesNames();
  252. for (var index = 0; index < attributes.length; index++) {
  253. var order = effect.getAttribute(index);
  254. if (order >= 0) {
  255. var vertexBuffer = vertexBuffers[attributes[index]];
  256. var stride = vertexBuffer.getStrideSize();
  257. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer._buffer);
  258. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  259. }
  260. }
  261. }
  262. if (this._cachedIndexBuffer !== indexBuffer) {
  263. this._cachedIndexBuffer = indexBuffer;
  264. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  265. }
  266. };
  267. BABYLON.Engine.prototype._releaseBuffer = function (buffer) {
  268. buffer.references--;
  269. if (buffer.references === 0) {
  270. this._gl.deleteBuffer(buffer);
  271. }
  272. };
  273. BABYLON.Engine.prototype.draw = function (useTriangles, indexStart, indexCount) {
  274. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  275. };
  276. // Shaders
  277. BABYLON.Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, optionalDefines) {
  278. var vertex = baseName.vertex || baseName;
  279. var fragment = baseName.fragment || baseName;
  280. var name = vertex + "+" + fragment + "@" + defines;
  281. if (this._compiledEffects[name]) {
  282. return this._compiledEffects[name];
  283. }
  284. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, optionalDefines);
  285. this._compiledEffects[name] = effect;
  286. return effect;
  287. };
  288. var compileShader = function (gl, source, type, defines) {
  289. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  290. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  291. gl.compileShader(shader);
  292. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  293. throw new Error(gl.getShaderInfoLog(shader));
  294. }
  295. return shader;
  296. };
  297. BABYLON.Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  298. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  299. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  300. var shaderProgram = this._gl.createProgram();
  301. this._gl.attachShader(shaderProgram, vertexShader);
  302. this._gl.attachShader(shaderProgram, fragmentShader);
  303. this._gl.linkProgram(shaderProgram);
  304. var error = this._gl.getProgramInfoLog(shaderProgram);
  305. if (error) {
  306. throw new Error(error);
  307. }
  308. this._gl.deleteShader(vertexShader);
  309. this._gl.deleteShader(fragmentShader);
  310. return shaderProgram;
  311. };
  312. BABYLON.Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  313. var results = [];
  314. for (var index = 0; index < uniformsNames.length; index++) {
  315. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  316. }
  317. return results;
  318. };
  319. BABYLON.Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  320. var results = [];
  321. for (var index = 0; index < attributesNames.length; index++) {
  322. try {
  323. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  324. } catch (e) {
  325. results.push(-1);
  326. }
  327. }
  328. return results;
  329. };
  330. BABYLON.Engine.prototype.enableEffect = function (effect) {
  331. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  332. return;
  333. }
  334. // Use program
  335. this._gl.useProgram(effect.getProgram());
  336. for (var index = 0; index < effect.getAttributesCount() ; index++) {
  337. // Attributes
  338. var order = effect.getAttribute(index);
  339. if (order >= 0) {
  340. this._gl.enableVertexAttribArray(effect.getAttribute(index));
  341. }
  342. }
  343. this._currentEffect = effect;
  344. };
  345. BABYLON.Engine.prototype.setMatrices = function (uniform, matrices) {
  346. if (!uniform)
  347. return;
  348. this._gl.uniformMatrix4fv(uniform, false, matrices);
  349. };
  350. BABYLON.Engine.prototype.setMatrix = function (uniform, matrix) {
  351. if (!uniform)
  352. return;
  353. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  354. };
  355. BABYLON.Engine.prototype.setVector2 = function (uniform, x, y) {
  356. if (!uniform)
  357. return;
  358. this._gl.uniform2f(uniform, x, y);
  359. };
  360. BABYLON.Engine.prototype.setVector3 = function (uniform, vector3) {
  361. if (!uniform)
  362. return;
  363. this._gl.uniform3f(uniform, vector3.x, vector3.y, vector3.z);
  364. };
  365. BABYLON.Engine.prototype.setFloat2 = function (uniform, x, y) {
  366. if (!uniform)
  367. return;
  368. this._gl.uniform2f(uniform, x, y);
  369. };
  370. BABYLON.Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  371. if (!uniform)
  372. return;
  373. this._gl.uniform3f(uniform, x, y, z);
  374. };
  375. BABYLON.Engine.prototype.setFloat = function (uniform, value) {
  376. if (!uniform)
  377. return;
  378. this._gl.uniform1f(uniform, value);
  379. };
  380. BABYLON.Engine.prototype.setBool = function (uniform, bool) {
  381. if (!uniform)
  382. return;
  383. this._gl.uniform1i(uniform, bool);
  384. };
  385. BABYLON.Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  386. if (!uniform)
  387. return;
  388. this._gl.uniform4f(uniform, x, y, z, w);
  389. };
  390. BABYLON.Engine.prototype.setColor3 = function (uniform, color3) {
  391. if (!uniform)
  392. return;
  393. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  394. };
  395. BABYLON.Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  396. if (!uniform)
  397. return;
  398. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  399. };
  400. // States
  401. BABYLON.Engine.prototype.setState = function (culling) {
  402. // Culling
  403. if (this._currentState.culling !== culling) {
  404. if (culling) {
  405. this._gl.cullFace(this.cullBackFaces ? this._gl.BACK : this._gl.FRONT);
  406. this._gl.enable(this._gl.CULL_FACE);
  407. } else {
  408. this._gl.disable(this._gl.CULL_FACE);
  409. }
  410. this._currentState.culling = culling;
  411. }
  412. };
  413. BABYLON.Engine.prototype.setDepthBuffer = function (enable) {
  414. if (enable) {
  415. this._gl.enable(this._gl.DEPTH_TEST);
  416. } else {
  417. this._gl.disable(this._gl.DEPTH_TEST);
  418. }
  419. };
  420. BABYLON.Engine.prototype.setDepthWrite = function (enable) {
  421. this._gl.depthMask(enable);
  422. };
  423. BABYLON.Engine.prototype.setColorWrite = function (enable) {
  424. this._gl.colorMask(enable, enable, enable, enable);
  425. };
  426. BABYLON.Engine.prototype.setAlphaMode = function (mode) {
  427. switch (mode) {
  428. case BABYLON.Engine.ALPHA_DISABLE:
  429. this.setDepthWrite(true);
  430. this._gl.disable(this._gl.BLEND);
  431. break;
  432. case BABYLON.Engine.ALPHA_COMBINE:
  433. this.setDepthWrite(false);
  434. this._gl.blendFuncSeparate(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ZERO, this._gl.ONE);
  435. this._gl.enable(this._gl.BLEND);
  436. break;
  437. case BABYLON.Engine.ALPHA_ADD:
  438. this.setDepthWrite(false);
  439. this._gl.blendFuncSeparate(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  440. this._gl.enable(this._gl.BLEND);
  441. break;
  442. }
  443. };
  444. BABYLON.Engine.prototype.setAlphaTesting = function (enable) {
  445. this._alphaTest = enable;
  446. };
  447. BABYLON.Engine.prototype.getAlphaTesting = function () {
  448. return this._alphaTest;
  449. };
  450. // Textures
  451. BABYLON.Engine.prototype.wipeCaches = function () {
  452. this._activeTexturesCache = [];
  453. this._currentEffect = null;
  454. this._currentState = {
  455. culling: null
  456. };
  457. this._cachedVertexBuffers = null;
  458. this._cachedVertexBuffers = null;
  459. this._cachedEffectForVertexBuffers = null;
  460. };
  461. var getExponantOfTwo = function (value, max) {
  462. var count = 1;
  463. do {
  464. count *= 2;
  465. } while (count < value);
  466. if (count > max)
  467. count = max;
  468. return count;
  469. };
  470. BABYLON.Engine.prototype.createTexture = function (url, noMipmap, invertY, scene) {
  471. var texture = this._gl.createTexture();
  472. var that = this;
  473. var onload = function (img) {
  474. var potWidth = getExponantOfTwo(img.width, that._caps.maxTextureSize);
  475. var potHeight = getExponantOfTwo(img.height, that._caps.maxTextureSize);
  476. var isPot = (img.width == potWidth && img.height == potHeight);
  477. if (!isPot) {
  478. that._workingCanvas.width = potWidth;
  479. that._workingCanvas.height = potHeight;
  480. that._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  481. };
  482. that._gl.bindTexture(that._gl.TEXTURE_2D, texture);
  483. that._gl.pixelStorei(that._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? true : invertY);
  484. that._gl.texImage2D(that._gl.TEXTURE_2D, 0, that._gl.RGBA, that._gl.RGBA, that._gl.UNSIGNED_BYTE, isPot ? img : that._workingCanvas);
  485. that._gl.texParameteri(that._gl.TEXTURE_2D, that._gl.TEXTURE_MAG_FILTER, that._gl.LINEAR);
  486. if (noMipmap) {
  487. that._gl.texParameteri(that._gl.TEXTURE_2D, that._gl.TEXTURE_MIN_FILTER, that._gl.LINEAR);
  488. } else {
  489. that._gl.texParameteri(that._gl.TEXTURE_2D, that._gl.TEXTURE_MIN_FILTER, that._gl.LINEAR_MIPMAP_LINEAR);
  490. that._gl.generateMipmap(that._gl.TEXTURE_2D);
  491. }
  492. that._gl.bindTexture(that._gl.TEXTURE_2D, null);
  493. that._activeTexturesCache = [];
  494. texture._baseWidth = img.width;
  495. texture._baseHeight = img.height;
  496. texture._width = potWidth;
  497. texture._height = potHeight;
  498. texture.isReady = true;
  499. scene._removePendingData(texture);
  500. };
  501. var onerror = function () {
  502. scene._removePendingData(texture);
  503. };
  504. scene._addPendingData(texture);
  505. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  506. texture.url = url;
  507. texture.noMipmap = noMipmap;
  508. texture.references = 1;
  509. this._loadedTexturesCache.push(texture);
  510. return texture;
  511. };
  512. BABYLON.Engine.prototype.createDynamicTexture = function (size, generateMipMaps) {
  513. var texture = this._gl.createTexture();
  514. var width = getExponantOfTwo(size, this._caps.maxTextureSize);
  515. var height = width;
  516. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  517. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, this._gl.LINEAR);
  518. if (!generateMipMaps) {
  519. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR);
  520. } else {
  521. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR_MIPMAP_LINEAR);
  522. }
  523. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  524. this._activeTexturesCache = [];
  525. texture._baseWidth = width;
  526. texture._baseHeight = height;
  527. texture._width = width;
  528. texture._height = height;
  529. texture.isReady = false;
  530. texture.generateMipMaps = generateMipMaps;
  531. texture.references = 1;
  532. this._loadedTexturesCache.push(texture);
  533. return texture;
  534. };
  535. BABYLON.Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  536. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  537. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY);
  538. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  539. if (texture.generateMipMaps) {
  540. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  541. }
  542. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  543. this._activeTexturesCache = [];
  544. texture.isReady = true;
  545. };
  546. BABYLON.Engine.prototype.updateVideoTexture = function (texture, video) {
  547. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  548. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, false);
  549. // Scale the video if it is a NPOT
  550. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  551. if (!texture._workingCanvas) {
  552. texture._workingCanvas = document.createElement("canvas");
  553. texture._workingContext = texture._workingCanvas.getContext("2d");
  554. texture._workingCanvas.width = texture._width;
  555. texture._workingCanvas.height = texture._height;
  556. }
  557. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  558. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  559. } else {
  560. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  561. }
  562. if (texture.generateMipMaps) {
  563. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  564. }
  565. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  566. this._activeTexturesCache = [];
  567. texture.isReady = true;
  568. };
  569. BABYLON.Engine.prototype.createRenderTargetTexture = function (size, generateMipMaps) {
  570. var gl = this._gl;
  571. var texture = gl.createTexture();
  572. gl.bindTexture(gl.TEXTURE_2D, texture);
  573. var width = size.width || size;
  574. var height = size.height || size;
  575. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  576. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, generateMipMaps ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  577. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  578. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  579. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  580. // Create the depth buffer
  581. var depthBuffer = gl.createRenderbuffer();
  582. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  583. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  584. // Create the framebuffer
  585. var framebuffer = gl.createFramebuffer();
  586. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  587. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  588. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  589. // Unbind
  590. gl.bindTexture(gl.TEXTURE_2D, null);
  591. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  592. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  593. texture._framebuffer = framebuffer;
  594. texture._depthBuffer = depthBuffer;
  595. texture._width = width;
  596. texture._height = height;
  597. texture.isReady = true;
  598. texture.generateMipMaps = generateMipMaps;
  599. texture.references = 1;
  600. this._activeTexturesCache = [];
  601. this._loadedTexturesCache.push(texture);
  602. return texture;
  603. };
  604. var extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  605. var cascadeLoad = function (rootUrl, index, loadedImages, scene, onfinish) {
  606. var img;
  607. var onload = function () {
  608. loadedImages.push(img);
  609. scene._removePendingData(img);
  610. if (index != extensions.length - 1) {
  611. cascadeLoad(rootUrl, index + 1, loadedImages, scene, onfinish);
  612. } else {
  613. onfinish(loadedImages);
  614. }
  615. };
  616. var onerror = function () {
  617. scene._removePendingData(img);
  618. };
  619. img = BABYLON.Tools.LoadImage(rootUrl + extensions[index], onload, onerror, scene.database);
  620. scene._addPendingData(img);
  621. };
  622. BABYLON.Engine.prototype.createCubeTexture = function (rootUrl, scene) {
  623. var gl = this._gl;
  624. var texture = gl.createTexture();
  625. texture.isCube = true;
  626. texture.url = rootUrl;
  627. texture.references = 1;
  628. this._loadedTexturesCache.push(texture);
  629. var that = this;
  630. cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
  631. var width = getExponantOfTwo(imgs[0].width);
  632. var height = width;
  633. that._workingCanvas.width = width;
  634. that._workingCanvas.height = height;
  635. var faces = [
  636. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  637. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  638. ];
  639. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  640. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
  641. for (var index = 0; index < faces.length; index++) {
  642. that._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  643. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, that._workingCanvas);
  644. }
  645. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  646. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  647. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
  648. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  649. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  650. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  651. that._activeTexturesCache = [];
  652. texture._width = width;
  653. texture._height = height;
  654. texture.isReady = true;
  655. });
  656. return texture;
  657. };
  658. BABYLON.Engine.prototype._releaseTexture = function (texture) {
  659. var gl = this._gl;
  660. if (texture._framebuffer) {
  661. gl.deleteFramebuffer(texture._framebuffer);
  662. }
  663. if (texture._depthBuffer) {
  664. gl.deleteRenderbuffer(texture._depthBuffer);
  665. }
  666. gl.deleteTexture(texture);
  667. // Unbind channels
  668. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  669. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  670. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  671. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  672. this._activeTexturesCache[channel] = null;
  673. }
  674. };
  675. BABYLON.Engine.prototype.bindSamplers = function (effect) {
  676. this._gl.useProgram(effect.getProgram());
  677. var samplers = effect.getSamplers();
  678. for (var index = 0; index < samplers.length; index++) {
  679. var uniform = effect.getUniform(samplers[index]);
  680. this._gl.uniform1i(uniform, index);
  681. }
  682. this._currentEffect = null;
  683. };
  684. BABYLON.Engine.prototype._bindTexture = function (channel, texture) {
  685. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  686. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  687. this._activeTexturesCache[channel] = null;
  688. };
  689. BABYLON.Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  690. this._bindTexture(channel, postProcess._texture);
  691. };
  692. BABYLON.Engine.prototype.setTexture = function (channel, texture) {
  693. if (channel < 0) {
  694. return;
  695. }
  696. // Not ready?
  697. if (!texture || !texture.isReady()) {
  698. if (this._activeTexturesCache[channel] != null) {
  699. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  700. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  701. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  702. this._activeTexturesCache[channel] = null;
  703. }
  704. return;
  705. }
  706. // Video
  707. if (texture instanceof BABYLON.VideoTexture) {
  708. if (texture._update()) {
  709. this._activeTexturesCache[channel] = null;
  710. }
  711. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  712. texture.delayLoad();
  713. return;
  714. }
  715. if (this._activeTexturesCache[channel] == texture) {
  716. return;
  717. }
  718. this._activeTexturesCache[channel] = texture;
  719. var internalTexture = texture.getInternalTexture();
  720. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  721. if (internalTexture.isCube) {
  722. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  723. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  724. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  725. 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);
  726. 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);
  727. }
  728. } else {
  729. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  730. if (internalTexture._cachedWrapU !== texture.wrapU) {
  731. internalTexture._cachedWrapU = texture.wrapU;
  732. switch (texture.wrapU) {
  733. case BABYLON.Texture.WRAP_ADDRESSMODE:
  734. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  735. break;
  736. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  737. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  738. break;
  739. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  740. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  741. break;
  742. }
  743. }
  744. if (internalTexture._cachedWrapV !== texture.wrapV) {
  745. internalTexture._cachedWrapV = texture.wrapV;
  746. switch (texture.wrapV) {
  747. case BABYLON.Texture.WRAP_ADDRESSMODE:
  748. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  749. break;
  750. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  751. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  752. break;
  753. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  754. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  755. break;
  756. }
  757. }
  758. }
  759. };
  760. // Dispose
  761. BABYLON.Engine.prototype.dispose = function () {
  762. // Release scenes
  763. while (this.scenes.length) {
  764. this.scenes[0].dispose();
  765. }
  766. // Release effects
  767. for (var name in this._compiledEffects.length) {
  768. this._gl.deleteProgram(this._compiledEffects[name]._program);
  769. }
  770. };
  771. // Statics
  772. BABYLON.Engine.ShadersRepository = "Babylon/Shaders/";
  773. BABYLON.Engine.ALPHA_DISABLE = 0;
  774. BABYLON.Engine.ALPHA_ADD = 1;
  775. BABYLON.Engine.ALPHA_COMBINE = 2;
  776. // Statics
  777. BABYLON.Engine.DELAYLOADSTATE_NONE = 0;
  778. BABYLON.Engine.DELAYLOADSTATE_LOADED = 1;
  779. BABYLON.Engine.DELAYLOADSTATE_LOADING = 2;
  780. BABYLON.Engine.DELAYLOADSTATE_NOTLOADED = 4;
  781. BABYLON.Engine.epsilon = 0.001;
  782. BABYLON.Engine.collisionsEpsilon = 0.001;
  783. BABYLON.Engine.isSupported = function () {
  784. try {
  785. var tempcanvas = document.createElement("canvas");
  786. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  787. return gl != null && !!window.WebGLRenderingContext;
  788. } catch (e) {
  789. return false;
  790. }
  791. };
  792. })();